org.el 900 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687
  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.2
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (eval-and-compile (require 'org-macs))
  84. (require 'org-compat)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  104. (declare-function org-agenda-redo "org-agenda" (&optional all))
  105. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  106. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  107. (declare-function org-archive-subtree-default "org-archive" ())
  108. (declare-function org-archive-to-archive-sibling "org-archive" ())
  109. (declare-function org-attach "org-attach" ())
  110. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  111. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  112. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  113. (declare-function org-clock-cancel "org-clock" ())
  114. (declare-function org-clock-display "org-clock" (&optional arg))
  115. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  116. (declare-function org-clock-goto "org-clock" (&optional select))
  117. (declare-function org-clock-in "org-clock" (&optional select start-time))
  118. (declare-function org-clock-in-last "org-clock" (&optional arg))
  119. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  120. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  121. (declare-function org-clock-report "org-clock" (&optional arg))
  122. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  123. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  124. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  125. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  126. (declare-function org-clock-update-time-maybe "org-clock" ())
  127. (declare-function org-clocking-buffer "org-clock" ())
  128. (declare-function org-clocktable-shift "org-clock" (dir n))
  129. (declare-function org-columns-insert-dblock "org-colview" ())
  130. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  131. (declare-function org-element-at-point "org-element" ())
  132. (declare-function org-element-cache-refresh "org-element" (pos))
  133. (declare-function org-element-cache-reset "org-element" (&optional all))
  134. (declare-function org-element-contents "org-element" (element))
  135. (declare-function org-element-context "org-element" (&optional element))
  136. (declare-function org-element-copy "org-element" (datum))
  137. (declare-function org-element-create "org-element" (type &optional props &rest children))
  138. (declare-function org-element-interpret-data "org-element" (data))
  139. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  140. (declare-function org-element-link-parser "org-element" ())
  141. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  142. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  143. (declare-function org-element-property "org-element" (property element))
  144. (declare-function org-element-put-property "org-element" (element property value))
  145. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  146. (declare-function org-element-timestamp-parser "org-element" ())
  147. (declare-function org-element-type "org-element" (element))
  148. (declare-function org-element-update-syntax "org-element" ())
  149. (declare-function org-export-dispatch "ox" (&optional arg))
  150. (declare-function org-export-get-backend "ox" (name))
  151. (declare-function org-export-get-backend "ox" (name))
  152. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  153. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  154. (declare-function org-feed-goto-inbox "org-feed" (feed))
  155. (declare-function org-feed-update-all "org-feed" ())
  156. (declare-function org-goto "org-goto" (&optional alternative-interface))
  157. (declare-function org-goto "org-goto" (&optional alternative-interface))
  158. (declare-function org-id-find-id-file "org-id" (id))
  159. (declare-function org-id-get-create "org-id" (&optional force))
  160. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  161. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  162. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  163. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  166. (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
  167. (declare-function org-table-align "org-table" ())
  168. (declare-function org-table-begin "org-table" (&optional table-type))
  169. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  170. (declare-function org-table-blank-field "org-table" ())
  171. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  172. (declare-function org-table-copy-down "org-table" (N))
  173. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  174. (declare-function org-table-create-or-convert-from-region "org-table" (arg))
  175. (declare-function org-table-create-with-table.el "org-table" ())
  176. (declare-function org-table-cut-region "org-table" (beg end))
  177. (declare-function org-table-edit-field "org-table" (arg))
  178. (declare-function org-table-end "org-table" (&optional table-type))
  179. (declare-function org-table-end-of-field "org-table" (&optional n))
  180. (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
  181. (declare-function org-table-field-info "org-table" (arg))
  182. (declare-function org-table-insert-row "org-table" (&optional arg))
  183. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  184. (declare-function org-table-maybe-eval-formula "org-table" ())
  185. (declare-function org-table-maybe-recalculate-line "org-table" ())
  186. (declare-function org-table-next-row "org-table" ())
  187. (declare-function org-table-paste-rectangle "org-table" ())
  188. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  189. (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
  190. (declare-function org-table-shrink "org-table" (&optional begin end))
  191. (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
  192. (declare-function org-table-sum "org-table" (&optional beg end nlast))
  193. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  194. (declare-function org-table-toggle-coordinate-overlays "org-table" ())
  195. (declare-function org-table-toggle-formula-debugger "org-table" ())
  196. (declare-function org-table-wrap-region "org-table" (arg))
  197. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  198. (declare-function org-timer "org-timer" (&optional restart no-insert))
  199. (declare-function org-timer-item "org-timer" (&optional arg))
  200. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  201. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  202. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  203. (declare-function org-timer-start "org-timer" (&optional offset))
  204. (declare-function org-timer-stop "org-timer" ())
  205. (declare-function org-timer-stop "org-timer" ())
  206. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  207. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  208. (declare-function orgtbl-mode "org-table" (&optional arg))
  209. (defvar ffap-url-regexp)
  210. (defvar org-element-paragraph-separate)
  211. (defvar org-indent-indentation-per-level)
  212. ;; load languages based on value of `org-babel-load-languages'
  213. (defvar org-babel-load-languages)
  214. ;;;###autoload
  215. (defun org-babel-do-load-languages (sym value)
  216. "Load the languages defined in `org-babel-load-languages'."
  217. (set-default sym value)
  218. (dolist (pair org-babel-load-languages)
  219. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  220. (if active
  221. (require (intern (concat "ob-" lang)))
  222. (fmakunbound
  223. (intern (concat "org-babel-execute:" lang)))
  224. (fmakunbound
  225. (intern (concat "org-babel-expand-body:" lang)))))))
  226. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  227. ;;;###autoload
  228. (defun org-babel-load-file (file &optional compile)
  229. "Load Emacs Lisp source code blocks in the Org FILE.
  230. This function exports the source code using `org-babel-tangle'
  231. and then loads the resulting file using `load-file'. With prefix
  232. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  233. file to byte-code before it is loaded."
  234. (interactive "fFile to load: \nP")
  235. (let* ((age (lambda (file)
  236. (float-time
  237. (time-subtract (current-time)
  238. (nth 5 (or (file-attributes (file-truename file))
  239. (file-attributes file)))))))
  240. (base-name (file-name-sans-extension file))
  241. (exported-file (concat base-name ".el")))
  242. ;; tangle if the Org file is newer than the elisp file
  243. (unless (and (file-exists-p exported-file)
  244. (> (funcall age file) (funcall age exported-file)))
  245. ;; Tangle-file traversal returns reversed list of tangled files
  246. ;; and we want to evaluate the first target.
  247. (setq exported-file
  248. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  249. (message "%s %s"
  250. (if compile
  251. (progn (byte-compile-file exported-file 'load)
  252. "Compiled and loaded")
  253. (progn (load-file exported-file) "Loaded"))
  254. exported-file)))
  255. (defcustom org-babel-load-languages '((emacs-lisp . t))
  256. "Languages which can be evaluated in Org buffers.
  257. \\<org-mode-map>
  258. This list can be used to load support for any of the languages
  259. below. Each language will depend on a different set of system
  260. executables and/or Emacs modes.
  261. When a language is \"loaded\", code blocks in that language can
  262. be evaluated with `org-babel-execute-src-block', which is bound
  263. by default to \\[org-ctrl-c-ctrl-c].
  264. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  265. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  266. default, only Emacs Lisp is loaded, since it has no specific
  267. requirement."
  268. :group 'org-babel
  269. :set 'org-babel-do-load-languages
  270. :version "24.1"
  271. :type '(alist :tag "Babel Languages"
  272. :key-type
  273. (choice
  274. (const :tag "Awk" awk)
  275. (const :tag "C" C)
  276. (const :tag "R" R)
  277. (const :tag "Asymptote" asymptote)
  278. (const :tag "Calc" calc)
  279. (const :tag "Clojure" clojure)
  280. (const :tag "CSS" css)
  281. (const :tag "Ditaa" ditaa)
  282. (const :tag "Dot" dot)
  283. (const :tag "Ebnf2ps" ebnf2ps)
  284. (const :tag "Emacs Lisp" emacs-lisp)
  285. (const :tag "Forth" forth)
  286. (const :tag "Fortran" fortran)
  287. (const :tag "Gnuplot" gnuplot)
  288. (const :tag "Haskell" haskell)
  289. (const :tag "hledger" hledger)
  290. (const :tag "IO" io)
  291. (const :tag "J" J)
  292. (const :tag "Java" java)
  293. (const :tag "Javascript" js)
  294. (const :tag "LaTeX" latex)
  295. (const :tag "Ledger" ledger)
  296. (const :tag "Lilypond" lilypond)
  297. (const :tag "Lisp" lisp)
  298. (const :tag "Makefile" makefile)
  299. (const :tag "Maxima" maxima)
  300. (const :tag "Matlab" matlab)
  301. (const :tag "Mscgen" mscgen)
  302. (const :tag "Ocaml" ocaml)
  303. (const :tag "Octave" octave)
  304. (const :tag "Org" org)
  305. (const :tag "Perl" perl)
  306. (const :tag "Pico Lisp" picolisp)
  307. (const :tag "PlantUML" plantuml)
  308. (const :tag "Python" python)
  309. (const :tag "Ruby" ruby)
  310. (const :tag "Sass" sass)
  311. (const :tag "Scala" scala)
  312. (const :tag "Scheme" scheme)
  313. (const :tag "Screen" screen)
  314. (const :tag "Shell Script" shell)
  315. (const :tag "Shen" shen)
  316. (const :tag "Sql" sql)
  317. (const :tag "Sqlite" sqlite)
  318. (const :tag "Stan" stan)
  319. (const :tag "Vala" vala))
  320. :value-type (boolean :tag "Activate" :value t)))
  321. ;;;; Customization variables
  322. (defcustom org-clone-delete-id nil
  323. "Remove ID property of clones of a subtree.
  324. When non-nil, clones of a subtree don't inherit the ID property.
  325. Otherwise they inherit the ID property with a new unique
  326. identifier."
  327. :type 'boolean
  328. :version "24.1"
  329. :group 'org-id)
  330. ;;; Version
  331. (org-check-version)
  332. ;;;###autoload
  333. (defun org-version (&optional here full message)
  334. "Show the Org version.
  335. Interactively, or when MESSAGE is non-nil, show it in echo area.
  336. With prefix argument, or when HERE is non-nil, insert it at point.
  337. In non-interactive uses, a reduced version string is output unless
  338. FULL is given."
  339. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  340. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  341. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  342. (load-suffixes (list ".el"))
  343. (org-install-dir
  344. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  345. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  346. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  347. (let* ((load-suffixes save-load-suffixes)
  348. (release (org-release))
  349. (git-version (org-git-version))
  350. (version (format "Org mode version %s (%s @ %s)"
  351. release
  352. git-version
  353. (if org-install-dir
  354. (if (string= org-dir org-install-dir)
  355. org-install-dir
  356. (concat "mixed installation! "
  357. org-install-dir
  358. " and "
  359. org-dir))
  360. "org-loaddefs.el can not be found!")))
  361. (version1 (if full version release)))
  362. (when here (insert version1))
  363. (when message (message "%s" version1))
  364. version1)))
  365. (defconst org-version (org-version))
  366. ;;; Syntax Constants
  367. ;;;; Block
  368. (defconst org-block-regexp
  369. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  370. "Regular expression for hiding blocks.")
  371. (defconst org-dblock-start-re
  372. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  373. "Matches the start line of a dynamic block, with parameters.")
  374. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  375. "Matches the end of a dynamic block.")
  376. ;;;; Clock and Planning
  377. (defconst org-clock-string "CLOCK:"
  378. "String used as prefix for timestamps clocking work hours on an item.")
  379. (defvar org-closed-string "CLOSED:"
  380. "String used as the prefix for timestamps logging closing a TODO entry.")
  381. (defvar org-deadline-string "DEADLINE:"
  382. "String to mark deadline entries.
  383. \\<org-mode-map>
  384. A deadline is this string, followed by a time stamp. It must be
  385. a word, terminated by a colon. You can insert a schedule keyword
  386. and a timestamp with `\\[org-deadline]'.")
  387. (defvar org-scheduled-string "SCHEDULED:"
  388. "String to mark scheduled TODO entries.
  389. \\<org-mode-map>
  390. A schedule is this string, followed by a time stamp. It must be
  391. a word, terminated by a colon. You can insert a schedule keyword
  392. and a timestamp with `\\[org-schedule]'.")
  393. (defconst org-ds-keyword-length
  394. (+ 2
  395. (apply #'max
  396. (mapcar #'length
  397. (list org-deadline-string org-scheduled-string
  398. org-clock-string org-closed-string))))
  399. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  400. (defconst org-planning-line-re
  401. (concat "^[ \t]*"
  402. (regexp-opt
  403. (list org-closed-string org-deadline-string org-scheduled-string)
  404. t))
  405. "Matches a line with planning info.
  406. Matched keyword is in group 1.")
  407. (defconst org-clock-line-re
  408. (concat "^[ \t]*" org-clock-string)
  409. "Matches a line with clock info.")
  410. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  411. "Matches the DEADLINE keyword.")
  412. (defconst org-deadline-time-regexp
  413. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  414. "Matches the DEADLINE keyword together with a time stamp.")
  415. (defconst org-deadline-time-hour-regexp
  416. (concat "\\<" org-deadline-string
  417. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  418. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  419. (defconst org-deadline-line-regexp
  420. (concat "\\<\\(" org-deadline-string "\\).*")
  421. "Matches the DEADLINE keyword and the rest of the line.")
  422. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  423. "Matches the SCHEDULED keyword.")
  424. (defconst org-scheduled-time-regexp
  425. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  426. "Matches the SCHEDULED keyword together with a time stamp.")
  427. (defconst org-scheduled-time-hour-regexp
  428. (concat "\\<" org-scheduled-string
  429. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  430. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  431. (defconst org-closed-time-regexp
  432. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  433. "Matches the CLOSED keyword together with a time stamp.")
  434. (defconst org-keyword-time-regexp
  435. (concat "\\<"
  436. (regexp-opt
  437. (list org-scheduled-string org-deadline-string org-closed-string
  438. org-clock-string)
  439. t)
  440. " *[[<]\\([^]>]+\\)[]>]")
  441. "Matches any of the 4 keywords, together with the time stamp.")
  442. (defconst org-keyword-time-not-clock-regexp
  443. (concat
  444. "\\<"
  445. (regexp-opt
  446. (list org-scheduled-string org-deadline-string org-closed-string) t)
  447. " *[[<]\\([^]>]+\\)[]>]")
  448. "Matches any of the 3 keywords, together with the time stamp.")
  449. (defconst org-maybe-keyword-time-regexp
  450. (concat "\\(\\<"
  451. (regexp-opt
  452. (list org-scheduled-string org-deadline-string org-closed-string
  453. org-clock-string)
  454. t)
  455. "\\)?"
  456. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  457. "\\|"
  458. "<%%([^\r\n>]*>\\)")
  459. "Matches a timestamp, possibly preceded by a keyword.")
  460. (defconst org-all-time-keywords
  461. (mapcar (lambda (w) (substring w 0 -1))
  462. (list org-scheduled-string org-deadline-string
  463. org-clock-string org-closed-string))
  464. "List of time keywords.")
  465. ;;;; Drawer
  466. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  467. "Matches first or last line of a hidden block.
  468. Group 1 contains drawer's name or \"END\".")
  469. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  470. "Regular expression matching the first line of a property drawer.")
  471. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  472. "Regular expression matching the last line of a property drawer.")
  473. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  474. "Regular expression matching the first line of a clock drawer.")
  475. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  476. "Regular expression matching the last line of a clock drawer.")
  477. (defconst org-property-drawer-re
  478. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  479. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  480. "[ \t]*:END:[ \t]*$")
  481. "Matches an entire property drawer.")
  482. (defconst org-clock-drawer-re
  483. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  484. org-clock-drawer-end-re "\\)\n?")
  485. "Matches an entire clock drawer.")
  486. ;;;; Headline
  487. (defconst org-heading-keyword-regexp-format
  488. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  489. "Printf format for a regexp matching a headline with some keyword.
  490. This regexp will match the headline of any node which has the
  491. exact keyword that is put into the format. The keyword isn't in
  492. any group by default, but the stars and the body are.")
  493. (defconst org-heading-keyword-maybe-regexp-format
  494. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  495. "Printf format for a regexp matching a headline, possibly with some keyword.
  496. This regexp can match any headline with the specified keyword, or
  497. without a keyword. The keyword isn't in any group by default,
  498. but the stars and the body are.")
  499. (defconst org-archive-tag "ARCHIVE"
  500. "The tag that marks a subtree as archived.
  501. An archived subtree does not open during visibility cycling, and does
  502. not contribute to the agenda listings.")
  503. (defconst org-tag-re "[[:alnum:]_@#%]+"
  504. "Regexp matching a single tag.")
  505. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  506. "Regexp matching the tag group at the end of a line, with leading spaces.
  507. Tags are stored in match group 1. Match group 2 stores the tags
  508. without the enclosing colons.")
  509. (defconst org-tag-line-re
  510. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  511. "Regexp matching tags in a headline.
  512. Tags are stored in match group 1. Match group 2 stores the tags
  513. without the enclosing colons.")
  514. (eval-and-compile
  515. (defconst org-comment-string "COMMENT"
  516. "Entries starting with this keyword will never be exported.
  517. \\<org-mode-map>
  518. An entry can be toggled between COMMENT and normal with
  519. `\\[org-toggle-comment]'."))
  520. ;;;; LaTeX Environments and Fragments
  521. (defconst org-latex-regexps
  522. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  523. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  524. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  525. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  526. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  527. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  528. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  529. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  530. "Regular expressions for matching embedded LaTeX.")
  531. ;;;; Node Property
  532. (defconst org-effort-property "Effort"
  533. "The property that is being used to keep track of effort estimates.
  534. Effort estimates given in this property need to have the format H:MM.")
  535. ;;;; Table
  536. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  537. "Detect an org-type or table-type table.")
  538. (defconst org-table-line-regexp "^[ \t]*|"
  539. "Detect an org-type table line.")
  540. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  541. "Detect an org-type table line.")
  542. (defconst org-table-hline-regexp "^[ \t]*|-"
  543. "Detect an org-type table hline.")
  544. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  545. "Detect a table-type table hline.")
  546. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  547. "Detect the first line outside a table when searching from within it.
  548. This works for both table types.")
  549. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  550. "Detect a #+TBLFM line.")
  551. ;;;; Timestamp
  552. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  553. "Regular expression for fast time stamp matching.")
  554. (defconst org-ts-regexp-inactive
  555. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  556. "Regular expression for fast inactive time stamp matching.")
  557. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  558. "Regular expression for fast time stamp matching.")
  559. (defconst org-ts-regexp0
  560. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  561. "Regular expression matching time strings for analysis.
  562. This one does not require the space after the date, so it can be used
  563. on a string that terminates immediately after the date.")
  564. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  565. "Regular expression matching time strings for analysis.")
  566. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  567. "Regular expression matching time stamps, with groups.")
  568. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  569. "Regular expression matching time stamps (also [..]), with groups.")
  570. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  571. "Regular expression matching a time stamp range.")
  572. (defconst org-tr-regexp-both
  573. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  574. "Regular expression matching a time stamp range.")
  575. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  576. org-ts-regexp "\\)?")
  577. "Regular expression matching a time stamp or time stamp range.")
  578. (defconst org-tsr-regexp-both
  579. (concat org-ts-regexp-both "\\(--?-?"
  580. org-ts-regexp-both "\\)?")
  581. "Regular expression matching a time stamp or time stamp range.
  582. The time stamps may be either active or inactive.")
  583. (defconst org-repeat-re
  584. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  585. "Regular expression for specifying repeated events.
  586. After a match, group 1 contains the repeat expression.")
  587. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  588. "Formats for `format-time-string' which are used for time stamps.")
  589. ;;; The custom variables
  590. (defgroup org nil
  591. "Outline-based notes management and organizer."
  592. :tag "Org"
  593. :group 'outlines
  594. :group 'calendar)
  595. (defcustom org-mode-hook nil
  596. "Mode hook for Org mode, run after the mode was turned on."
  597. :group 'org
  598. :type 'hook)
  599. (defcustom org-load-hook nil
  600. "Hook that is run after org.el has been loaded."
  601. :group 'org
  602. :type 'hook)
  603. (defcustom org-log-buffer-setup-hook nil
  604. "Hook that is run after an Org log buffer is created."
  605. :group 'org
  606. :version "24.1"
  607. :type 'hook)
  608. (defvar org-modules) ; defined below
  609. (defvar org-modules-loaded nil
  610. "Have the modules been loaded already?")
  611. (defun org-load-modules-maybe (&optional force)
  612. "Load all extensions listed in `org-modules'."
  613. (when (or force (not org-modules-loaded))
  614. (dolist (ext org-modules)
  615. (condition-case nil (require ext)
  616. (error (message "Problems while trying to load feature `%s'" ext))))
  617. (setq org-modules-loaded t)))
  618. (defun org-set-modules (var value)
  619. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  620. (set var value)
  621. (when (featurep 'org)
  622. (org-load-modules-maybe 'force)
  623. (org-element-cache-reset 'all)))
  624. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
  625. "Modules that should always be loaded together with org.el.
  626. If a description starts with <C>, the file is not part of Emacs
  627. and loading it will require that you have downloaded and properly
  628. installed the Org mode distribution.
  629. You can also use this system to load external packages (i.e. neither Org
  630. core modules, nor modules from the CONTRIB directory). Just add symbols
  631. to the end of the list. If the package is called org-xyz.el, then you need
  632. to add the symbol `xyz', and the package must have a call to:
  633. (provide \\='org-xyz)
  634. For export specific modules, see also `org-export-backends'."
  635. :group 'org
  636. :set 'org-set-modules
  637. :version "26.1"
  638. :package-version '(Org . "9.2")
  639. :type
  640. '(set :greedy t
  641. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  642. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  643. (const :tag " crypt: Encryption of subtrees" org-crypt)
  644. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  645. (const :tag " docview: Links to doc-view buffers" org-docview)
  646. (const :tag " eww: Store link to url of eww" org-eww)
  647. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  648. (const :tag " habit: Track your consistency with habits" org-habit)
  649. (const :tag " id: Global IDs for identifying entries" org-id)
  650. (const :tag " info: Links to Info nodes" org-info)
  651. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  652. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  653. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  654. (const :tag " mouse: Additional mouse support" org-mouse)
  655. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  656. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  657. (const :tag " tempo: Fast completion for structures" org-tempo)
  658. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  659. (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
  660. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  661. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  662. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  663. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  664. (const :tag "C collector: Collect properties into tables" org-collector)
  665. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  666. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  667. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  668. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  669. (const :tag "C eval: Include command output as text" org-eval)
  670. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  671. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  672. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  673. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  674. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  675. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  676. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  677. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  678. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  679. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  680. (const :tag "C notify: Notifications for Org-mode" org-notify)
  681. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  682. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  683. (const :tag "C registry: A registry for Org links" org-registry)
  684. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  685. (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
  686. (const :tag "C secretary: Team management with Org" org-secretary)
  687. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  688. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  689. (const :tag "C track: Keep up with Org mode development" org-track)
  690. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  691. (const :tag "C vm: Links to VM folders/messages" org-vm)
  692. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  693. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  694. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  695. (defvar org-export-registered-backends) ; From ox.el.
  696. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  697. (declare-function org-export-backend-name "ox" (backend) t)
  698. (defcustom org-export-backends '(ascii html icalendar latex odt)
  699. "List of export back-ends that should be always available.
  700. If a description starts with <C>, the file is not part of Emacs
  701. and loading it will require that you have downloaded and properly
  702. installed the Org mode distribution.
  703. Unlike to `org-modules', libraries in this list will not be
  704. loaded along with Org, but only once the export framework is
  705. needed.
  706. This variable needs to be set before org.el is loaded. If you
  707. need to make a change while Emacs is running, use the customize
  708. interface or run the following code, where VAL stands for the new
  709. value of the variable, after updating it:
  710. (progn
  711. (setq org-export-registered-backends
  712. (cl-remove-if-not
  713. (lambda (backend)
  714. (let ((name (org-export-backend-name backend)))
  715. (or (memq name val)
  716. (catch \\='parentp
  717. (dolist (b val)
  718. (and (org-export-derived-backend-p b name)
  719. (throw \\='parentp t)))))))
  720. org-export-registered-backends))
  721. (let ((new-list (mapcar #\\='org-export-backend-name
  722. org-export-registered-backends)))
  723. (dolist (backend val)
  724. (cond
  725. ((not (load (format \"ox-%s\" backend) t t))
  726. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  727. backend))
  728. ((not (memq backend new-list)) (push backend new-list))))
  729. (set-default \\='org-export-backends new-list)))
  730. Adding a back-end to this list will also pull the back-end it
  731. depends on, if any."
  732. :group 'org
  733. :group 'org-export
  734. :version "26.1"
  735. :package-version '(Org . "9.0")
  736. :initialize 'custom-initialize-set
  737. :set (lambda (var val)
  738. (if (not (featurep 'ox)) (set-default var val)
  739. ;; Any back-end not required anymore (not present in VAL and not
  740. ;; a parent of any back-end in the new value) is removed from the
  741. ;; list of registered back-ends.
  742. (setq org-export-registered-backends
  743. (cl-remove-if-not
  744. (lambda (backend)
  745. (let ((name (org-export-backend-name backend)))
  746. (or (memq name val)
  747. (catch 'parentp
  748. (dolist (b val)
  749. (and (org-export-derived-backend-p b name)
  750. (throw 'parentp t)))))))
  751. org-export-registered-backends))
  752. ;; Now build NEW-LIST of both new back-ends and required
  753. ;; parents.
  754. (let ((new-list (mapcar #'org-export-backend-name
  755. org-export-registered-backends)))
  756. (dolist (backend val)
  757. (cond
  758. ((not (load (format "ox-%s" backend) t t))
  759. (message "Problems while trying to load export back-end `%s'"
  760. backend))
  761. ((not (memq backend new-list)) (push backend new-list))))
  762. ;; Set VAR to that list with fixed dependencies.
  763. (set-default var new-list))))
  764. :type '(set :greedy t
  765. (const :tag " ascii Export buffer to ASCII format" ascii)
  766. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  767. (const :tag " html Export buffer to HTML format" html)
  768. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  769. (const :tag " latex Export buffer to LaTeX format" latex)
  770. (const :tag " man Export buffer to MAN format" man)
  771. (const :tag " md Export buffer to Markdown format" md)
  772. (const :tag " odt Export buffer to ODT format" odt)
  773. (const :tag " org Export buffer to Org format" org)
  774. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  775. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  776. (const :tag "C deck Export buffer to deck.js presentations" deck)
  777. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  778. (const :tag "C groff Export buffer to Groff format" groff)
  779. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  780. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  781. (const :tag "C s5 Export buffer to s5 presentations" s5)
  782. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  783. (eval-after-load 'ox
  784. '(dolist (backend org-export-backends)
  785. (condition-case nil (require (intern (format "ox-%s" backend)))
  786. (error (message "Problems while trying to load export back-end `%s'"
  787. backend)))))
  788. (defcustom org-support-shift-select nil
  789. "Non-nil means make shift-cursor commands select text when possible.
  790. \\<org-mode-map>\
  791. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  792. start selecting a region, or enlarge regions started in this way.
  793. In Org mode, in special contexts, these same keys are used for
  794. other purposes, important enough to compete with shift selection.
  795. Org tries to balance these needs by supporting `shift-select-mode'
  796. outside these special contexts, under control of this variable.
  797. The default of this variable is nil, to avoid confusing behavior. Shifted
  798. cursor keys will then execute Org commands in the following contexts:
  799. - on a headline, changing TODO state (left/right) and priority (up/down)
  800. - on a time stamp, changing the time
  801. - in a plain list item, changing the bullet type
  802. - in a property definition line, switching between allowed values
  803. - in the BEGIN line of a clock table (changing the time block).
  804. Outside these contexts, the commands will throw an error.
  805. When this variable is t and the cursor is not in a special
  806. context, Org mode will support shift-selection for making and
  807. enlarging regions. To make this more effective, the bullet
  808. cycling will no longer happen anywhere in an item line, but only
  809. if the cursor is exactly on the bullet.
  810. If you set this variable to the symbol `always', then the keys
  811. will not be special in headlines, property lines, and item lines,
  812. to make shift selection work there as well. If this is what you
  813. want, you can use the following alternative commands:
  814. `\\[org-todo]' and `\\[org-priority]' \
  815. to change TODO state and priority,
  816. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  817. can be used to switch TODO sets,
  818. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  819. and properties can be edited by hand or in column view.
  820. However, when the cursor is on a timestamp, shift-cursor commands
  821. will still edit the time stamp - this is just too good to give up."
  822. :group 'org
  823. :type '(choice
  824. (const :tag "Never" nil)
  825. (const :tag "When outside special context" t)
  826. (const :tag "Everywhere except timestamps" always)))
  827. (defcustom org-loop-over-headlines-in-active-region nil
  828. "Shall some commands act upon headlines in the active region?
  829. When set to t, some commands will be performed in all headlines
  830. within the active region.
  831. When set to `start-level', some commands will be performed in all
  832. headlines within the active region, provided that these headlines
  833. are of the same level than the first one.
  834. When set to a string, those commands will be performed on the
  835. matching headlines within the active region. Such string must be
  836. a tags/property/todo match as it is used in the agenda tags view.
  837. The list of commands is: `org-schedule', `org-deadline',
  838. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  839. `org-archive-to-archive-sibling'. The archiving commands skip
  840. already archived entries."
  841. :type '(choice (const :tag "Don't loop" nil)
  842. (const :tag "All headlines in active region" t)
  843. (const :tag "In active region, headlines at the same level than the first one" start-level)
  844. (string :tag "Tags/Property/Todo matcher"))
  845. :version "24.1"
  846. :group 'org-todo
  847. :group 'org-archive)
  848. (defcustom org-startup-folded t
  849. "Non-nil means entering Org mode will switch to OVERVIEW.
  850. This can also be configured on a per-file basis by adding one of
  851. the following lines anywhere in the buffer:
  852. #+STARTUP: fold (or `overview', this is equivalent)
  853. #+STARTUP: nofold (or `showall', this is equivalent)
  854. #+STARTUP: content
  855. #+STARTUP: showeverything
  856. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  857. to ignore this option when Org opens agenda files for the first
  858. time."
  859. :group 'org-startup
  860. :type '(choice
  861. (const :tag "nofold: show all" nil)
  862. (const :tag "fold: overview" t)
  863. (const :tag "content: all headlines" content)
  864. (const :tag "show everything, even drawers" showeverything)))
  865. (defcustom org-startup-truncated t
  866. "Non-nil means entering Org mode will set `truncate-lines'.
  867. This is useful since some lines containing links can be very long and
  868. uninteresting. Also tables look terrible when wrapped.
  869. The variable `org-startup-truncated' allows to configure
  870. truncation for Org mode different to the other modes that use the
  871. variable `truncate-lines' and as a shortcut instead of putting
  872. the variable `truncate-lines' into the `org-mode-hook'. If one
  873. wants to configure truncation for Org mode not statically but
  874. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  875. the variable `truncate-lines' has to be used because in such a
  876. case it is too late to set the variable `org-startup-truncated'."
  877. :group 'org-startup
  878. :type 'boolean)
  879. (defcustom org-startup-indented nil
  880. "Non-nil means turn on `org-indent-mode' on startup.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: indent
  884. #+STARTUP: noindent"
  885. :group 'org-structure
  886. :type '(choice
  887. (const :tag "Not" nil)
  888. (const :tag "Globally (slow on startup in large files)" t)))
  889. (defcustom org-use-sub-superscripts t
  890. "Non-nil means interpret \"_\" and \"^\" for display.
  891. If you want to control how Org exports those characters, see
  892. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  893. used to be an alias for `org-export-with-sub-superscripts' in
  894. Org <8.0, it is not anymore.
  895. When this option is turned on, you can use TeX-like syntax for
  896. sub- and superscripts within the buffer. Several characters after
  897. \"_\" or \"^\" will be considered as a single item - so grouping
  898. with {} is normally not needed. For example, the following things
  899. will be parsed as single sub- or superscripts:
  900. 10^24 or 10^tau several digits will be considered 1 item.
  901. 10^-12 or 10^-tau a leading sign with digits or a word
  902. x^2-y^3 will be read as x^2 - y^3, because items are
  903. terminated by almost any nonword/nondigit char.
  904. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  905. Still, ambiguity is possible. So when in doubt, use {} to enclose
  906. the sub/superscript. If you set this variable to the symbol `{}',
  907. the braces are *required* in order to trigger interpretations as
  908. sub/superscript. This can be helpful in documents that need \"_\"
  909. frequently in plain text."
  910. :group 'org-startup
  911. :version "24.4"
  912. :package-version '(Org . "8.0")
  913. :type '(choice
  914. (const :tag "Always interpret" t)
  915. (const :tag "Only with braces" {})
  916. (const :tag "Never interpret" nil)))
  917. (defcustom org-startup-with-beamer-mode nil
  918. "Non-nil means turn on `org-beamer-mode' on startup.
  919. This can also be configured on a per-file basis by adding one of
  920. the following lines anywhere in the buffer:
  921. #+STARTUP: beamer"
  922. :group 'org-startup
  923. :version "24.1"
  924. :type 'boolean)
  925. (defcustom org-startup-align-all-tables nil
  926. "Non-nil means align all tables when visiting a file.
  927. This can also be configured on a per-file basis by adding one of
  928. the following lines anywhere in the buffer:
  929. #+STARTUP: align
  930. #+STARTUP: noalign"
  931. :group 'org-startup
  932. :type 'boolean)
  933. (defcustom org-startup-shrink-all-tables nil
  934. "Non-nil means shrink all table columns with a width cookie.
  935. This can also be configured on a per-file basis by adding one of
  936. the following lines anywhere in the buffer:
  937. #+STARTUP: shrink"
  938. :group 'org-startup
  939. :type 'boolean
  940. :version "27.1"
  941. :package-version '(Org . "9.2")
  942. :safe #'booleanp)
  943. (defcustom org-startup-with-inline-images nil
  944. "Non-nil means show inline images when loading a new Org file.
  945. This can also be configured on a per-file basis by adding one of
  946. the following lines anywhere in the buffer:
  947. #+STARTUP: inlineimages
  948. #+STARTUP: noinlineimages"
  949. :group 'org-startup
  950. :version "24.1"
  951. :type 'boolean)
  952. (defcustom org-startup-with-latex-preview nil
  953. "Non-nil means preview LaTeX fragments when loading a new Org file.
  954. This can also be configured on a per-file basis by adding one of
  955. the following lines anywhere in the buffer:
  956. #+STARTUP: latexpreview
  957. #+STARTUP: nolatexpreview"
  958. :group 'org-startup
  959. :version "24.4"
  960. :package-version '(Org . "8.0")
  961. :type 'boolean)
  962. (defcustom org-insert-mode-line-in-empty-file nil
  963. "Non-nil means insert the first line setting Org mode in empty files.
  964. When the function `org-mode' is called interactively in an empty file, this
  965. normally means that the file name does not automatically trigger Org mode.
  966. To ensure that the file will always be in Org mode in the future, a
  967. line enforcing Org mode will be inserted into the buffer, if this option
  968. has been set."
  969. :group 'org-startup
  970. :type 'boolean)
  971. (defcustom org-replace-disputed-keys nil
  972. "Non-nil means use alternative key bindings for some keys.
  973. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  974. These keys are also used by other packages like Shift Select mode,
  975. CUA mode or Windmove. If you want to use Org mode together with
  976. one of these other modes, or more generally if you would like to
  977. move some Org mode commands to other keys, set this variable and
  978. configure the keys with the variable `org-disputed-keys'.
  979. This option is only relevant at load-time of Org mode, and must be set
  980. *before* org.el is loaded. Changing it requires a restart of Emacs to
  981. become effective."
  982. :group 'org-startup
  983. :type 'boolean)
  984. (defcustom org-use-extra-keys nil
  985. "Non-nil means use extra key sequence definitions for certain commands.
  986. This happens automatically if `window-system' is nil. This
  987. variable lets you do the same manually. You must set it before
  988. loading Org."
  989. :group 'org-startup
  990. :type 'boolean)
  991. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  992. (defcustom org-disputed-keys
  993. '(([(shift up)] . [(meta p)])
  994. ([(shift down)] . [(meta n)])
  995. ([(shift left)] . [(meta -)])
  996. ([(shift right)] . [(meta +)])
  997. ([(control shift right)] . [(meta shift +)])
  998. ([(control shift left)] . [(meta shift -)]))
  999. "Keys for which Org mode and other modes compete.
  1000. This is an alist, cars are the default keys, second element specifies
  1001. the alternative to use when `org-replace-disputed-keys' is t.
  1002. Keys can be specified in any syntax supported by `define-key'.
  1003. The value of this option takes effect only at Org mode startup,
  1004. therefore you'll have to restart Emacs to apply it after changing."
  1005. :group 'org-startup
  1006. :type 'alist)
  1007. (defun org-key (key)
  1008. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  1009. Or return the original if not disputed."
  1010. (when org-replace-disputed-keys
  1011. (let* ((nkey (key-description key))
  1012. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  1013. org-disputed-keys)))
  1014. (setq key (if x (cdr x) key))))
  1015. key)
  1016. (defun org-defkey (keymap key def)
  1017. "Define a key, possibly translated, as returned by `org-key'."
  1018. (define-key keymap (org-key key) def))
  1019. (defcustom org-ellipsis nil
  1020. "The ellipsis to use in the Org mode outline.
  1021. When nil, just use the standard three dots. When a non-empty string,
  1022. use that string instead.
  1023. The change affects only Org mode (which will then use its own display table).
  1024. Changing this requires executing `\\[org-mode]' in a buffer to become
  1025. effective."
  1026. :group 'org-startup
  1027. :type '(choice (const :tag "Default" nil)
  1028. (string :tag "String" :value "...#"))
  1029. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  1030. (defvar org-display-table nil
  1031. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  1032. (defgroup org-keywords nil
  1033. "Keywords in Org mode."
  1034. :tag "Org Keywords"
  1035. :group 'org)
  1036. (defcustom org-closed-keep-when-no-todo nil
  1037. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1038. :group 'org-todo
  1039. :group 'org-keywords
  1040. :version "24.4"
  1041. :package-version '(Org . "8.0")
  1042. :type 'boolean)
  1043. (defgroup org-structure nil
  1044. "Options concerning the general structure of Org files."
  1045. :tag "Org Structure"
  1046. :group 'org)
  1047. (defgroup org-reveal-location nil
  1048. "Options about how to make context of a location visible."
  1049. :tag "Org Reveal Location"
  1050. :group 'org-structure)
  1051. (defcustom org-show-context-detail '((agenda . local)
  1052. (bookmark-jump . lineage)
  1053. (isearch . lineage)
  1054. (default . ancestors))
  1055. "Alist between context and visibility span when revealing a location.
  1056. \\<org-mode-map>Some actions may move point into invisible
  1057. locations. As a consequence, Org always expose a neighborhood
  1058. around point. How much is shown depends on the initial action,
  1059. or context. Valid contexts are
  1060. agenda when exposing an entry from the agenda
  1061. org-goto when using the command `org-goto' (`\\[org-goto]')
  1062. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1063. tags-tree when constructing a sparse tree based on tags matches
  1064. link-search when exposing search matches associated with a link
  1065. mark-goto when exposing the jump goal of a mark
  1066. bookmark-jump when exposing a bookmark location
  1067. isearch when exiting from an incremental search
  1068. default default for all contexts not set explicitly
  1069. Allowed visibility spans are
  1070. minimal show current headline; if point is not on headline,
  1071. also show entry
  1072. local show current headline, entry and next headline
  1073. ancestors show current headline and its direct ancestors; if
  1074. point is not on headline, also show entry
  1075. lineage show current headline, its direct ancestors and all
  1076. their children; if point is not on headline, also show
  1077. entry and first child
  1078. tree show current headline, its direct ancestors and all
  1079. their children; if point is not on headline, also show
  1080. entry and all children
  1081. canonical show current headline, its direct ancestors along with
  1082. their entries and children; if point is not located on
  1083. the headline, also show current entry and all children
  1084. As special cases, a nil or t value means show all contexts in
  1085. `minimal' or `canonical' view, respectively.
  1086. Some views can make displayed information very compact, but also
  1087. make it harder to edit the location of the match. In such
  1088. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1089. more context."
  1090. :group 'org-reveal-location
  1091. :version "26.1"
  1092. :package-version '(Org . "9.0")
  1093. :type '(choice
  1094. (const :tag "Canonical" t)
  1095. (const :tag "Minimal" nil)
  1096. (repeat :greedy t :tag "Individual contexts"
  1097. (cons
  1098. (choice :tag "Context"
  1099. (const agenda)
  1100. (const org-goto)
  1101. (const occur-tree)
  1102. (const tags-tree)
  1103. (const link-search)
  1104. (const mark-goto)
  1105. (const bookmark-jump)
  1106. (const isearch)
  1107. (const default))
  1108. (choice :tag "Detail level"
  1109. (const minimal)
  1110. (const local)
  1111. (const ancestors)
  1112. (const lineage)
  1113. (const tree)
  1114. (const canonical))))))
  1115. (defcustom org-indirect-buffer-display 'other-window
  1116. "How should indirect tree buffers be displayed?
  1117. This applies to indirect buffers created with the commands
  1118. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1119. Valid values are:
  1120. current-window Display in the current window
  1121. other-window Just display in another window.
  1122. dedicated-frame Create one new frame, and re-use it each time.
  1123. new-frame Make a new frame each time. Note that in this case
  1124. previously-made indirect buffers are kept, and you need to
  1125. kill these buffers yourself."
  1126. :group 'org-structure
  1127. :group 'org-agenda-windows
  1128. :type '(choice
  1129. (const :tag "In current window" current-window)
  1130. (const :tag "In current frame, other window" other-window)
  1131. (const :tag "Each time a new frame" new-frame)
  1132. (const :tag "One dedicated frame" dedicated-frame)))
  1133. (defcustom org-use-speed-commands nil
  1134. "Non-nil means activate single letter commands at beginning of a headline.
  1135. This may also be a function to test for appropriate locations where speed
  1136. commands should be active.
  1137. For example, to activate speed commands when the point is on any
  1138. star at the beginning of the headline, you can do this:
  1139. (setq org-use-speed-commands
  1140. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1141. :group 'org-structure
  1142. :type '(choice
  1143. (const :tag "Never" nil)
  1144. (const :tag "At beginning of headline stars" t)
  1145. (function)))
  1146. (defcustom org-speed-commands-user nil
  1147. "Alist of additional speed commands.
  1148. This list will be checked before `org-speed-commands-default'
  1149. when the variable `org-use-speed-commands' is non-nil
  1150. and when the cursor is at the beginning of a headline.
  1151. The car of each entry is a string with a single letter, which must
  1152. be assigned to `self-insert-command' in the global map.
  1153. The cdr is either a command to be called interactively, a function
  1154. to be called, or a form to be evaluated.
  1155. An entry that is just a list with a single string will be interpreted
  1156. as a descriptive headline that will be added when listing the speed
  1157. commands in the Help buffer using the `?' speed command."
  1158. :group 'org-structure
  1159. :type '(repeat :value ("k" . ignore)
  1160. (choice :value ("k" . ignore)
  1161. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1162. (cons :tag "Letter and Command"
  1163. (string :tag "Command letter")
  1164. (choice
  1165. (function)
  1166. (sexp))))))
  1167. (defcustom org-bookmark-names-plist
  1168. '(:last-capture "org-capture-last-stored"
  1169. :last-refile "org-refile-last-stored"
  1170. :last-capture-marker "org-capture-last-stored-marker")
  1171. "Names for bookmarks automatically set by some Org commands.
  1172. This can provide strings as names for a number of bookmarks Org sets
  1173. automatically. The following keys are currently implemented:
  1174. :last-capture
  1175. :last-capture-marker
  1176. :last-refile
  1177. When a key does not show up in the property list, the corresponding bookmark
  1178. is not set."
  1179. :group 'org-structure
  1180. :type 'plist)
  1181. (defgroup org-cycle nil
  1182. "Options concerning visibility cycling in Org mode."
  1183. :tag "Org Cycle"
  1184. :group 'org-structure)
  1185. (defcustom org-cycle-skip-children-state-if-no-children t
  1186. "Non-nil means skip CHILDREN state in entries that don't have any."
  1187. :group 'org-cycle
  1188. :type 'boolean)
  1189. (defcustom org-cycle-max-level nil
  1190. "Maximum level which should still be subject to visibility cycling.
  1191. Levels higher than this will, for cycling, be treated as text, not a headline.
  1192. When `org-odd-levels-only' is set, a value of N in this variable actually
  1193. means 2N-1 stars as the limiting headline.
  1194. When nil, cycle all levels.
  1195. Note that the limiting level of cycling is also influenced by
  1196. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1197. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1198. than its value."
  1199. :group 'org-cycle
  1200. :type '(choice
  1201. (const :tag "No limit" nil)
  1202. (integer :tag "Maximum level")))
  1203. (defcustom org-hide-block-startup nil
  1204. "Non-nil means entering Org mode will fold all blocks.
  1205. This can also be set in on a per-file basis with
  1206. #+STARTUP: hideblocks
  1207. #+STARTUP: showblocks"
  1208. :group 'org-startup
  1209. :group 'org-cycle
  1210. :type 'boolean)
  1211. (defcustom org-cycle-global-at-bob nil
  1212. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1213. This makes it possible to do global cycling without having to use `S-TAB'
  1214. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1215. line of the buffer
  1216. must not be a headline -- it may be empty or some other text.
  1217. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1218. sure the cursor stays at the beginning of the buffer.
  1219. When this option is nil, don't do anything special at the beginning of
  1220. the buffer."
  1221. :group 'org-cycle
  1222. :type 'boolean)
  1223. (defcustom org-cycle-level-after-item/entry-creation t
  1224. "Non-nil means cycle entry level or item indentation in new empty entries.
  1225. When the cursor is at the end of an empty headline, i.e., with only stars
  1226. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1227. and then all possible ancestor states, before returning to the original state.
  1228. This makes data entry extremely fast: M-RET to create a new headline,
  1229. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1230. When the cursor is at the end of an empty plain list item, one TAB will
  1231. make it a subitem, two or more tabs will back up to make this an item
  1232. higher up in the item hierarchy."
  1233. :group 'org-cycle
  1234. :type 'boolean)
  1235. (defcustom org-cycle-emulate-tab t
  1236. "Where should `org-cycle' emulate TAB.
  1237. nil Never
  1238. white Only in completely white lines
  1239. whitestart Only at the beginning of lines, before the first non-white char
  1240. t Everywhere except in headlines
  1241. exc-hl-bol Everywhere except at the start of a headline
  1242. If TAB is used in a place where it does not emulate TAB, the current subtree
  1243. visibility is cycled."
  1244. :group 'org-cycle
  1245. :type '(choice (const :tag "Never" nil)
  1246. (const :tag "Only in completely white lines" white)
  1247. (const :tag "Before first char in a line" whitestart)
  1248. (const :tag "Everywhere except in headlines" t)
  1249. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1250. (defcustom org-cycle-separator-lines 2
  1251. "Number of empty lines needed to keep an empty line between collapsed trees.
  1252. If you leave an empty line between the end of a subtree and the following
  1253. headline, this empty line is hidden when the subtree is folded.
  1254. Org mode will leave (exactly) one empty line visible if the number of
  1255. empty lines is equal or larger to the number given in this variable.
  1256. So the default 2 means at least 2 empty lines after the end of a subtree
  1257. are needed to produce free space between a collapsed subtree and the
  1258. following headline.
  1259. If the number is negative, and the number of empty lines is at least -N,
  1260. all empty lines are shown.
  1261. Special case: when 0, never leave empty lines in collapsed view."
  1262. :group 'org-cycle
  1263. :type 'integer)
  1264. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1265. (defcustom org-pre-cycle-hook nil
  1266. "Hook that is run before visibility cycling is happening.
  1267. The function(s) in this hook must accept a single argument which indicates
  1268. the new state that will be set right after running this hook. The
  1269. argument is a symbol. Before a global state change, it can have the values
  1270. `overview', `content', or `all'. Before a local state change, it can have
  1271. the values `folded', `children', or `subtree'."
  1272. :group 'org-cycle
  1273. :type 'hook)
  1274. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1275. org-cycle-show-empty-lines
  1276. org-optimize-window-after-visibility-change)
  1277. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1278. The function(s) in this hook must accept a single argument which indicates
  1279. the new state that was set by the most recent `org-cycle' command. The
  1280. argument is a symbol. After a global state change, it can have the values
  1281. `overview', `contents', or `all'. After a local state change, it can have
  1282. the values `folded', `children', or `subtree'."
  1283. :group 'org-cycle
  1284. :type 'hook
  1285. :version "26.1"
  1286. :package-version '(Org . "8.3"))
  1287. (defgroup org-edit-structure nil
  1288. "Options concerning structure editing in Org mode."
  1289. :tag "Org Edit Structure"
  1290. :group 'org-structure)
  1291. (defcustom org-odd-levels-only nil
  1292. "Non-nil means skip even levels and only use odd levels for the outline.
  1293. This has the effect that two stars are being added/taken away in
  1294. promotion/demotion commands. It also influences how levels are
  1295. handled by the exporters.
  1296. Changing it requires restart of `font-lock-mode' to become effective
  1297. for fontification also in regions already fontified.
  1298. You may also set this on a per-file basis by adding one of the following
  1299. lines to the buffer:
  1300. #+STARTUP: odd
  1301. #+STARTUP: oddeven"
  1302. :group 'org-edit-structure
  1303. :group 'org-appearance
  1304. :type 'boolean)
  1305. (defcustom org-adapt-indentation t
  1306. "Non-nil means adapt indentation to outline node level.
  1307. When this variable is set, Org assumes that you write outlines by
  1308. indenting text in each node to align with the headline (after the
  1309. stars). The following issues are influenced by this variable:
  1310. - The indentation is increased by one space in a demotion
  1311. command, and decreased by one in a promotion command. However,
  1312. in the latter case, if shifting some line in the entry body
  1313. would alter document structure (e.g., insert a new headline),
  1314. indentation is not changed at all.
  1315. - Property drawers and planning information is inserted indented
  1316. when this variable is set. When nil, they will not be indented.
  1317. - TAB indents a line relative to current level. The lines below
  1318. a headline will be indented when this variable is set.
  1319. Note that this is all about true indentation, by adding and
  1320. removing space characters. See also \"org-indent.el\" which does
  1321. level-dependent indentation in a virtual way, i.e. at display
  1322. time in Emacs."
  1323. :group 'org-edit-structure
  1324. :type 'boolean
  1325. :safe #'booleanp)
  1326. (defcustom org-special-ctrl-a/e nil
  1327. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1328. When t, `C-a' will bring back the cursor to the beginning of the
  1329. headline text, i.e. after the stars and after a possible TODO
  1330. keyword. In an item, this will be the position after bullet and
  1331. check-box, if any. When the cursor is already at that position,
  1332. another `C-a' will bring it to the beginning of the line.
  1333. `C-e' will jump to the end of the headline, ignoring the presence
  1334. of tags in the headline. A second `C-e' will then jump to the
  1335. true end of the line, after any tags. This also means that, when
  1336. this variable is non-nil, `C-e' also will never jump beyond the
  1337. end of the heading of a folded section, i.e. not after the
  1338. ellipses.
  1339. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1340. normally, going to the true line boundary first. Only a directly
  1341. following, identical keypress will bring the cursor to the
  1342. special positions.
  1343. This may also be a cons cell where the behavior for `C-a' and
  1344. `C-e' is set separately."
  1345. :group 'org-edit-structure
  1346. :type '(choice
  1347. (const :tag "off" nil)
  1348. (const :tag "on: after stars/bullet and before tags first" t)
  1349. (const :tag "reversed: true line boundary first" reversed)
  1350. (cons :tag "Set C-a and C-e separately"
  1351. (choice :tag "Special C-a"
  1352. (const :tag "off" nil)
  1353. (const :tag "on: after stars/bullet first" t)
  1354. (const :tag "reversed: before stars/bullet first" reversed))
  1355. (choice :tag "Special C-e"
  1356. (const :tag "off" nil)
  1357. (const :tag "on: before tags first" t)
  1358. (const :tag "reversed: after tags first" reversed)))))
  1359. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1360. (defcustom org-special-ctrl-k nil
  1361. "Non-nil means `C-k' will behave specially in headlines.
  1362. When nil, `C-k' will call the default `kill-line' command.
  1363. When t, the following will happen while the cursor is in the headline:
  1364. - When the cursor is at the beginning of a headline, kill the entire
  1365. line and possible the folded subtree below the line.
  1366. - When in the middle of the headline text, kill the headline up to the tags.
  1367. - When after the headline text, kill the tags."
  1368. :group 'org-edit-structure
  1369. :type 'boolean)
  1370. (defcustom org-ctrl-k-protect-subtree nil
  1371. "Non-nil means, do not delete a hidden subtree with C-k.
  1372. When set to the symbol `error', simply throw an error when C-k is
  1373. used to kill (part-of) a headline that has hidden text behind it.
  1374. Any other non-nil value will result in a query to the user, if it is
  1375. OK to kill that hidden subtree. When nil, kill without remorse."
  1376. :group 'org-edit-structure
  1377. :version "24.1"
  1378. :type '(choice
  1379. (const :tag "Do not protect hidden subtrees" nil)
  1380. (const :tag "Protect hidden subtrees with a security query" t)
  1381. (const :tag "Never kill a hidden subtree with C-k" error)))
  1382. (defcustom org-special-ctrl-o t
  1383. "Non-nil means, make `C-o' insert a row in tables."
  1384. :group 'org-edit-structure
  1385. :type 'boolean)
  1386. (defcustom org-catch-invisible-edits nil
  1387. "Check if in invisible region before inserting or deleting a character.
  1388. Valid values are:
  1389. nil Do not check, so just do invisible edits.
  1390. error Throw an error and do nothing.
  1391. show Make point visible, and do the requested edit.
  1392. show-and-error Make point visible, then throw an error and abort the edit.
  1393. smart Make point visible, and do insertion/deletion if it is
  1394. adjacent to visible text and the change feels predictable.
  1395. Never delete a previously invisible character or add in the
  1396. middle or right after an invisible region. Basically, this
  1397. allows insertion and backward-delete right before ellipses.
  1398. FIXME: maybe in this case we should not even show?"
  1399. :group 'org-edit-structure
  1400. :version "24.1"
  1401. :type '(choice
  1402. (const :tag "Do not check" nil)
  1403. (const :tag "Throw error when trying to edit" error)
  1404. (const :tag "Unhide, but do not do the edit" show-and-error)
  1405. (const :tag "Show invisible part and do the edit" show)
  1406. (const :tag "Be smart and do the right thing" smart)))
  1407. (defcustom org-yank-folded-subtrees t
  1408. "Non-nil means when yanking subtrees, fold them.
  1409. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1410. it starts with a heading and all other headings in it are either children
  1411. or siblings, then fold all the subtrees. However, do this only if no
  1412. text after the yank would be swallowed into a folded tree by this action."
  1413. :group 'org-edit-structure
  1414. :type 'boolean)
  1415. (defcustom org-yank-adjusted-subtrees nil
  1416. "Non-nil means when yanking subtrees, adjust the level.
  1417. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1418. this function for details."
  1419. :group 'org-edit-structure
  1420. :type 'boolean)
  1421. (defcustom org-M-RET-may-split-line '((default . t))
  1422. "Non-nil means M-RET will split the line at the cursor position.
  1423. When nil, it will go to the end of the line before making a
  1424. new line.
  1425. You may also set this option in a different way for different
  1426. contexts. Valid contexts are:
  1427. headline when creating a new headline
  1428. item when creating a new item
  1429. table in a table field
  1430. default the value to be used for all contexts not explicitly
  1431. customized"
  1432. :group 'org-structure
  1433. :group 'org-table
  1434. :type '(choice
  1435. (const :tag "Always" t)
  1436. (const :tag "Never" nil)
  1437. (repeat :greedy t :tag "Individual contexts"
  1438. (cons
  1439. (choice :tag "Context"
  1440. (const headline)
  1441. (const item)
  1442. (const table)
  1443. (const default))
  1444. (boolean)))))
  1445. (defcustom org-insert-heading-respect-content nil
  1446. "Non-nil means insert new headings after the current subtree.
  1447. \\<org-mode-map>
  1448. When nil, the new heading is created directly after the current line.
  1449. The commands `\\[org-insert-heading-respect-content]' and \
  1450. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1451. for the duration of the command."
  1452. :group 'org-structure
  1453. :type 'boolean)
  1454. (defcustom org-blank-before-new-entry '((heading . auto)
  1455. (plain-list-item . auto))
  1456. "Should `org-insert-heading' leave a blank line before new heading/item?
  1457. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1458. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1459. which case Org will look at the surrounding headings/items and try to
  1460. make an intelligent decision whether to insert a blank line or not."
  1461. :group 'org-edit-structure
  1462. :type '(list
  1463. (cons (const heading)
  1464. (choice (const :tag "Never" nil)
  1465. (const :tag "Always" t)
  1466. (const :tag "Auto" auto)))
  1467. (cons (const plain-list-item)
  1468. (choice (const :tag "Never" nil)
  1469. (const :tag "Always" t)
  1470. (const :tag "Auto" auto)))))
  1471. (defcustom org-insert-heading-hook nil
  1472. "Hook being run after inserting a new heading."
  1473. :group 'org-edit-structure
  1474. :type 'hook)
  1475. (defcustom org-enable-fixed-width-editor t
  1476. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1477. This currently only means they are never auto-wrapped.
  1478. When nil, such lines will be treated like ordinary lines."
  1479. :group 'org-edit-structure
  1480. :type 'boolean)
  1481. (defgroup org-sparse-trees nil
  1482. "Options concerning sparse trees in Org mode."
  1483. :tag "Org Sparse Trees"
  1484. :group 'org-structure)
  1485. (defcustom org-highlight-sparse-tree-matches t
  1486. "Non-nil means highlight all matches that define a sparse tree.
  1487. The highlights will automatically disappear the next time the buffer is
  1488. changed by an edit command."
  1489. :group 'org-sparse-trees
  1490. :type 'boolean)
  1491. (defcustom org-remove-highlights-with-change t
  1492. "Non-nil means any change to the buffer will remove temporary highlights.
  1493. \\<org-mode-map>\
  1494. Such highlights are created by `org-occur' and `org-clock-display'.
  1495. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1496. to get rid of the highlights.
  1497. The highlights created by `org-toggle-latex-fragment' always need
  1498. `\\[org-toggle-latex-fragment]' to be removed."
  1499. :group 'org-sparse-trees
  1500. :group 'org-time
  1501. :type 'boolean)
  1502. (defcustom org-occur-case-fold-search t
  1503. "Non-nil means `org-occur' should be case-insensitive.
  1504. If set to `smart' the search will be case-insensitive only if it
  1505. doesn't specify any upper case character."
  1506. :group 'org-sparse-trees
  1507. :version "26.1"
  1508. :type '(choice
  1509. (const :tag "Case-sensitive" nil)
  1510. (const :tag "Case-insensitive" t)
  1511. (const :tag "Case-insensitive for lower case searches only" smart)))
  1512. (defcustom org-occur-hook '(org-first-headline-recenter)
  1513. "Hook that is run after `org-occur' has constructed a sparse tree.
  1514. This can be used to recenter the window to show as much of the structure
  1515. as possible."
  1516. :group 'org-sparse-trees
  1517. :type 'hook)
  1518. (defgroup org-table nil
  1519. "Options concerning tables in Org mode."
  1520. :tag "Org Table"
  1521. :group 'org)
  1522. (defcustom org-self-insert-cluster-for-undo nil
  1523. "Non-nil means cluster self-insert commands for undo when possible.
  1524. If this is set, then, like in the Emacs command loop, 20 consecutive
  1525. characters will be undone together.
  1526. This is configurable, because there is some impact on typing performance."
  1527. :group 'org-table
  1528. :type 'boolean)
  1529. (defcustom org-table-tab-recognizes-table.el t
  1530. "Non-nil means TAB will automatically notice a table.el table.
  1531. When it sees such a table, it moves point into it and - if necessary -
  1532. calls `table-recognize-table'."
  1533. :group 'org-table-editing
  1534. :type 'boolean)
  1535. (defgroup org-link nil
  1536. "Options concerning links in Org mode."
  1537. :tag "Org Link"
  1538. :group 'org)
  1539. (defvar-local org-link-abbrev-alist-local nil
  1540. "Buffer-local version of `org-link-abbrev-alist', which see.
  1541. The value of this is taken from the #+LINK lines.")
  1542. (defcustom org-link-parameters
  1543. '(("doi" :follow org--open-doi-link)
  1544. ("elisp" :follow org--open-elisp-link)
  1545. ("file" :complete org-file-complete-link)
  1546. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1547. ("help" :follow org--open-help-link)
  1548. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1549. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1550. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1551. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1552. ("shell" :follow org--open-shell-link))
  1553. "An alist of properties that defines all the links in Org mode.
  1554. The key in each association is a string of the link type.
  1555. Subsequent optional elements make up a p-list of link properties.
  1556. :follow - A function that takes the link path as an argument.
  1557. :export - A function that takes the link path, description and
  1558. export-backend as arguments.
  1559. :store - A function responsible for storing the link. See the
  1560. function `org-store-link-functions'.
  1561. :complete - A function that inserts a link with completion. The
  1562. function takes one optional prefix arg.
  1563. :face - A face for the link, or a function that returns a face.
  1564. The function takes one argument which is the link path. The
  1565. default face is `org-link'.
  1566. :mouse-face - The mouse-face. The default is `highlight'.
  1567. :display - `full' will not fold the link in descriptive
  1568. display. Default is `org-link'.
  1569. :help-echo - A string or function that takes (window object position)
  1570. as arguments and returns a string.
  1571. :keymap - A keymap that is active on the link. The default is
  1572. `org-mouse-map'.
  1573. :htmlize-link - A function for the htmlize-link. Defaults
  1574. to (list :uri \"type:path\")
  1575. :activate-func - A function to run at the end of font-lock
  1576. activation. The function must accept (link-start link-end path bracketp)
  1577. as arguments."
  1578. :group 'org-link
  1579. :type '(alist :tag "Link display parameters"
  1580. :value-type plist)
  1581. :version "26.1"
  1582. :package-version '(Org . "9.1"))
  1583. (defun org-link-get-parameter (type key)
  1584. "Get TYPE link property for KEY.
  1585. TYPE is a string and KEY is a plist keyword."
  1586. (plist-get
  1587. (cdr (assoc type org-link-parameters))
  1588. key))
  1589. (defun org-link-set-parameters (type &rest parameters)
  1590. "Set link TYPE properties to PARAMETERS.
  1591. PARAMETERS should be :key val pairs."
  1592. (let ((data (assoc type org-link-parameters)))
  1593. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1594. (push (cons type parameters) org-link-parameters)
  1595. (org-make-link-regexps)
  1596. (org-element-update-syntax))))
  1597. (defun org-link-types ()
  1598. "Return a list of known link types."
  1599. (mapcar #'car org-link-parameters))
  1600. (defcustom org-link-abbrev-alist nil
  1601. "Alist of link abbreviations.
  1602. The car of each element is a string, to be replaced at the start of a link.
  1603. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1604. links in Org buffers can have an optional tag after a double colon, e.g.,
  1605. [[linkkey:tag][description]]
  1606. The `linkkey' must be a single word, starting with a letter, followed
  1607. by letters, numbers, `-' or `_'.
  1608. If REPLACE is a string, the tag will simply be appended to create the link.
  1609. If the string contains \"%s\", the tag will be inserted there. If the string
  1610. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1611. at that point (see the function `url-hexify-string'). If the string contains
  1612. the specifier \"%(my-function)\", then the custom function `my-function' will
  1613. be invoked: this function takes the tag as its only argument and must return
  1614. a string.
  1615. REPLACE may also be a function that will be called with the tag as the
  1616. only argument to create the link, which should be returned as a string.
  1617. See the manual for examples."
  1618. :group 'org-link
  1619. :type '(repeat
  1620. (cons
  1621. (string :tag "Protocol")
  1622. (choice
  1623. (string :tag "Format")
  1624. (function)))))
  1625. (defcustom org-descriptive-links t
  1626. "Non-nil means Org will display descriptive links.
  1627. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1628. \"Org Website\", hiding the link itself and just displaying its
  1629. description. When set to nil, Org will display the full links
  1630. literally.
  1631. You can interactively set the value of this variable by calling
  1632. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1633. :group 'org-link
  1634. :type 'boolean)
  1635. (defcustom org-link-file-path-type 'adaptive
  1636. "How the path name in file links should be stored.
  1637. Valid values are:
  1638. relative Relative to the current directory, i.e. the directory of the file
  1639. into which the link is being inserted.
  1640. absolute Absolute path, if possible with ~ for home directory.
  1641. noabbrev Absolute path, no abbreviation of home directory.
  1642. adaptive Use relative path for files in the current directory and sub-
  1643. directories of it. For other files, use an absolute path."
  1644. :group 'org-link
  1645. :type '(choice
  1646. (const relative)
  1647. (const absolute)
  1648. (const noabbrev)
  1649. (const adaptive)))
  1650. (defvaralias 'org-activate-links 'org-highlight-links)
  1651. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1652. "Types of links that should be highlighted in Org files.
  1653. This is a list of symbols, each one of them leading to the
  1654. highlighting of a certain link type.
  1655. You can still open links that are not highlighted.
  1656. In principle, it does not hurt to turn on highlighting for all
  1657. link types. There may be a small gain when turning off unused
  1658. link types. The types are:
  1659. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1660. angle Links in angular brackets that may contain whitespace like
  1661. <bbdb:Carsten Dominik>.
  1662. plain Plain links in normal text, no whitespace, like http://google.com.
  1663. radio Text that is matched by a radio target, see manual for details.
  1664. tag Tag settings in a headline (link to tag search).
  1665. date Time stamps (link to calendar).
  1666. footnote Footnote labels.
  1667. If you set this variable during an Emacs session, use `org-mode-restart'
  1668. in the Org buffer so that the change takes effect."
  1669. :group 'org-link
  1670. :group 'org-appearance
  1671. :type '(set :greedy t
  1672. (const :tag "Double bracket links" bracket)
  1673. (const :tag "Angular bracket links" angle)
  1674. (const :tag "Plain text links" plain)
  1675. (const :tag "Radio target matches" radio)
  1676. (const :tag "Tags" tag)
  1677. (const :tag "Timestamps" date)
  1678. (const :tag "Footnotes" footnote)))
  1679. (defcustom org-make-link-description-function nil
  1680. "Function to use for generating link descriptions from links.
  1681. This function must take two parameters: the first one is the
  1682. link, the second one is the description generated by
  1683. `org-insert-link'. The function should return the description to
  1684. use."
  1685. :group 'org-link
  1686. :type '(choice (const nil) (function)))
  1687. (defgroup org-link-store nil
  1688. "Options concerning storing links in Org mode."
  1689. :tag "Org Store Link"
  1690. :group 'org-link)
  1691. (defcustom org-url-hexify-p t
  1692. "When non-nil, hexify URL when creating a link."
  1693. :type 'boolean
  1694. :version "24.3"
  1695. :group 'org-link-store)
  1696. (defcustom org-email-link-description-format "Email %c: %.30s"
  1697. "Format of the description part of a link to an email or usenet message.
  1698. The following %-escapes will be replaced by corresponding information:
  1699. %F full \"From\" field
  1700. %f name, taken from \"From\" field, address if no name
  1701. %T full \"To\" field
  1702. %t first name in \"To\" field, address if no name
  1703. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1704. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1705. %s subject
  1706. %d date
  1707. %m message-id.
  1708. You may use normal field width specification between the % and the letter.
  1709. This is for example useful to limit the length of the subject.
  1710. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1711. :group 'org-link-store
  1712. :type 'string)
  1713. (defcustom org-from-is-user-regexp
  1714. (let (r1 r2)
  1715. (when (and user-mail-address (not (string= user-mail-address "")))
  1716. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1717. (when (and user-full-name (not (string= user-full-name "")))
  1718. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1719. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1720. "Regexp matched against the \"From:\" header of an email or usenet message.
  1721. It should match if the message is from the user him/herself."
  1722. :group 'org-link-store
  1723. :type 'regexp)
  1724. (defcustom org-context-in-file-links t
  1725. "Non-nil means file links from `org-store-link' contain context.
  1726. \\<org-mode-map>
  1727. A search string will be added to the file name with :: as separator
  1728. and used to find the context when the link is activated by the command
  1729. `org-open-at-point'. When this option is t, the entire active region
  1730. will be placed in the search string of the file link. If set to a
  1731. positive integer, only the first n lines of context will be stored.
  1732. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1733. \\[org-store-link]')
  1734. negates this setting for the duration of the command."
  1735. :group 'org-link-store
  1736. :type '(choice boolean integer))
  1737. (defcustom org-keep-stored-link-after-insertion nil
  1738. "Non-nil means keep link in list for entire session.
  1739. \\<org-mode-map>
  1740. The command `org-store-link' adds a link pointing to the current
  1741. location to an internal list. These links accumulate during a session.
  1742. The command `org-insert-link' can be used to insert links into any
  1743. Org file (offering completion for all stored links).
  1744. When this option is nil, every link which has been inserted once using
  1745. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1746. unused
  1747. links more efficient."
  1748. :group 'org-link-store
  1749. :type 'boolean)
  1750. (defgroup org-link-follow nil
  1751. "Options concerning following links in Org mode."
  1752. :tag "Org Follow Link"
  1753. :group 'org-link)
  1754. (defcustom org-link-translation-function nil
  1755. "Function to translate links with different syntax to Org syntax.
  1756. This can be used to translate links created for example by the Planner
  1757. or emacs-wiki packages to Org syntax.
  1758. The function must accept two parameters, a TYPE containing the link
  1759. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1760. which is everything after the link protocol. It should return a cons
  1761. with possibly modified values of type and path.
  1762. Org contains a function for this, so if you set this variable to
  1763. `org-translate-link-from-planner', you should be able follow many
  1764. links created by planner."
  1765. :group 'org-link-follow
  1766. :type '(choice (const nil) (function)))
  1767. (defcustom org-follow-link-hook nil
  1768. "Hook that is run after a link has been followed."
  1769. :group 'org-link-follow
  1770. :type 'hook)
  1771. (defcustom org-tab-follows-link nil
  1772. "Non-nil means on links TAB will follow the link.
  1773. Needs to be set before org.el is loaded.
  1774. This really should not be used, it does not make sense, and the
  1775. implementation is bad."
  1776. :group 'org-link-follow
  1777. :type 'boolean)
  1778. (defcustom org-return-follows-link nil
  1779. "Non-nil means on links RET will follow the link.
  1780. In tables, the special behavior of RET has precedence."
  1781. :group 'org-link-follow
  1782. :type 'boolean)
  1783. (defcustom org-mouse-1-follows-link
  1784. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1785. "Non-nil means mouse-1 on a link will follow the link.
  1786. A longer mouse click will still set point. Needs to be set
  1787. before org.el is loaded."
  1788. :group 'org-link-follow
  1789. :version "26.1"
  1790. :package-version '(Org . "8.3")
  1791. :type '(choice
  1792. (const :tag "A double click follows the link" double)
  1793. (const :tag "Unconditionally follow the link with mouse-1" t)
  1794. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1795. (defcustom org-mark-ring-length 4
  1796. "Number of different positions to be recorded in the ring.
  1797. Changing this requires a restart of Emacs to work correctly."
  1798. :group 'org-link-follow
  1799. :type 'integer)
  1800. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1801. "Non-nil means internal fuzzy links can only match headlines.
  1802. When nil, the a fuzzy link may point to a target or a named
  1803. construct in the document. When set to the special value
  1804. `query-to-create', offer to create a new headline when none
  1805. matched.
  1806. Spaces and statistics cookies are ignored during heading searches."
  1807. :group 'org-link-follow
  1808. :version "24.1"
  1809. :type '(choice
  1810. (const :tag "Use fuzzy text search" nil)
  1811. (const :tag "Match only exact headline" t)
  1812. (const :tag "Match exact headline or query to create it"
  1813. query-to-create))
  1814. :safe #'symbolp)
  1815. (defcustom org-link-frame-setup
  1816. '((vm . vm-visit-folder-other-frame)
  1817. (vm-imap . vm-visit-imap-folder-other-frame)
  1818. (gnus . org-gnus-no-new-news)
  1819. (file . find-file-other-window)
  1820. (wl . wl-other-frame))
  1821. "Setup the frame configuration for following links.
  1822. When following a link with Emacs, it may often be useful to display
  1823. this link in another window or frame. This variable can be used to
  1824. set this up for the different types of links.
  1825. For VM, use any of
  1826. `vm-visit-folder'
  1827. `vm-visit-folder-other-window'
  1828. `vm-visit-folder-other-frame'
  1829. For Gnus, use any of
  1830. `gnus'
  1831. `gnus-other-frame'
  1832. `org-gnus-no-new-news'
  1833. For FILE, use any of
  1834. `find-file'
  1835. `find-file-other-window'
  1836. `find-file-other-frame'
  1837. For Wanderlust use any of
  1838. `wl'
  1839. `wl-other-frame'
  1840. For the calendar, use the variable `calendar-setup'.
  1841. For BBDB, it is currently only possible to display the matches in
  1842. another window."
  1843. :group 'org-link-follow
  1844. :type '(list
  1845. (cons (const vm)
  1846. (choice
  1847. (const vm-visit-folder)
  1848. (const vm-visit-folder-other-window)
  1849. (const vm-visit-folder-other-frame)))
  1850. (cons (const vm-imap)
  1851. (choice
  1852. (const vm-visit-imap-folder)
  1853. (const vm-visit-imap-folder-other-window)
  1854. (const vm-visit-imap-folder-other-frame)))
  1855. (cons (const gnus)
  1856. (choice
  1857. (const gnus)
  1858. (const gnus-other-frame)
  1859. (const org-gnus-no-new-news)))
  1860. (cons (const file)
  1861. (choice
  1862. (const find-file)
  1863. (const find-file-other-window)
  1864. (const find-file-other-frame)))
  1865. (cons (const wl)
  1866. (choice
  1867. (const wl)
  1868. (const wl-other-frame)))))
  1869. (defcustom org-display-internal-link-with-indirect-buffer nil
  1870. "Non-nil means use indirect buffer to display infile links.
  1871. Activating internal links (from one location in a file to another location
  1872. in the same file) normally just jumps to the location. When the link is
  1873. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1874. is displayed in
  1875. another window. When this option is set, the other window actually displays
  1876. an indirect buffer clone of the current buffer, to avoid any visibility
  1877. changes to the current buffer."
  1878. :group 'org-link-follow
  1879. :type 'boolean)
  1880. (defcustom org-open-non-existing-files nil
  1881. "Non-nil means `org-open-file' will open non-existing files.
  1882. When nil, an error will be generated.
  1883. This variable applies only to external applications because they
  1884. might choke on non-existing files. If the link is to a file that
  1885. will be opened in Emacs, the variable is ignored."
  1886. :group 'org-link-follow
  1887. :type 'boolean)
  1888. (defcustom org-open-directory-means-index-dot-org nil
  1889. "Non-nil means a link to a directory really means to index.org.
  1890. When nil, following a directory link will run dired or open a finder/explorer
  1891. window on that directory."
  1892. :group 'org-link-follow
  1893. :type 'boolean)
  1894. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1895. "Non-nil means ask for confirmation before executing shell links.
  1896. Shell links can be dangerous: just think about a link
  1897. [[shell:rm -rf ~/*][Google Search]]
  1898. This link would show up in your Org document as \"Google Search\",
  1899. but really it would remove your entire home directory.
  1900. Therefore we advise against setting this variable to nil.
  1901. Just change it to `y-or-n-p' if you want to confirm with a
  1902. single keystroke rather than having to type \"yes\"."
  1903. :group 'org-link-follow
  1904. :type '(choice
  1905. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1906. (const :tag "with y-or-n (faster)" y-or-n-p)
  1907. (const :tag "no confirmation (dangerous)" nil)))
  1908. (put 'org-confirm-shell-link-function
  1909. 'safe-local-variable
  1910. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1911. (defcustom org-confirm-shell-link-not-regexp ""
  1912. "A regexp to skip confirmation for shell links."
  1913. :group 'org-link-follow
  1914. :version "24.1"
  1915. :type 'regexp)
  1916. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1917. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1918. Elisp links can be dangerous: just think about a link
  1919. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1920. This link would show up in your Org document as \"Google Search\",
  1921. but really it would remove your entire home directory.
  1922. Therefore we advise against setting this variable to nil.
  1923. Just change it to `y-or-n-p' if you want to confirm with a
  1924. single keystroke rather than having to type \"yes\"."
  1925. :group 'org-link-follow
  1926. :type '(choice
  1927. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1928. (const :tag "with y-or-n (faster)" y-or-n-p)
  1929. (const :tag "no confirmation (dangerous)" nil)))
  1930. (put 'org-confirm-shell-link-function
  1931. 'safe-local-variable
  1932. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1933. (defcustom org-confirm-elisp-link-not-regexp ""
  1934. "A regexp to skip confirmation for Elisp links."
  1935. :group 'org-link-follow
  1936. :version "24.1"
  1937. :type 'regexp)
  1938. (defconst org-file-apps-defaults-gnu
  1939. '((remote . emacs)
  1940. (system . mailcap)
  1941. (t . mailcap))
  1942. "Default file applications on a UNIX or GNU/Linux system.
  1943. See `org-file-apps'.")
  1944. (defconst org-file-apps-defaults-macosx
  1945. '((remote . emacs)
  1946. (system . "open %s")
  1947. ("ps.gz" . "gv %s")
  1948. ("eps.gz" . "gv %s")
  1949. ("dvi" . "xdvi %s")
  1950. ("fig" . "xfig %s")
  1951. (t . "open %s"))
  1952. "Default file applications on a macOS system.
  1953. The system \"open\" is known as a default, but we use X11 applications
  1954. for some files for which the OS does not have a good default.
  1955. See `org-file-apps'.")
  1956. (defconst org-file-apps-defaults-windowsnt
  1957. (list '(remote . emacs)
  1958. (cons 'system (lambda (file _path)
  1959. (with-no-warnings (w32-shell-execute "open" file))))
  1960. (cons t (lambda (file _path)
  1961. (with-no-warnings (w32-shell-execute "open" file)))))
  1962. "Default file applications on a Windows NT system.
  1963. The system \"open\" is used for most files.
  1964. See `org-file-apps'.")
  1965. (defcustom org-file-apps
  1966. '((auto-mode . emacs)
  1967. ("\\.mm\\'" . default)
  1968. ("\\.x?html?\\'" . default)
  1969. ("\\.pdf\\'" . default))
  1970. "External applications for opening `file:path' items in a document.
  1971. \\<org-mode-map>\
  1972. Org mode uses system defaults for different file types, but
  1973. you can use this variable to set the application for a given file
  1974. extension. The entries in this list are cons cells where the car identifies
  1975. files and the cdr the corresponding command.
  1976. Possible values for the file identifier are:
  1977. \"string\" A string as a file identifier can be interpreted in different
  1978. ways, depending on its contents:
  1979. - Alphanumeric characters only:
  1980. Match links with this file extension.
  1981. Example: (\"pdf\" . \"evince %s\")
  1982. to open PDFs with evince.
  1983. - Regular expression: Match links where the
  1984. filename matches the regexp. If you want to
  1985. use groups here, use shy groups.
  1986. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1987. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1988. to open *.html and *.xhtml with firefox.
  1989. - Regular expression which contains (non-shy) groups:
  1990. Match links where the whole link, including \"::\", and
  1991. anything after that, matches the regexp.
  1992. In a custom command string, %1, %2, etc. are replaced with
  1993. the parts of the link that were matched by the groups.
  1994. For backwards compatibility, if a command string is given
  1995. that does not use any of the group matches, this case is
  1996. handled identically to the second one (i.e. match against
  1997. file name only).
  1998. In a custom function, you can access the group matches with
  1999. (match-string n link).
  2000. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  2001. \"evince -p %1 %s\")
  2002. to open [[file:document.pdf::5]] with evince at page 5.
  2003. `directory' Matches a directory
  2004. `remote' Matches a remote file, accessible through tramp or efs.
  2005. Remote files most likely should be visited through Emacs
  2006. because external applications cannot handle such paths.
  2007. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2008. so all files Emacs knows how to handle. Using this with
  2009. command `emacs' will open most files in Emacs. Beware that this
  2010. will also open html files inside Emacs, unless you add
  2011. (\"html\" . default) to the list as well.
  2012. `system' The system command to open files, like `open' on Windows
  2013. and macOS, and mailcap under GNU/Linux. This is the command
  2014. that will be selected if you call `org-open-at-point' with a
  2015. double prefix argument (`\\[universal-argument] \
  2016. \\[universal-argument] \\[org-open-at-point]').
  2017. t Default for files not matched by any of the other options.
  2018. Possible values for the command are:
  2019. `emacs' The file will be visited by the current Emacs process.
  2020. `default' Use the default application for this file type, which is the
  2021. association for t in the list, most likely in the system-specific
  2022. part. This can be used to overrule an unwanted setting in the
  2023. system-specific variable.
  2024. `system' Use the system command for opening files, like \"open\".
  2025. This command is specified by the entry whose car is `system'.
  2026. Most likely, the system-specific version of this variable
  2027. does define this command, but you can overrule/replace it
  2028. here.
  2029. `mailcap' Use command specified in the mailcaps.
  2030. string A command to be executed by a shell; %s will be replaced
  2031. by the path to the file.
  2032. function A Lisp function, which will be called with two arguments:
  2033. the file path and the original link string, without the
  2034. \"file:\" prefix.
  2035. For more examples, see the system specific constants
  2036. `org-file-apps-defaults-macosx'
  2037. `org-file-apps-defaults-windowsnt'
  2038. `org-file-apps-defaults-gnu'."
  2039. :group 'org-link-follow
  2040. :type '(repeat
  2041. (cons (choice :value ""
  2042. (string :tag "Extension")
  2043. (const :tag "System command to open files" system)
  2044. (const :tag "Default for unrecognized files" t)
  2045. (const :tag "Remote file" remote)
  2046. (const :tag "Links to a directory" directory)
  2047. (const :tag "Any files that have Emacs modes"
  2048. auto-mode))
  2049. (choice :value ""
  2050. (const :tag "Visit with Emacs" emacs)
  2051. (const :tag "Use default" default)
  2052. (const :tag "Use the system command" system)
  2053. (string :tag "Command")
  2054. (function :tag "Function")))))
  2055. (defcustom org-doi-server-url "http://dx.doi.org/"
  2056. "The URL of the DOI server."
  2057. :type 'string
  2058. :version "24.3"
  2059. :group 'org-link-follow)
  2060. (defgroup org-refile nil
  2061. "Options concerning refiling entries in Org mode."
  2062. :tag "Org Refile"
  2063. :group 'org)
  2064. (defcustom org-directory "~/org"
  2065. "Directory with Org files.
  2066. This is just a default location to look for Org files. There is no need
  2067. at all to put your files into this directory. It is used in the
  2068. following situations:
  2069. 1. When a capture template specifies a target file that is not an
  2070. absolute path. The path will then be interpreted relative to
  2071. `org-directory'
  2072. 2. When the value of variable `org-agenda-files' is a single file, any
  2073. relative paths in this file will be taken as relative to
  2074. `org-directory'."
  2075. :group 'org-refile
  2076. :group 'org-capture
  2077. :type 'directory)
  2078. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2079. "Default target for storing notes.
  2080. Used as a fall back file for org-capture.el, for templates that
  2081. do not specify a target file."
  2082. :group 'org-refile
  2083. :group 'org-capture
  2084. :type 'file)
  2085. (defcustom org-reverse-note-order nil
  2086. "Non-nil means store new notes at the beginning of a file or entry.
  2087. When nil, new notes will be filed to the end of a file or entry.
  2088. This can also be a list with cons cells of regular expressions that
  2089. are matched against file names, and values."
  2090. :group 'org-capture
  2091. :group 'org-refile
  2092. :type '(choice
  2093. (const :tag "Reverse always" t)
  2094. (const :tag "Reverse never" nil)
  2095. (repeat :tag "By file name regexp"
  2096. (cons regexp boolean))))
  2097. (defcustom org-log-refile nil
  2098. "Information to record when a task is refiled.
  2099. Possible values are:
  2100. nil Don't add anything
  2101. time Add a time stamp to the task
  2102. note Prompt for a note and add it with template `org-log-note-headings'
  2103. This option can also be set with on a per-file-basis with
  2104. #+STARTUP: nologrefile
  2105. #+STARTUP: logrefile
  2106. #+STARTUP: lognoterefile
  2107. You can have local logging settings for a subtree by setting the LOGGING
  2108. property to one or more of these keywords.
  2109. When bulk-refiling from the agenda, the value `note' is forbidden and
  2110. will temporarily be changed to `time'."
  2111. :group 'org-refile
  2112. :group 'org-progress
  2113. :version "24.1"
  2114. :type '(choice
  2115. (const :tag "No logging" nil)
  2116. (const :tag "Record timestamp" time)
  2117. (const :tag "Record timestamp with note." note)))
  2118. (defcustom org-refile-targets nil
  2119. "Targets for refiling entries with `\\[org-refile]'.
  2120. This is a list of cons cells. Each cell contains:
  2121. - a specification of the files to be considered, either a list of files,
  2122. or a symbol whose function or variable value will be used to retrieve
  2123. a file name or a list of file names. If you use `org-agenda-files' for
  2124. that, all agenda files will be scanned for targets. Nil means consider
  2125. headings in the current buffer.
  2126. - A specification of how to find candidate refile targets. This may be
  2127. any of:
  2128. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2129. This tag has to be present in all target headlines, inheritance will
  2130. not be considered.
  2131. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2132. todo keyword.
  2133. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2134. headlines that are refiling targets.
  2135. - a cons cell (:level . N). Any headline of level N is considered a target.
  2136. Note that, when `org-odd-levels-only' is set, level corresponds to
  2137. order in hierarchy, not to the number of stars.
  2138. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2139. Note that, when `org-odd-levels-only' is set, level corresponds to
  2140. order in hierarchy, not to the number of stars.
  2141. Each element of this list generates a set of possible targets.
  2142. The union of these sets is presented (with completion) to
  2143. the user by `org-refile'.
  2144. You can set the variable `org-refile-target-verify-function' to a function
  2145. to verify each headline found by the simple criteria above.
  2146. When this variable is nil, all top-level headlines in the current buffer
  2147. are used, equivalent to the value `((nil . (:level . 1))'."
  2148. :group 'org-refile
  2149. :type '(repeat
  2150. (cons
  2151. (choice :value org-agenda-files
  2152. (const :tag "All agenda files" org-agenda-files)
  2153. (const :tag "Current buffer" nil)
  2154. (function) (variable) (file))
  2155. (choice :tag "Identify target headline by"
  2156. (cons :tag "Specific tag" (const :value :tag) (string))
  2157. (cons :tag "TODO keyword" (const :value :todo) (string))
  2158. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2159. (cons :tag "Level number" (const :value :level) (integer))
  2160. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2161. (defcustom org-refile-target-verify-function nil
  2162. "Function to verify if the headline at point should be a refile target.
  2163. The function will be called without arguments, with point at the
  2164. beginning of the headline. It should return t and leave point
  2165. where it is if the headline is a valid target for refiling.
  2166. If the target should not be selected, the function must return nil.
  2167. In addition to this, it may move point to a place from where the search
  2168. should be continued. For example, the function may decide that the entire
  2169. subtree of the current entry should be excluded and move point to the end
  2170. of the subtree."
  2171. :group 'org-refile
  2172. :type '(choice
  2173. (const nil)
  2174. (function)))
  2175. (defcustom org-refile-use-cache nil
  2176. "Non-nil means cache refile targets to speed up the process.
  2177. \\<org-mode-map>\
  2178. The cache for a particular file will be updated automatically when
  2179. the buffer has been killed, or when any of the marker used for flagging
  2180. refile targets no longer points at a live buffer.
  2181. If you have added new entries to a buffer that might themselves be targets,
  2182. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2183. if you find that easier, \
  2184. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2185. \\[org-refile]'."
  2186. :group 'org-refile
  2187. :version "24.1"
  2188. :type 'boolean)
  2189. (defcustom org-refile-use-outline-path nil
  2190. "Non-nil means provide refile targets as paths.
  2191. So a level 3 headline will be available as level1/level2/level3.
  2192. When the value is `file', also include the file name (without directory)
  2193. into the path. In this case, you can also stop the completion after
  2194. the file name, to get entries inserted as top level in the file.
  2195. When `full-file-path', include the full file path.
  2196. When `buffer-name', use the buffer name."
  2197. :group 'org-refile
  2198. :type '(choice
  2199. (const :tag "Not" nil)
  2200. (const :tag "Yes" t)
  2201. (const :tag "Start with file name" file)
  2202. (const :tag "Start with full file path" full-file-path)
  2203. (const :tag "Start with buffer name" buffer-name)))
  2204. (defcustom org-outline-path-complete-in-steps t
  2205. "Non-nil means complete the outline path in hierarchical steps.
  2206. When Org uses the refile interface to select an outline path (see
  2207. `org-refile-use-outline-path'), the completion of the path can be
  2208. done in a single go, or it can be done in steps down the headline
  2209. hierarchy. Going in steps is probably the best if you do not use
  2210. a special completion package like `ido' or `icicles'. However,
  2211. when using these packages, going in one step can be very fast,
  2212. while still showing the whole path to the entry."
  2213. :group 'org-refile
  2214. :type 'boolean)
  2215. (defcustom org-refile-allow-creating-parent-nodes nil
  2216. "Non-nil means allow the creation of new nodes as refile targets.
  2217. New nodes are then created by adding \"/new node name\" to the completion
  2218. of an existing node. When the value of this variable is `confirm',
  2219. new node creation must be confirmed by the user (recommended).
  2220. When nil, the completion must match an existing entry.
  2221. Note that, if the new heading is not seen by the criteria
  2222. listed in `org-refile-targets', multiple instances of the same
  2223. heading would be created by trying again to file under the new
  2224. heading."
  2225. :group 'org-refile
  2226. :type '(choice
  2227. (const :tag "Never" nil)
  2228. (const :tag "Always" t)
  2229. (const :tag "Prompt for confirmation" confirm)))
  2230. (defcustom org-refile-active-region-within-subtree nil
  2231. "Non-nil means also refile active region within a subtree.
  2232. By default `org-refile' doesn't allow refiling regions if they
  2233. don't contain a set of subtrees, but it might be convenient to
  2234. do so sometimes: in that case, the first line of the region is
  2235. converted to a headline before refiling."
  2236. :group 'org-refile
  2237. :version "24.1"
  2238. :type 'boolean)
  2239. (defgroup org-todo nil
  2240. "Options concerning TODO items in Org mode."
  2241. :tag "Org TODO"
  2242. :group 'org)
  2243. (defgroup org-progress nil
  2244. "Options concerning Progress logging in Org mode."
  2245. :tag "Org Progress"
  2246. :group 'org-time)
  2247. (defvar org-todo-interpretation-widgets
  2248. '((:tag "Sequence (cycling hits every state)" sequence)
  2249. (:tag "Type (cycling directly to DONE)" type))
  2250. "The available interpretation symbols for customizing `org-todo-keywords'.
  2251. Interested libraries should add to this list.")
  2252. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2253. "List of TODO entry keyword sequences and their interpretation.
  2254. \\<org-mode-map>This is a list of sequences.
  2255. Each sequence starts with a symbol, either `sequence' or `type',
  2256. indicating if the keywords should be interpreted as a sequence of
  2257. action steps, or as different types of TODO items. The first
  2258. keywords are states requiring action - these states will select a headline
  2259. for inclusion into the global TODO list Org produces. If one of the
  2260. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2261. signify that no further action is necessary. If \"|\" is not found,
  2262. the last keyword is treated as the only DONE state of the sequence.
  2263. The command `\\[org-todo]' cycles an entry through these states, and one
  2264. additional state where no keyword is present. For details about this
  2265. cycling, see the manual.
  2266. TODO keywords and interpretation can also be set on a per-file basis with
  2267. the special #+SEQ_TODO and #+TYP_TODO lines.
  2268. Each keyword can optionally specify a character for fast state selection
  2269. \(in combination with the variable `org-use-fast-todo-selection')
  2270. and specifiers for state change logging, using the same syntax that
  2271. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2272. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2273. indicates to record a time stamp each time this state is selected.
  2274. Each keyword may also specify if a timestamp or a note should be
  2275. recorded when entering or leaving the state, by adding additional
  2276. characters in the parenthesis after the keyword. This looks like this:
  2277. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2278. record only the time of the state change. With X and Y being either
  2279. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2280. Y when leaving the state if and only if the *target* state does not
  2281. define X. You may omit any of the fast-selection key or X or /Y,
  2282. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2283. For backward compatibility, this variable may also be just a list
  2284. of keywords. In this case the interpretation (sequence or type) will be
  2285. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2286. :group 'org-todo
  2287. :group 'org-keywords
  2288. :type '(choice
  2289. (repeat :tag "Old syntax, just keywords"
  2290. (string :tag "Keyword"))
  2291. (repeat :tag "New syntax"
  2292. (cons
  2293. (choice
  2294. :tag "Interpretation"
  2295. ;;Quick and dirty way to see
  2296. ;;`org-todo-interpretations'. This takes the
  2297. ;;place of item arguments
  2298. :convert-widget
  2299. (lambda (widget)
  2300. (widget-put widget
  2301. :args (mapcar
  2302. (lambda (x)
  2303. (widget-convert
  2304. (cons 'const x)))
  2305. org-todo-interpretation-widgets))
  2306. widget))
  2307. (repeat
  2308. (string :tag "Keyword"))))))
  2309. (defvar-local org-todo-keywords-1 nil
  2310. "All TODO and DONE keywords active in a buffer.")
  2311. (defvar org-todo-keywords-for-agenda nil)
  2312. (defvar org-done-keywords-for-agenda nil)
  2313. (defvar org-todo-keyword-alist-for-agenda nil)
  2314. (defvar org-tag-alist-for-agenda nil
  2315. "Alist of all tags from all agenda files.")
  2316. (defvar org-tag-groups-alist-for-agenda nil
  2317. "Alist of all groups tags from all current agenda files.")
  2318. (defvar-local org-tag-groups-alist nil)
  2319. (defvar org-agenda-contributing-files nil)
  2320. (defvar-local org-current-tag-alist nil
  2321. "Alist of all tag groups in current buffer.
  2322. This variable takes into consideration `org-tag-alist',
  2323. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2324. (defvar-local org-not-done-keywords nil)
  2325. (defvar-local org-done-keywords nil)
  2326. (defvar-local org-todo-heads nil)
  2327. (defvar-local org-todo-sets nil)
  2328. (defvar-local org-todo-log-states nil)
  2329. (defvar-local org-todo-kwd-alist nil)
  2330. (defvar-local org-todo-key-alist nil)
  2331. (defvar-local org-todo-key-trigger nil)
  2332. (defcustom org-todo-interpretation 'sequence
  2333. "Controls how TODO keywords are interpreted.
  2334. This variable is in principle obsolete and is only used for
  2335. backward compatibility, if the interpretation of todo keywords is
  2336. not given already in `org-todo-keywords'. See that variable for
  2337. more information."
  2338. :group 'org-todo
  2339. :group 'org-keywords
  2340. :type '(choice (const sequence)
  2341. (const type)))
  2342. (defcustom org-use-fast-todo-selection t
  2343. "\\<org-mode-map>\
  2344. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2345. This variable describes if and under what circumstances the cycling
  2346. mechanism for TODO keywords will be replaced by a single-key, direct
  2347. selection scheme.
  2348. When nil, fast selection is never used.
  2349. When the symbol `prefix', it will be used when `org-todo' is called
  2350. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2351. in an Org buffer, and
  2352. `\\[universal-argument] t' in an agenda buffer.
  2353. When t, fast selection is used by default. In this case, the prefix
  2354. argument forces cycling instead.
  2355. In all cases, the special interface is only used if access keys have
  2356. actually been assigned by the user, i.e. if keywords in the configuration
  2357. are followed by a letter in parenthesis, like TODO(t)."
  2358. :group 'org-todo
  2359. :type '(choice
  2360. (const :tag "Never" nil)
  2361. (const :tag "By default" t)
  2362. (const :tag "Only with C-u C-c C-t" prefix)))
  2363. (defcustom org-provide-todo-statistics t
  2364. "Non-nil means update todo statistics after insert and toggle.
  2365. ALL-HEADLINES means update todo statistics by including headlines
  2366. with no TODO keyword as well, counting them as not done.
  2367. A list of TODO keywords means the same, but skip keywords that are
  2368. not in this list.
  2369. When set to a list of two lists, the first list contains keywords
  2370. to consider as TODO keywords, the second list contains keywords
  2371. to consider as DONE keywords.
  2372. When this is set, todo statistics is updated in the parent of the
  2373. current entry each time a todo state is changed."
  2374. :group 'org-todo
  2375. :type '(choice
  2376. (const :tag "Yes, only for TODO entries" t)
  2377. (const :tag "Yes, including all entries" all-headlines)
  2378. (repeat :tag "Yes, for TODOs in this list"
  2379. (string :tag "TODO keyword"))
  2380. (list :tag "Yes, for TODOs and DONEs in these lists"
  2381. (repeat (string :tag "TODO keyword"))
  2382. (repeat (string :tag "DONE keyword")))
  2383. (other :tag "No TODO statistics" nil)))
  2384. (defcustom org-hierarchical-todo-statistics t
  2385. "Non-nil means TODO statistics covers just direct children.
  2386. When nil, all entries in the subtree are considered.
  2387. This has only an effect if `org-provide-todo-statistics' is set.
  2388. To set this to nil for only a single subtree, use a COOKIE_DATA
  2389. property and include the word \"recursive\" into the value."
  2390. :group 'org-todo
  2391. :type 'boolean)
  2392. (defcustom org-after-todo-state-change-hook nil
  2393. "Hook which is run after the state of a TODO item was changed.
  2394. The new state (a string with a TODO keyword, or nil) is available in the
  2395. Lisp variable `org-state'."
  2396. :group 'org-todo
  2397. :type 'hook)
  2398. (defvar org-blocker-hook nil
  2399. "Hook for functions that are allowed to block a state change.
  2400. Functions in this hook should not modify the buffer.
  2401. Each function gets as its single argument a property list,
  2402. see `org-trigger-hook' for more information about this list.
  2403. If any of the functions in this hook returns nil, the state change
  2404. is blocked.")
  2405. (defvar org-trigger-hook nil
  2406. "Hook for functions that are triggered by a state change.
  2407. Each function gets as its single argument a property list with at
  2408. least the following elements:
  2409. (:type type-of-change :position pos-at-entry-start
  2410. :from old-state :to new-state)
  2411. Depending on the type, more properties may be present.
  2412. This mechanism is currently implemented for:
  2413. TODO state changes
  2414. ------------------
  2415. :type todo-state-change
  2416. :from previous state (keyword as a string), or nil, or a symbol
  2417. `todo' or `done', to indicate the general type of state.
  2418. :to new state, like in :from")
  2419. (defcustom org-enforce-todo-dependencies nil
  2420. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2421. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2422. be blocked if any prior sibling is not yet done.
  2423. Finally, if the parent is blocked because of ordered siblings of its own,
  2424. the child will also be blocked."
  2425. :set (lambda (var val)
  2426. (set var val)
  2427. (if val
  2428. (add-hook 'org-blocker-hook
  2429. 'org-block-todo-from-children-or-siblings-or-parent)
  2430. (remove-hook 'org-blocker-hook
  2431. 'org-block-todo-from-children-or-siblings-or-parent)))
  2432. :group 'org-todo
  2433. :type 'boolean)
  2434. (defcustom org-enforce-todo-checkbox-dependencies nil
  2435. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2436. When this is nil, checkboxes have no influence on switching TODO states.
  2437. When non-nil, you first need to check off all check boxes before the TODO
  2438. entry can be switched to DONE.
  2439. This variable needs to be set before org.el is loaded, and you need to
  2440. restart Emacs after a change to make the change effective. The only way
  2441. to change it while Emacs is running is through the customize interface."
  2442. :set (lambda (var val)
  2443. (set var val)
  2444. (if val
  2445. (add-hook 'org-blocker-hook
  2446. 'org-block-todo-from-checkboxes)
  2447. (remove-hook 'org-blocker-hook
  2448. 'org-block-todo-from-checkboxes)))
  2449. :group 'org-todo
  2450. :type 'boolean)
  2451. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2452. "Non-nil means inserting a TODO heading is treated as state change.
  2453. So when the command `\\[org-insert-todo-heading]' is used, state change
  2454. logging will apply if appropriate. When nil, the new TODO item will
  2455. be inserted directly, and no logging will take place."
  2456. :group 'org-todo
  2457. :type 'boolean)
  2458. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2459. "Non-nil means switching TODO states with S-cursor counts as state change.
  2460. This is the default behavior. However, setting this to nil allows a
  2461. convenient way to select a TODO state and bypass any logging associated
  2462. with that."
  2463. :group 'org-todo
  2464. :type 'boolean)
  2465. (defcustom org-todo-state-tags-triggers nil
  2466. "Tag changes that should be triggered by TODO state changes.
  2467. This is a list. Each entry is
  2468. (state-change (tag . flag) .......)
  2469. State-change can be a string with a state, and empty string to indicate the
  2470. state that has no TODO keyword, or it can be one of the symbols `todo'
  2471. or `done', meaning any not-done or done state, respectively."
  2472. :group 'org-todo
  2473. :group 'org-tags
  2474. :type '(repeat
  2475. (cons (choice :tag "When changing to"
  2476. (const :tag "Not-done state" todo)
  2477. (const :tag "Done state" done)
  2478. (string :tag "State"))
  2479. (repeat
  2480. (cons :tag "Tag action"
  2481. (string :tag "Tag")
  2482. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2483. (defcustom org-log-done nil
  2484. "Information to record when a task moves to the DONE state.
  2485. Possible values are:
  2486. nil Don't add anything, just change the keyword
  2487. time Add a time stamp to the task
  2488. note Prompt for a note and add it with template `org-log-note-headings'
  2489. This option can also be set with on a per-file-basis with
  2490. #+STARTUP: nologdone
  2491. #+STARTUP: logdone
  2492. #+STARTUP: lognotedone
  2493. You can have local logging settings for a subtree by setting the LOGGING
  2494. property to one or more of these keywords."
  2495. :group 'org-todo
  2496. :group 'org-progress
  2497. :type '(choice
  2498. (const :tag "No logging" nil)
  2499. (const :tag "Record CLOSED timestamp" time)
  2500. (const :tag "Record CLOSED timestamp with note." note)))
  2501. ;; Normalize old uses of org-log-done.
  2502. (cond
  2503. ((eq org-log-done t) (setq org-log-done 'time))
  2504. ((and (listp org-log-done) (memq 'done org-log-done))
  2505. (setq org-log-done 'note)))
  2506. (defcustom org-log-reschedule nil
  2507. "Information to record when the scheduling date of a task is modified.
  2508. Possible values are:
  2509. nil Don't add anything, just change the date
  2510. time Add a time stamp to the task
  2511. note Prompt for a note and add it with template `org-log-note-headings'
  2512. This option can also be set with on a per-file-basis with
  2513. #+STARTUP: nologreschedule
  2514. #+STARTUP: logreschedule
  2515. #+STARTUP: lognotereschedule
  2516. You can have local logging settings for a subtree by setting the LOGGING
  2517. property to one or more of these keywords.
  2518. This variable has an effect when calling `org-schedule' or
  2519. `org-agenda-schedule' only."
  2520. :group 'org-todo
  2521. :group 'org-progress
  2522. :type '(choice
  2523. (const :tag "No logging" nil)
  2524. (const :tag "Record timestamp" time)
  2525. (const :tag "Record timestamp with note" note)))
  2526. (defcustom org-log-redeadline nil
  2527. "Information to record when the deadline date of a task is modified.
  2528. Possible values are:
  2529. nil Don't add anything, just change the date
  2530. time Add a time stamp to the task
  2531. note Prompt for a note and add it with template `org-log-note-headings'
  2532. This option can also be set with on a per-file-basis with
  2533. #+STARTUP: nologredeadline
  2534. #+STARTUP: logredeadline
  2535. #+STARTUP: lognoteredeadline
  2536. You can have local logging settings for a subtree by setting the LOGGING
  2537. property to one or more of these keywords.
  2538. This variable has an effect when calling `org-deadline' or
  2539. `org-agenda-deadline' only."
  2540. :group 'org-todo
  2541. :group 'org-progress
  2542. :type '(choice
  2543. (const :tag "No logging" nil)
  2544. (const :tag "Record timestamp" time)
  2545. (const :tag "Record timestamp with note." note)))
  2546. (defcustom org-log-note-clock-out nil
  2547. "Non-nil means record a note when clocking out of an item.
  2548. This can also be configured on a per-file basis by adding one of
  2549. the following lines anywhere in the buffer:
  2550. #+STARTUP: lognoteclock-out
  2551. #+STARTUP: nolognoteclock-out"
  2552. :group 'org-todo
  2553. :group 'org-progress
  2554. :type 'boolean)
  2555. (defcustom org-log-done-with-time t
  2556. "Non-nil means the CLOSED time stamp will contain date and time.
  2557. When nil, only the date will be recorded."
  2558. :group 'org-progress
  2559. :type 'boolean)
  2560. (defcustom org-log-note-headings
  2561. '((done . "CLOSING NOTE %t")
  2562. (state . "State %-12s from %-12S %t")
  2563. (note . "Note taken on %t")
  2564. (reschedule . "Rescheduled from %S on %t")
  2565. (delschedule . "Not scheduled, was %S on %t")
  2566. (redeadline . "New deadline from %S on %t")
  2567. (deldeadline . "Removed deadline, was %S on %t")
  2568. (refile . "Refiled on %t")
  2569. (clock-out . ""))
  2570. "Headings for notes added to entries.
  2571. The value is an alist, with the car being a symbol indicating the
  2572. note context, and the cdr is the heading to be used. The heading
  2573. may also be the empty string. The following placeholders can be
  2574. used:
  2575. %t a time stamp.
  2576. %T an active time stamp instead the default inactive one
  2577. %d a short-format time stamp.
  2578. %D an active short-format time stamp.
  2579. %s the new TODO state or time stamp (inactive), in double quotes.
  2580. %S the old TODO state or time stamp (inactive), in double quotes.
  2581. %u the user name.
  2582. %U full user name.
  2583. In fact, it is not a good idea to change the `state' entry,
  2584. because Agenda Log mode depends on the format of these entries."
  2585. :group 'org-todo
  2586. :group 'org-progress
  2587. :type '(list :greedy t
  2588. (cons (const :tag "Heading when closing an item" done) string)
  2589. (cons (const :tag
  2590. "Heading when changing todo state (todo sequence only)"
  2591. state) string)
  2592. (cons (const :tag "Heading when just taking a note" note) string)
  2593. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2594. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2595. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2596. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2597. (cons (const :tag "Heading when refiling" refile) string)
  2598. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2599. (unless (assq 'note org-log-note-headings)
  2600. (push '(note . "%t") org-log-note-headings))
  2601. (defcustom org-log-into-drawer nil
  2602. "Non-nil means insert state change notes and time stamps into a drawer.
  2603. When nil, state changes notes will be inserted after the headline and
  2604. any scheduling and clock lines, but not inside a drawer.
  2605. The value of this variable should be the name of the drawer to use.
  2606. LOGBOOK is proposed as the default drawer for this purpose, you can
  2607. also set this to a string to define the drawer of your choice.
  2608. A value of t is also allowed, representing \"LOGBOOK\".
  2609. A value of t or nil can also be set with on a per-file-basis with
  2610. #+STARTUP: logdrawer
  2611. #+STARTUP: nologdrawer
  2612. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2613. will be ignored.
  2614. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2615. a subtree.
  2616. Do not check directly this variable in a Lisp program. Call
  2617. function `org-log-into-drawer' instead."
  2618. :group 'org-todo
  2619. :group 'org-progress
  2620. :type '(choice
  2621. (const :tag "Not into a drawer" nil)
  2622. (const :tag "LOGBOOK" t)
  2623. (string :tag "Other")))
  2624. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2625. (defun org-log-into-drawer ()
  2626. "Name of the log drawer, as a string, or nil.
  2627. This is the value of `org-log-into-drawer'. However, if the
  2628. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2629. be used instead of the default value."
  2630. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2631. (cond ((equal p "nil") nil)
  2632. ((equal p "t") "LOGBOOK")
  2633. ((stringp p) p)
  2634. (p "LOGBOOK")
  2635. ((stringp org-log-into-drawer) org-log-into-drawer)
  2636. (org-log-into-drawer "LOGBOOK"))))
  2637. (defcustom org-log-state-notes-insert-after-drawers nil
  2638. "Non-nil means insert state change notes after any drawers in entry.
  2639. Only the drawers that *immediately* follow the headline and the
  2640. deadline/scheduled line are skipped.
  2641. When nil, insert notes right after the heading and perhaps the line
  2642. with deadline/scheduling if present.
  2643. This variable will have no effect if `org-log-into-drawer' is
  2644. set."
  2645. :group 'org-todo
  2646. :group 'org-progress
  2647. :type 'boolean)
  2648. (defcustom org-log-states-order-reversed t
  2649. "Non-nil means the latest state note will be directly after heading.
  2650. When nil, the state change notes will be ordered according to time.
  2651. This option can also be set with on a per-file-basis with
  2652. #+STARTUP: logstatesreversed
  2653. #+STARTUP: nologstatesreversed"
  2654. :group 'org-todo
  2655. :group 'org-progress
  2656. :type 'boolean)
  2657. (defcustom org-todo-repeat-to-state nil
  2658. "The TODO state to which a repeater should return the repeating task.
  2659. By default this is the first task of a TODO sequence or the
  2660. previous state of a TYPE_TODO set. But you can specify to use
  2661. the previous state in a TODO sequence or a string.
  2662. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2663. entry, which has precedence over this option."
  2664. :group 'org-todo
  2665. :version "24.1"
  2666. :type '(choice (const :tag "Use the previous TODO state" t)
  2667. (const :tag "Use the head of the TODO sequence" nil)
  2668. (string :tag "Use a specific TODO state")))
  2669. (defcustom org-log-repeat 'time
  2670. "Non-nil means record moving through the DONE state when triggering repeat.
  2671. An auto-repeating task is immediately switched back to TODO when
  2672. marked DONE. If you are not logging state changes (by adding \"@\"
  2673. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2674. record a closing note, there will be no record of the task moving
  2675. through DONE. This variable forces taking a note anyway.
  2676. nil Don't force a record
  2677. time Record a time stamp
  2678. note Prompt for a note and add it with template `org-log-note-headings'
  2679. This option can also be set with on a per-file-basis with
  2680. #+STARTUP: nologrepeat
  2681. #+STARTUP: logrepeat
  2682. #+STARTUP: lognoterepeat
  2683. You can have local logging settings for a subtree by setting the LOGGING
  2684. property to one or more of these keywords."
  2685. :group 'org-todo
  2686. :group 'org-progress
  2687. :type '(choice
  2688. (const :tag "Don't force a record" nil)
  2689. (const :tag "Force recording the DONE state" time)
  2690. (const :tag "Force recording a note with the DONE state" note)))
  2691. (defgroup org-priorities nil
  2692. "Priorities in Org mode."
  2693. :tag "Org Priorities"
  2694. :group 'org-todo)
  2695. (defcustom org-enable-priority-commands t
  2696. "Non-nil means priority commands are active.
  2697. When nil, these commands will be disabled, so that you never accidentally
  2698. set a priority."
  2699. :group 'org-priorities
  2700. :type 'boolean)
  2701. (defcustom org-highest-priority ?A
  2702. "The highest priority of TODO items. A character like ?A, ?B etc.
  2703. Must have a smaller ASCII number than `org-lowest-priority'."
  2704. :group 'org-priorities
  2705. :type 'character)
  2706. (defcustom org-lowest-priority ?C
  2707. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2708. Must have a larger ASCII number than `org-highest-priority'."
  2709. :group 'org-priorities
  2710. :type 'character)
  2711. (defcustom org-default-priority ?B
  2712. "The default priority of TODO items.
  2713. This is the priority an item gets if no explicit priority is given.
  2714. When starting to cycle on an empty priority the first step in the cycle
  2715. depends on `org-priority-start-cycle-with-default'. The resulting first
  2716. step priority must not exceed the range from `org-highest-priority' to
  2717. `org-lowest-priority' which means that `org-default-priority' has to be
  2718. in this range exclusive or inclusive the range boundaries. Else the
  2719. first step refuses to set the default and the second will fall back
  2720. to (depending on the command used) the highest or lowest priority."
  2721. :group 'org-priorities
  2722. :type 'character)
  2723. (defcustom org-priority-start-cycle-with-default t
  2724. "Non-nil means start with default priority when starting to cycle.
  2725. When this is nil, the first step in the cycle will be (depending on the
  2726. command used) one higher or lower than the default priority.
  2727. See also `org-default-priority'."
  2728. :group 'org-priorities
  2729. :type 'boolean)
  2730. (defcustom org-get-priority-function nil
  2731. "Function to extract the priority from a string.
  2732. The string is normally the headline. If this is nil Org computes the
  2733. priority from the priority cookie like [#A] in the headline. It returns
  2734. an integer, increasing by 1000 for each priority level.
  2735. The user can set a different function here, which should take a string
  2736. as an argument and return the numeric priority."
  2737. :group 'org-priorities
  2738. :version "24.1"
  2739. :type '(choice
  2740. (const nil)
  2741. (function)))
  2742. (defgroup org-time nil
  2743. "Options concerning time stamps and deadlines in Org mode."
  2744. :tag "Org Time"
  2745. :group 'org)
  2746. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2747. "Number of minutes to round time stamps to.
  2748. \\<org-mode-map>\
  2749. These are two values, the first applies when first creating a time stamp.
  2750. The second applies when changing it with the commands `S-up' and `S-down'.
  2751. When changing the time stamp, this means that it will change in steps
  2752. of N minutes, as given by the second value.
  2753. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2754. numbers should be factors of 60, so for example 5, 10, 15.
  2755. When this is larger than 1, you can still force an exact time stamp by using
  2756. a double prefix argument to a time stamp command like \
  2757. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2758. and by using a prefix arg to `S-up/down' to specify the exact number
  2759. of minutes to shift."
  2760. :group 'org-time
  2761. :get (lambda (var) ; Make sure both elements are there
  2762. (if (integerp (default-value var))
  2763. (list (default-value var) 5)
  2764. (default-value var)))
  2765. :type '(list
  2766. (integer :tag "when inserting times")
  2767. (integer :tag "when modifying times")))
  2768. ;; Normalize old customizations of this variable.
  2769. (when (integerp org-time-stamp-rounding-minutes)
  2770. (setq org-time-stamp-rounding-minutes
  2771. (list org-time-stamp-rounding-minutes
  2772. org-time-stamp-rounding-minutes)))
  2773. (defcustom org-display-custom-times nil
  2774. "Non-nil means overlay custom formats over all time stamps.
  2775. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2776. To turn this on on a per-file basis, insert anywhere in the file:
  2777. #+STARTUP: customtime"
  2778. :group 'org-time
  2779. :set 'set-default
  2780. :type 'sexp)
  2781. (make-variable-buffer-local 'org-display-custom-times)
  2782. (defcustom org-time-stamp-custom-formats
  2783. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2784. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2785. These are overlaid over the default ISO format if the variable
  2786. `org-display-custom-times' is set. Time like %H:%M should be at the
  2787. end of the second format. The custom formats are also honored by export
  2788. commands, if custom time display is turned on at the time of export."
  2789. :group 'org-time
  2790. :type 'sexp)
  2791. (defun org-time-stamp-format (&optional long inactive)
  2792. "Get the right format for a time string."
  2793. (let ((f (if long (cdr org-time-stamp-formats)
  2794. (car org-time-stamp-formats))))
  2795. (if inactive
  2796. (concat "[" (substring f 1 -1) "]")
  2797. f)))
  2798. (defcustom org-deadline-warning-days 14
  2799. "Number of days before expiration during which a deadline becomes active.
  2800. This variable governs the display in sparse trees and in the agenda.
  2801. When 0 or negative, it means use this number (the absolute value of it)
  2802. even if a deadline has a different individual lead time specified.
  2803. Custom commands can set this variable in the options section."
  2804. :group 'org-time
  2805. :group 'org-agenda-daily/weekly
  2806. :type 'integer)
  2807. (defcustom org-scheduled-delay-days 0
  2808. "Number of days before a scheduled item becomes active.
  2809. This variable governs the display in sparse trees and in the agenda.
  2810. The default value (i.e. 0) means: don't delay scheduled item.
  2811. When negative, it means use this number (the absolute value of it)
  2812. even if a scheduled item has a different individual delay time
  2813. specified.
  2814. Custom commands can set this variable in the options section."
  2815. :group 'org-time
  2816. :group 'org-agenda-daily/weekly
  2817. :version "24.4"
  2818. :package-version '(Org . "8.0")
  2819. :type 'integer)
  2820. (defcustom org-read-date-prefer-future t
  2821. "Non-nil means assume future for incomplete date input from user.
  2822. This affects the following situations:
  2823. 1. The user gives a month but not a year.
  2824. For example, if it is April and you enter \"feb 2\", this will be read
  2825. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2826. 2. The user gives a day, but no month.
  2827. For example, if today is the 15th, and you enter \"3\", Org will read
  2828. this as the third of *next* month. However, if you enter \"17\",
  2829. it will be considered as *this* month.
  2830. If you set this variable to the symbol `time', then also the following
  2831. will work:
  2832. 3. If the user gives a time.
  2833. If the time is before now, it will be interpreted as tomorrow.
  2834. Currently none of this works for ISO week specifications.
  2835. When this option is nil, the current day, month and year will always be
  2836. used as defaults.
  2837. See also `org-agenda-jump-prefer-future'."
  2838. :group 'org-time
  2839. :type '(choice
  2840. (const :tag "Never" nil)
  2841. (const :tag "Check month and day" t)
  2842. (const :tag "Check month, day, and time" time)))
  2843. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2844. "Should the agenda jump command prefer the future for incomplete dates?
  2845. The default is to do the same as configured in `org-read-date-prefer-future'.
  2846. But you can also set a deviating value here.
  2847. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2848. :group 'org-agenda
  2849. :group 'org-time
  2850. :version "24.1"
  2851. :type '(choice
  2852. (const :tag "Use org-read-date-prefer-future"
  2853. org-read-date-prefer-future)
  2854. (const :tag "Never" nil)
  2855. (const :tag "Always" t)))
  2856. (defcustom org-read-date-force-compatible-dates t
  2857. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2858. Depending on the system Emacs is running on, certain dates cannot
  2859. be represented with the type used internally to represent time.
  2860. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2861. correctly. Some systems allow for earlier dates, some for later,
  2862. some for both. One way to find out it to insert any date into an
  2863. Org buffer, putting the cursor on the year and hitting S-up and
  2864. S-down to test the range.
  2865. When this variable is set to t, the date/time prompt will not let
  2866. you specify dates outside the 1970-2037 range, so it is certain that
  2867. these dates will work in whatever version of Emacs you are
  2868. running, and also that you can move a file from one Emacs implementation
  2869. to another. WHenever Org is forcing the year for you, it will display
  2870. a message and beep.
  2871. When this variable is nil, Org will check if the date is
  2872. representable in the specific Emacs implementation you are using.
  2873. If not, it will force a year, usually the current year, and beep
  2874. to remind you. Currently this setting is not recommended because
  2875. the likelihood that you will open your Org files in an Emacs that
  2876. has limited date range is not negligible.
  2877. A workaround for this problem is to use diary sexp dates for time
  2878. stamps outside of this range."
  2879. :group 'org-time
  2880. :version "24.1"
  2881. :type 'boolean)
  2882. (defcustom org-read-date-display-live t
  2883. "Non-nil means display current interpretation of date prompt live.
  2884. This display will be in an overlay, in the minibuffer."
  2885. :group 'org-time
  2886. :type 'boolean)
  2887. (defcustom org-read-date-popup-calendar t
  2888. "Non-nil means pop up a calendar when prompting for a date.
  2889. In the calendar, the date can be selected with mouse-1. However, the
  2890. minibuffer will also be active, and you can simply enter the date as well.
  2891. When nil, only the minibuffer will be available."
  2892. :group 'org-time
  2893. :type 'boolean)
  2894. (defvaralias 'org-popup-calendar-for-date-prompt
  2895. 'org-read-date-popup-calendar)
  2896. (defcustom org-extend-today-until 0
  2897. "The hour when your day really ends. Must be an integer.
  2898. This has influence for the following applications:
  2899. - When switching the agenda to \"today\". It it is still earlier than
  2900. the time given here, the day recognized as TODAY is actually yesterday.
  2901. - When a date is read from the user and it is still before the time given
  2902. here, the current date and time will be assumed to be yesterday, 23:59.
  2903. Also, timestamps inserted in capture templates follow this rule.
  2904. IMPORTANT: This is a feature whose implementation is and likely will
  2905. remain incomplete. Really, it is only here because past midnight seems to
  2906. be the favorite working time of John Wiegley :-)"
  2907. :group 'org-time
  2908. :type 'integer)
  2909. (defcustom org-use-effective-time nil
  2910. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2911. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2912. \"effective time\" of any timestamps between midnight and 8am will be
  2913. 23:59 of the previous day."
  2914. :group 'org-time
  2915. :version "24.1"
  2916. :type 'boolean)
  2917. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2918. "When non-nil, use the last clock out time for `org-todo'.
  2919. Note that this option has precedence over the combined use of
  2920. `org-use-effective-time' and `org-extend-today-until'."
  2921. :group 'org-time
  2922. :version "24.4"
  2923. :package-version '(Org . "8.0")
  2924. :type 'boolean)
  2925. (defcustom org-edit-timestamp-down-means-later nil
  2926. "Non-nil means S-down will increase the time in a time stamp.
  2927. When nil, S-up will increase."
  2928. :group 'org-time
  2929. :type 'boolean)
  2930. (defcustom org-calendar-follow-timestamp-change t
  2931. "Non-nil means make the calendar window follow timestamp changes.
  2932. When a timestamp is modified and the calendar window is visible, it will be
  2933. moved to the new date."
  2934. :group 'org-time
  2935. :type 'boolean)
  2936. (defgroup org-tags nil
  2937. "Options concerning tags in Org mode."
  2938. :tag "Org Tags"
  2939. :group 'org)
  2940. (defcustom org-tag-alist nil
  2941. "Default tags available in Org files.
  2942. The value of this variable is an alist. Associations either:
  2943. (TAG)
  2944. (TAG . SELECT)
  2945. (SPECIAL)
  2946. where TAG is a tag as a string, SELECT is character, used to
  2947. select that tag through the fast tag selection interface, and
  2948. SPECIAL is one of the following keywords: `:startgroup',
  2949. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2950. `:newline'. These keywords are used to define a hierarchy of
  2951. tags. See manual for details.
  2952. When this variable is nil, Org mode bases tag input on what is
  2953. already in the buffer. The value can be overridden locally by
  2954. using a TAGS keyword, e.g.,
  2955. #+TAGS: tag1 tag2
  2956. See also `org-tag-persistent-alist' to sidestep this behavior."
  2957. :group 'org-tags
  2958. :type '(repeat
  2959. (choice
  2960. (cons :tag "Tag with key"
  2961. (string :tag "Tag name")
  2962. (character :tag "Access char"))
  2963. (list :tag "Tag" (string :tag "Tag name"))
  2964. (const :tag "Start radio group" (:startgroup))
  2965. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2966. (const :tag "Group tags delimiter" (:grouptags))
  2967. (const :tag "End radio group" (:endgroup))
  2968. (const :tag "End tag group, non distinct" (:endgrouptag))
  2969. (const :tag "New line" (:newline)))))
  2970. (defcustom org-tag-persistent-alist nil
  2971. "Tags always available in Org files.
  2972. The value of this variable is an alist. Associations either:
  2973. (TAG)
  2974. (TAG . SELECT)
  2975. (SPECIAL)
  2976. where TAG is a tag as a string, SELECT is a character, used to
  2977. select that tag through the fast tag selection interface, and
  2978. SPECIAL is one of the following keywords: `:startgroup',
  2979. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2980. `:newline'. These keywords are used to define a hierarchy of
  2981. tags. See manual for details.
  2982. Unlike to `org-tag-alist', tags defined in this variable do not
  2983. depend on a local TAGS keyword. Instead, to disable these tags
  2984. on a per-file basis, insert anywhere in the file:
  2985. #+STARTUP: noptag"
  2986. :group 'org-tags
  2987. :type '(repeat
  2988. (choice
  2989. (cons :tag "Tag with key"
  2990. (string :tag "Tag name")
  2991. (character :tag "Access char"))
  2992. (list :tag "Tag" (string :tag "Tag name"))
  2993. (const :tag "Start radio group" (:startgroup))
  2994. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2995. (const :tag "Group tags delimiter" (:grouptags))
  2996. (const :tag "End radio group" (:endgroup))
  2997. (const :tag "End tag group, non distinct" (:endgrouptag))
  2998. (const :tag "New line" (:newline)))))
  2999. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3000. "If non-nil, always offer completion for all tags of all agenda files.
  3001. Setting this variable locally allows for dynamic generation of tag
  3002. completions in capture buffers.
  3003. (add-hook \\='org-capture-mode-hook
  3004. (lambda ()
  3005. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3006. :group 'org-tags
  3007. :version "24.1"
  3008. :type 'boolean)
  3009. (defvar org-file-tags nil
  3010. "List of tags that can be inherited by all entries in the file.
  3011. The tags will be inherited if the variable `org-use-tag-inheritance'
  3012. says they should be.
  3013. This variable is populated from #+FILETAGS lines.")
  3014. (defcustom org-use-fast-tag-selection 'auto
  3015. "Non-nil means use fast tag selection scheme.
  3016. This is a special interface to select and deselect tags with single keys.
  3017. When nil, fast selection is never used.
  3018. When the symbol `auto', fast selection is used if and only if selection
  3019. characters for tags have been configured, either through the variable
  3020. `org-tag-alist' or through a #+TAGS line in the buffer.
  3021. When t, fast selection is always used and selection keys are assigned
  3022. automatically if necessary."
  3023. :group 'org-tags
  3024. :type '(choice
  3025. (const :tag "Always" t)
  3026. (const :tag "Never" nil)
  3027. (const :tag "When selection characters are configured" auto)))
  3028. (defcustom org-fast-tag-selection-single-key nil
  3029. "Non-nil means fast tag selection exits after first change.
  3030. When nil, you have to press RET to exit it.
  3031. During fast tag selection, you can toggle this flag with `C-c'.
  3032. This variable can also have the value `expert'. In this case, the window
  3033. displaying the tags menu is not even shown, until you press C-c again."
  3034. :group 'org-tags
  3035. :type '(choice
  3036. (const :tag "No" nil)
  3037. (const :tag "Yes" t)
  3038. (const :tag "Expert" expert)))
  3039. (defvar org-fast-tag-selection-include-todo nil
  3040. "Non-nil means fast tags selection interface will also offer TODO states.
  3041. This is an undocumented feature, you should not rely on it.")
  3042. (defcustom org-tags-column -77
  3043. "The column to which tags should be indented in a headline.
  3044. If this number is positive, it specifies the column. If it is negative,
  3045. it means that the tags should be flushright to that column. For example,
  3046. -80 works well for a normal 80 character screen.
  3047. When 0, place tags directly after headline text, with only one space in
  3048. between."
  3049. :group 'org-tags
  3050. :type 'integer)
  3051. (defcustom org-auto-align-tags t
  3052. "Non-nil keeps tags aligned when modifying headlines.
  3053. Some operations (i.e. demoting) change the length of a headline and
  3054. therefore shift the tags around. With this option turned on, after
  3055. each such operation the tags are again aligned to `org-tags-column'."
  3056. :group 'org-tags
  3057. :type 'boolean)
  3058. (defcustom org-use-tag-inheritance t
  3059. "Non-nil means tags in levels apply also for sublevels.
  3060. When nil, only the tags directly given in a specific line apply there.
  3061. This may also be a list of tags that should be inherited, or a regexp that
  3062. matches tags that should be inherited. Additional control is possible
  3063. with the variable `org-tags-exclude-from-inheritance' which gives an
  3064. explicit list of tags to be excluded from inheritance, even if the value of
  3065. `org-use-tag-inheritance' would select it for inheritance.
  3066. If this option is t, a match early-on in a tree can lead to a large
  3067. number of matches in the subtree when constructing the agenda or creating
  3068. a sparse tree. If you only want to see the first match in a tree during
  3069. a search, check out the variable `org-tags-match-list-sublevels'."
  3070. :group 'org-tags
  3071. :type '(choice
  3072. (const :tag "Not" nil)
  3073. (const :tag "Always" t)
  3074. (repeat :tag "Specific tags" (string :tag "Tag"))
  3075. (regexp :tag "Tags matched by regexp")))
  3076. (defcustom org-tags-exclude-from-inheritance nil
  3077. "List of tags that should never be inherited.
  3078. This is a way to exclude a few tags from inheritance. For way to do
  3079. the opposite, to actively allow inheritance for selected tags,
  3080. see the variable `org-use-tag-inheritance'."
  3081. :group 'org-tags
  3082. :type '(repeat (string :tag "Tag")))
  3083. (defun org-tag-inherit-p (tag)
  3084. "Check if TAG is one that should be inherited."
  3085. (cond
  3086. ((member tag org-tags-exclude-from-inheritance) nil)
  3087. ((eq org-use-tag-inheritance t) t)
  3088. ((not org-use-tag-inheritance) nil)
  3089. ((stringp org-use-tag-inheritance)
  3090. (string-match org-use-tag-inheritance tag))
  3091. ((listp org-use-tag-inheritance)
  3092. (member tag org-use-tag-inheritance))
  3093. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3094. (defcustom org-tags-match-list-sublevels t
  3095. "Non-nil means list also sublevels of headlines matching a search.
  3096. This variable applies to tags/property searches, and also to stuck
  3097. projects because this search is based on a tags match as well.
  3098. When set to the symbol `indented', sublevels are indented with
  3099. leading dots.
  3100. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3101. the sublevels of a headline matching a tag search often also match
  3102. the same search. Listing all of them can create very long lists.
  3103. Setting this variable to nil causes subtrees of a match to be skipped.
  3104. This variable is semi-obsolete and probably should always be true. It
  3105. is better to limit inheritance to certain tags using the variables
  3106. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3107. :group 'org-tags
  3108. :type '(choice
  3109. (const :tag "No, don't list them" nil)
  3110. (const :tag "Yes, do list them" t)
  3111. (const :tag "List them, indented with leading dots" indented)))
  3112. (defcustom org-tags-sort-function nil
  3113. "When set, tags are sorted using this function as a comparator."
  3114. :group 'org-tags
  3115. :type '(choice
  3116. (const :tag "No sorting" nil)
  3117. (const :tag "Alphabetical" org-string-collate-lessp)
  3118. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3119. (function :tag "Custom function" nil)))
  3120. (defvar org-tags-history nil
  3121. "History of minibuffer reads for tags.")
  3122. (defvar org-last-tags-completion-table nil
  3123. "The last used completion table for tags.")
  3124. (defvar org-after-tags-change-hook nil
  3125. "Hook that is run after the tags in a line have changed.")
  3126. (defgroup org-properties nil
  3127. "Options concerning properties in Org mode."
  3128. :tag "Org Properties"
  3129. :group 'org)
  3130. (defcustom org-property-format "%-10s %s"
  3131. "How property key/value pairs should be formatted by `indent-line'.
  3132. When `indent-line' hits a property definition, it will format the line
  3133. according to this format, mainly to make sure that the values are
  3134. lined-up with respect to each other."
  3135. :group 'org-properties
  3136. :type 'string)
  3137. (defcustom org-properties-postprocess-alist nil
  3138. "Alist of properties and functions to adjust inserted values.
  3139. Elements of this alist must be of the form
  3140. ([string] [function])
  3141. where [string] must be a property name and [function] must be a
  3142. lambda expression: this lambda expression must take one argument,
  3143. the value to adjust, and return the new value as a string.
  3144. For example, this element will allow the property \"Remaining\"
  3145. to be updated wrt the relation between the \"Effort\" property
  3146. and the clock summary:
  3147. ((\"Remaining\" (lambda(value)
  3148. (let ((clocksum (org-clock-sum-current-item))
  3149. (effort (org-duration-to-minutes
  3150. (org-entry-get (point) \"Effort\"))))
  3151. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3152. :group 'org-properties
  3153. :version "24.1"
  3154. :type '(alist :key-type (string :tag "Property")
  3155. :value-type (function :tag "Function")))
  3156. (defcustom org-use-property-inheritance nil
  3157. "Non-nil means properties apply also for sublevels.
  3158. This setting is chiefly used during property searches. Turning it on can
  3159. cause significant overhead when doing a search, which is why it is not
  3160. on by default.
  3161. When nil, only the properties directly given in the current entry count.
  3162. When t, every property is inherited. The value may also be a list of
  3163. properties that should have inheritance, or a regular expression matching
  3164. properties that should be inherited.
  3165. However, note that some special properties use inheritance under special
  3166. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3167. and the properties ending in \"_ALL\" when they are used as descriptor
  3168. for valid values of a property.
  3169. Note for programmers:
  3170. When querying an entry with `org-entry-get', you can control if inheritance
  3171. should be used. By default, `org-entry-get' looks only at the local
  3172. properties. You can request inheritance by setting the inherit argument
  3173. to t (to force inheritance) or to `selective' (to respect the setting
  3174. in this variable)."
  3175. :group 'org-properties
  3176. :type '(choice
  3177. (const :tag "Not" nil)
  3178. (const :tag "Always" t)
  3179. (repeat :tag "Specific properties" (string :tag "Property"))
  3180. (regexp :tag "Properties matched by regexp")))
  3181. (defun org-property-inherit-p (property)
  3182. "Return a non-nil value if PROPERTY should be inherited."
  3183. (cond
  3184. ((eq org-use-property-inheritance t) t)
  3185. ((not org-use-property-inheritance) nil)
  3186. ((stringp org-use-property-inheritance)
  3187. (string-match org-use-property-inheritance property))
  3188. ((listp org-use-property-inheritance)
  3189. (member-ignore-case property org-use-property-inheritance))
  3190. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3191. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3192. "The default column format, if no other format has been defined.
  3193. This variable can be set on the per-file basis by inserting a line
  3194. #+COLUMNS: %25ITEM ....."
  3195. :group 'org-properties
  3196. :type 'string)
  3197. (defcustom org-columns-ellipses ".."
  3198. "The ellipses to be used when a field in column view is truncated.
  3199. When this is the empty string, as many characters as possible are shown,
  3200. but then there will be no visual indication that the field has been truncated.
  3201. When this is a string of length N, the last N characters of a truncated
  3202. field are replaced by this string. If the column is narrower than the
  3203. ellipses string, only part of the ellipses string will be shown."
  3204. :group 'org-properties
  3205. :type 'string)
  3206. (defconst org-global-properties-fixed
  3207. '(("VISIBILITY_ALL" . "folded children content all")
  3208. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3209. "List of property/value pairs that can be inherited by any entry.
  3210. These are fixed values, for the preset properties. The user variable
  3211. that can be used to add to this list is `org-global-properties'.
  3212. The entries in this list are cons cells where the car is a property
  3213. name and cdr is a string with the value. If the value represents
  3214. multiple items like an \"_ALL\" property, separate the items by
  3215. spaces.")
  3216. (defcustom org-global-properties nil
  3217. "List of property/value pairs that can be inherited by any entry.
  3218. This list will be combined with the constant `org-global-properties-fixed'.
  3219. The entries in this list are cons cells where the car is a property
  3220. name and cdr is a string with the value.
  3221. You can set buffer-local values for the same purpose in the variable
  3222. `org-file-properties' this by adding lines like
  3223. #+PROPERTY: NAME VALUE"
  3224. :group 'org-properties
  3225. :type '(repeat
  3226. (cons (string :tag "Property")
  3227. (string :tag "Value"))))
  3228. (defvar-local org-file-properties nil
  3229. "List of property/value pairs that can be inherited by any entry.
  3230. Valid for the current buffer.
  3231. This variable is populated from #+PROPERTY lines.")
  3232. (defgroup org-agenda nil
  3233. "Options concerning agenda views in Org mode."
  3234. :tag "Org Agenda"
  3235. :group 'org)
  3236. (defvar-local org-category nil
  3237. "Variable used by Org files to set a category for agenda display.
  3238. Such files should use a file variable to set it, for example
  3239. # -*- mode: org; org-category: \"ELisp\"
  3240. or contain a special line
  3241. #+CATEGORY: ELisp
  3242. If the file does not specify a category, then file's base name
  3243. is used instead.")
  3244. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3245. (defcustom org-agenda-files nil
  3246. "The files to be used for agenda display.
  3247. If an entry is a directory, all files in that directory that are matched
  3248. by `org-agenda-file-regexp' will be part of the file list.
  3249. If the value of the variable is not a list but a single file name, then
  3250. the list of agenda files is actually stored and maintained in that file,
  3251. one agenda file per line. In this file paths can be given relative to
  3252. `org-directory'. Tilde expansion and environment variable substitution
  3253. are also made.
  3254. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3255. and removed with `\\[org-remove-file]'."
  3256. :group 'org-agenda
  3257. :type '(choice
  3258. (repeat :tag "List of files and directories" file)
  3259. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3260. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3261. "Regular expression to match files for `org-agenda-files'.
  3262. If any element in the list in that variable contains a directory instead
  3263. of a normal file, all files in that directory that are matched by this
  3264. regular expression will be included."
  3265. :group 'org-agenda
  3266. :type 'regexp)
  3267. (defcustom org-agenda-text-search-extra-files nil
  3268. "List of extra files to be searched by text search commands.
  3269. These files will be searched in addition to the agenda files by the
  3270. commands `org-search-view' (`\\[org-agenda] s') \
  3271. and `org-occur-in-agenda-files'.
  3272. Note that these files will only be searched for text search commands,
  3273. not for the other agenda views like todo lists, tag searches or the weekly
  3274. agenda. This variable is intended to list notes and possibly archive files
  3275. that should also be searched by these two commands.
  3276. In fact, if the first element in the list is the symbol `agenda-archives',
  3277. then all archive files of all agenda files will be added to the search
  3278. scope."
  3279. :group 'org-agenda
  3280. :type '(set :greedy t
  3281. (const :tag "Agenda Archives" agenda-archives)
  3282. (repeat :inline t (file))))
  3283. (defvaralias 'org-agenda-multi-occur-extra-files
  3284. 'org-agenda-text-search-extra-files)
  3285. (defcustom org-agenda-skip-unavailable-files nil
  3286. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3287. A nil value means to remove them, after a query, from the list."
  3288. :group 'org-agenda
  3289. :type 'boolean)
  3290. (defcustom org-agenda-diary-file 'diary-file
  3291. "File to which to add new entries with the `i' key in agenda and calendar.
  3292. When this is the symbol `diary-file', the functionality in the Emacs
  3293. calendar will be used to add entries to the `diary-file'. But when this
  3294. points to a file, `org-agenda-diary-entry' will be used instead."
  3295. :group 'org-agenda
  3296. :type '(choice
  3297. (const :tag "The standard Emacs diary file" diary-file)
  3298. (file :tag "Special Org file diary entries")))
  3299. (defgroup org-latex nil
  3300. "Options for embedding LaTeX code into Org mode."
  3301. :tag "Org LaTeX"
  3302. :group 'org)
  3303. (defcustom org-format-latex-options
  3304. '(:foreground default :background default :scale 1.0
  3305. :html-foreground "Black" :html-background "Transparent"
  3306. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3307. "Options for creating images from LaTeX fragments.
  3308. This is a property list with the following properties:
  3309. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3310. `default' means use the foreground of the default face.
  3311. `auto' means use the foreground from the text face.
  3312. :background the background color, or \"Transparent\".
  3313. `default' means use the background of the default face.
  3314. `auto' means use the background from the text face.
  3315. :scale a scaling factor for the size of the images, to get more pixels
  3316. :html-foreground, :html-background, :html-scale
  3317. the same numbers for HTML export.
  3318. :matchers a list indicating which matchers should be used to
  3319. find LaTeX fragments. Valid members of this list are:
  3320. \"begin\" find environments
  3321. \"$1\" find single characters surrounded by $.$
  3322. \"$\" find math expressions surrounded by $...$
  3323. \"$$\" find math expressions surrounded by $$....$$
  3324. \"\\(\" find math expressions surrounded by \\(...\\)
  3325. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3326. :group 'org-latex
  3327. :type 'plist)
  3328. (defcustom org-format-latex-signal-error t
  3329. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3330. When nil, just push out a message."
  3331. :group 'org-latex
  3332. :version "24.1"
  3333. :type 'boolean)
  3334. (defcustom org-latex-to-mathml-jar-file nil
  3335. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3336. Use this to specify additional executable file say a jar file.
  3337. When using MathToWeb as the converter, specify the full-path to
  3338. your mathtoweb.jar file."
  3339. :group 'org-latex
  3340. :version "24.1"
  3341. :type '(choice
  3342. (const :tag "None" nil)
  3343. (file :tag "JAR file" :must-match t)))
  3344. (defcustom org-latex-to-mathml-convert-command nil
  3345. "Command to convert LaTeX fragments to MathML.
  3346. Replace format-specifiers in the command as noted below and use
  3347. `shell-command' to convert LaTeX to MathML.
  3348. %j: Executable file in fully expanded form as specified by
  3349. `org-latex-to-mathml-jar-file'.
  3350. %I: Input LaTeX file in fully expanded form.
  3351. %i: The latex fragment to be converted.
  3352. %o: Output MathML file.
  3353. This command is used by `org-create-math-formula'.
  3354. When using MathToWeb as the converter, set this option to
  3355. \"java -jar %j -unicode -force -df %o %I\".
  3356. When using LaTeXML set this option to
  3357. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3358. :group 'org-latex
  3359. :version "24.1"
  3360. :type '(choice
  3361. (const :tag "None" nil)
  3362. (string :tag "\nShell command")))
  3363. (defcustom org-preview-latex-default-process 'dvipng
  3364. "The default process to convert LaTeX fragments to image files.
  3365. All available processes and theirs documents can be found in
  3366. `org-preview-latex-process-alist', which see."
  3367. :group 'org-latex
  3368. :version "26.1"
  3369. :package-version '(Org . "9.0")
  3370. :type 'symbol)
  3371. (defcustom org-preview-latex-process-alist
  3372. '((dvipng
  3373. :programs ("latex" "dvipng")
  3374. :description "dvi > png"
  3375. :message "you need to install the programs: latex and dvipng."
  3376. :image-input-type "dvi"
  3377. :image-output-type "png"
  3378. :image-size-adjust (1.0 . 1.0)
  3379. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3380. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3381. (dvisvgm
  3382. :programs ("latex" "dvisvgm")
  3383. :description "dvi > svg"
  3384. :message "you need to install the programs: latex and dvisvgm."
  3385. :use-xcolor t
  3386. :image-input-type "dvi"
  3387. :image-output-type "svg"
  3388. :image-size-adjust (1.7 . 1.5)
  3389. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3390. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3391. (imagemagick
  3392. :programs ("latex" "convert")
  3393. :description "pdf > png"
  3394. :message "you need to install the programs: latex and imagemagick."
  3395. :use-xcolor t
  3396. :image-input-type "pdf"
  3397. :image-output-type "png"
  3398. :image-size-adjust (1.0 . 1.0)
  3399. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3400. :image-converter
  3401. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3402. "Definitions of external processes for LaTeX previewing.
  3403. Org mode can use some external commands to generate TeX snippet's images for
  3404. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3405. `org-create-formula-image' how to call them.
  3406. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3407. PROPERTIES accepts the following attributes:
  3408. :programs list of strings, required programs.
  3409. :description string, describe the process.
  3410. :message string, message it when required programs cannot be found.
  3411. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3412. :image-output-type string, output file type of image converter (e.g., \"png\").
  3413. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3414. deal with background and foreground color of image.
  3415. Otherwise, dvipng style background and foreground color
  3416. format are generated. You may then refer to them in
  3417. command options with \"%F\" and \"%B\".
  3418. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3419. image size showed in buffer and the cdr element is for
  3420. HTML file. This option is only useful for process
  3421. developers, users should use variable
  3422. `org-format-latex-options' instead.
  3423. :post-clean list of strings, files matched are to be cleaned up once
  3424. the image is generated. When nil, the files with \".dvi\",
  3425. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3426. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3427. be cleaned up.
  3428. :latex-header list of strings, the LaTeX header of the snippet file.
  3429. When nil, the fallback value is used instead, which is
  3430. controlled by `org-format-latex-header',
  3431. `org-latex-default-packages-alist' and
  3432. `org-latex-packages-alist', which see.
  3433. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3434. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3435. replaced with values defined below.
  3436. :image-converter list of image converter commands strings. Each of them is
  3437. given to the shell and supports any of the following
  3438. place-holders defined below.
  3439. Place-holders used by `:image-converter' and `:latex-compiler':
  3440. %f input file name
  3441. %b base name of input file
  3442. %o base directory of input file
  3443. %O absolute output file name
  3444. Place-holders only used by `:image-converter':
  3445. %F foreground of image
  3446. %B background of image
  3447. %D dpi, which is used to adjust image size by some processing commands.
  3448. %S the image size scale ratio, which is used to adjust image size by some
  3449. processing commands."
  3450. :group 'org-latex
  3451. :version "26.1"
  3452. :package-version '(Org . "9.0")
  3453. :type '(alist :tag "LaTeX to image backends"
  3454. :value-type (plist)))
  3455. (defcustom org-preview-latex-image-directory "ltximg/"
  3456. "Path to store latex preview images.
  3457. A relative path here creates many directories relative to the
  3458. processed Org files paths. An absolute path puts all preview
  3459. images at the same place."
  3460. :group 'org-latex
  3461. :version "26.1"
  3462. :package-version '(Org . "9.0")
  3463. :type 'string)
  3464. (defun org-format-latex-mathml-available-p ()
  3465. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3466. (save-match-data
  3467. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3468. org-latex-to-mathml-convert-command)
  3469. (let ((executable (car (split-string
  3470. org-latex-to-mathml-convert-command))))
  3471. (when (executable-find executable)
  3472. (if (string-match
  3473. "%j" org-latex-to-mathml-convert-command)
  3474. (file-readable-p org-latex-to-mathml-jar-file)
  3475. t))))))
  3476. (defcustom org-format-latex-header "\\documentclass{article}
  3477. \\usepackage[usenames]{color}
  3478. \[PACKAGES]
  3479. \[DEFAULT-PACKAGES]
  3480. \\pagestyle{empty} % do not remove
  3481. % The settings below are copied from fullpage.sty
  3482. \\setlength{\\textwidth}{\\paperwidth}
  3483. \\addtolength{\\textwidth}{-3cm}
  3484. \\setlength{\\oddsidemargin}{1.5cm}
  3485. \\addtolength{\\oddsidemargin}{-2.54cm}
  3486. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3487. \\setlength{\\textheight}{\\paperheight}
  3488. \\addtolength{\\textheight}{-\\headheight}
  3489. \\addtolength{\\textheight}{-\\headsep}
  3490. \\addtolength{\\textheight}{-\\footskip}
  3491. \\addtolength{\\textheight}{-3cm}
  3492. \\setlength{\\topmargin}{1.5cm}
  3493. \\addtolength{\\topmargin}{-2.54cm}"
  3494. "The document header used for processing LaTeX fragments.
  3495. It is imperative that this header make sure that no page number
  3496. appears on the page. The package defined in the variables
  3497. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3498. will either replace the placeholder \"[PACKAGES]\" in this
  3499. header, or they will be appended."
  3500. :group 'org-latex
  3501. :type 'string)
  3502. (defun org-set-packages-alist (var val)
  3503. "Set the packages alist and make sure it has 3 elements per entry."
  3504. (set var (mapcar (lambda (x)
  3505. (if (and (consp x) (= (length x) 2))
  3506. (list (car x) (nth 1 x) t)
  3507. x))
  3508. val)))
  3509. (defun org-get-packages-alist (var)
  3510. "Get the packages alist and make sure it has 3 elements per entry."
  3511. (mapcar (lambda (x)
  3512. (if (and (consp x) (= (length x) 2))
  3513. (list (car x) (nth 1 x) t)
  3514. x))
  3515. (default-value var)))
  3516. (defcustom org-latex-default-packages-alist
  3517. '(("AUTO" "inputenc" t ("pdflatex"))
  3518. ("T1" "fontenc" t ("pdflatex"))
  3519. ("" "graphicx" t)
  3520. ("" "grffile" t)
  3521. ("" "longtable" nil)
  3522. ("" "wrapfig" nil)
  3523. ("" "rotating" nil)
  3524. ("normalem" "ulem" t)
  3525. ("" "amsmath" t)
  3526. ("" "textcomp" t)
  3527. ("" "amssymb" t)
  3528. ("" "capt-of" nil)
  3529. ("" "hyperref" nil))
  3530. "Alist of default packages to be inserted in the header.
  3531. Change this only if one of the packages here causes an
  3532. incompatibility with another package you are using.
  3533. The packages in this list are needed by one part or another of
  3534. Org mode to function properly:
  3535. - inputenc, fontenc: for basic font and character selection
  3536. - graphicx: for including images
  3537. - grffile: allow periods and spaces in graphics file names
  3538. - longtable: For multipage tables
  3539. - wrapfig: for figure placement
  3540. - rotating: for sideways figures and tables
  3541. - ulem: for underline and strike-through
  3542. - amsmath: for subscript and superscript and math environments
  3543. - textcomp, amssymb: for various symbols used
  3544. for interpreting the entities in `org-entities'. You can skip
  3545. some of these packages if you don't use any of their symbols.
  3546. - capt-of: for captions outside of floats
  3547. - hyperref: for cross references
  3548. Therefore you should not modify this variable unless you know
  3549. what you are doing. The one reason to change it anyway is that
  3550. you might be loading some other package that conflicts with one
  3551. of the default packages. Each element is either a cell or
  3552. a string.
  3553. A cell is of the format
  3554. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3555. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3556. when compiling LaTeX snippets into images for inclusion into
  3557. non-LaTeX output. COMPILERS is a list of compilers that should
  3558. include the package, see `org-latex-compiler'. If the document
  3559. compiler is not in the list, and the list is non-nil, the package
  3560. will not be inserted in the final document.
  3561. A string will be inserted as-is in the header of the document."
  3562. :group 'org-latex
  3563. :group 'org-export-latex
  3564. :set 'org-set-packages-alist
  3565. :get 'org-get-packages-alist
  3566. :version "26.1"
  3567. :package-version '(Org . "8.3")
  3568. :type '(repeat
  3569. (choice
  3570. (list :tag "options/package pair"
  3571. (string :tag "options")
  3572. (string :tag "package")
  3573. (boolean :tag "Snippet")
  3574. (choice
  3575. (const :tag "For all compilers" nil)
  3576. (repeat :tag "Allowed compiler" string)))
  3577. (string :tag "A line of LaTeX"))))
  3578. (defcustom org-latex-packages-alist nil
  3579. "Alist of packages to be inserted in every LaTeX header.
  3580. These will be inserted after `org-latex-default-packages-alist'.
  3581. Each element is either a cell or a string.
  3582. A cell is of the format:
  3583. (\"options\" \"package\" SNIPPET-FLAG)
  3584. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3585. needed when turning LaTeX snippets into images for inclusion into
  3586. non-LaTeX output.
  3587. A string will be inserted as-is in the header of the document.
  3588. Make sure that you only list packages here which:
  3589. - you want in every file;
  3590. - do not conflict with the setup in `org-format-latex-header';
  3591. - do not conflict with the default packages in
  3592. `org-latex-default-packages-alist'."
  3593. :group 'org-latex
  3594. :group 'org-export-latex
  3595. :set 'org-set-packages-alist
  3596. :get 'org-get-packages-alist
  3597. :type '(repeat
  3598. (choice
  3599. (list :tag "options/package pair"
  3600. (string :tag "options")
  3601. (string :tag "package")
  3602. (boolean :tag "Snippet"))
  3603. (string :tag "A line of LaTeX"))))
  3604. (defgroup org-appearance nil
  3605. "Settings for Org mode appearance."
  3606. :tag "Org Appearance"
  3607. :group 'org)
  3608. (defcustom org-level-color-stars-only nil
  3609. "Non-nil means fontify only the stars in each headline.
  3610. When nil, the entire headline is fontified.
  3611. Changing it requires restart of `font-lock-mode' to become effective
  3612. also in regions already fontified."
  3613. :group 'org-appearance
  3614. :type 'boolean)
  3615. (defcustom org-hide-leading-stars nil
  3616. "Non-nil means hide the first N-1 stars in a headline.
  3617. This works by using the face `org-hide' for these stars. This
  3618. face is white for a light background, and black for a dark
  3619. background. You may have to customize the face `org-hide' to
  3620. make this work.
  3621. Changing it requires restart of `font-lock-mode' to become effective
  3622. also in regions already fontified.
  3623. You may also set this on a per-file basis by adding one of the following
  3624. lines to the buffer:
  3625. #+STARTUP: hidestars
  3626. #+STARTUP: showstars"
  3627. :group 'org-appearance
  3628. :type 'boolean)
  3629. (defcustom org-hidden-keywords nil
  3630. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3631. For example, a value \\='(title) for this list makes the document's title
  3632. appear in the buffer without the initial \"#+TITLE:\" part."
  3633. :group 'org-appearance
  3634. :version "24.1"
  3635. :type '(set (const :tag "#+AUTHOR" author)
  3636. (const :tag "#+DATE" date)
  3637. (const :tag "#+EMAIL" email)
  3638. (const :tag "#+TITLE" title)))
  3639. (defcustom org-custom-properties nil
  3640. "List of properties (as strings) with a special meaning.
  3641. The default use of these custom properties is to let the user
  3642. hide them with `org-toggle-custom-properties-visibility'."
  3643. :group 'org-properties
  3644. :group 'org-appearance
  3645. :version "24.3"
  3646. :type '(repeat (string :tag "Property Name")))
  3647. (defcustom org-fontify-done-headline nil
  3648. "Non-nil means change the face of a headline if it is marked DONE.
  3649. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3650. When this is non-nil, the headline after the keyword is set to the
  3651. `org-headline-done' as an additional indication."
  3652. :group 'org-appearance
  3653. :type 'boolean)
  3654. (defcustom org-fontify-emphasized-text t
  3655. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3656. Changing this variable requires a restart of Emacs to take effect."
  3657. :group 'org-appearance
  3658. :type 'boolean)
  3659. (defcustom org-fontify-whole-heading-line nil
  3660. "Non-nil means fontify the whole line for headings.
  3661. This is useful when setting a background color for the
  3662. org-level-* faces."
  3663. :group 'org-appearance
  3664. :type 'boolean)
  3665. (defcustom org-highlight-latex-and-related nil
  3666. "Non-nil means highlight LaTeX related syntax in the buffer.
  3667. When non nil, the value should be a list containing any of the
  3668. following symbols:
  3669. `latex' Highlight LaTeX snippets and environments.
  3670. `script' Highlight subscript and superscript.
  3671. `entities' Highlight entities."
  3672. :group 'org-appearance
  3673. :version "24.4"
  3674. :package-version '(Org . "8.0")
  3675. :type '(choice
  3676. (const :tag "No highlighting" nil)
  3677. (set :greedy t :tag "Highlight"
  3678. (const :tag "LaTeX snippets and environments" latex)
  3679. (const :tag "Subscript and superscript" script)
  3680. (const :tag "Entities" entities))))
  3681. (defcustom org-hide-emphasis-markers nil
  3682. "Non-nil mean font-lock should hide the emphasis marker characters."
  3683. :group 'org-appearance
  3684. :type 'boolean
  3685. :safe #'booleanp)
  3686. (defcustom org-hide-macro-markers nil
  3687. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3688. :group 'org-appearance
  3689. :type 'boolean)
  3690. (defcustom org-pretty-entities nil
  3691. "Non-nil means show entities as UTF8 characters.
  3692. When nil, the \\name form remains in the buffer."
  3693. :group 'org-appearance
  3694. :version "24.1"
  3695. :type 'boolean)
  3696. (defcustom org-pretty-entities-include-sub-superscripts t
  3697. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3698. :group 'org-appearance
  3699. :version "24.1"
  3700. :type 'boolean)
  3701. (defvar org-emph-re nil
  3702. "Regular expression for matching emphasis.
  3703. After a match, the match groups contain these elements:
  3704. 0 The match of the full regular expression, including the characters
  3705. before and after the proper match
  3706. 1 The character before the proper match, or empty at beginning of line
  3707. 2 The proper match, including the leading and trailing markers
  3708. 3 The leading marker like * or /, indicating the type of highlighting
  3709. 4 The text between the emphasis markers, not including the markers
  3710. 5 The character after the match, empty at the end of a line")
  3711. (defvar org-verbatim-re nil
  3712. "Regular expression for matching verbatim text.")
  3713. (defvar org-emphasis-regexp-components) ; defined just below
  3714. (defvar org-emphasis-alist) ; defined just below
  3715. (defun org-set-emph-re (var val)
  3716. "Set variable and compute the emphasis regular expression."
  3717. (set var val)
  3718. (when (and (boundp 'org-emphasis-alist)
  3719. (boundp 'org-emphasis-regexp-components)
  3720. org-emphasis-alist org-emphasis-regexp-components)
  3721. (pcase-let*
  3722. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3723. (body (if (<= nl 0) body
  3724. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3725. (template
  3726. (format (concat "\\([%s]\\|^\\)" ;before markers
  3727. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3728. "\\([%s]\\|$\\)") ;after markers
  3729. pre border border body border post)))
  3730. (setq org-emph-re (format template "*/_+"))
  3731. (setq org-verbatim-re (format template "=~")))))
  3732. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3733. ;; set this option proved cumbersome. See this message/thread:
  3734. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3735. (defvar org-emphasis-regexp-components
  3736. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3737. "Components used to build the regular expression for emphasis.
  3738. This is a list with five entries. Terminology: In an emphasis string
  3739. like \" *strong word* \", we call the initial space PREMATCH, the final
  3740. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3741. and \"trong wor\" is the body. The different components in this variable
  3742. specify what is allowed/forbidden in each part:
  3743. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3744. post Chars allowed as postmatch. End of line will be allowed too.
  3745. border The chars *forbidden* as border characters.
  3746. body-regexp A regexp like \".\" to match a body character. Don't use
  3747. non-shy groups here, and don't allow newline here.
  3748. newline The maximum number of newlines allowed in an emphasis exp.
  3749. You need to reload Org or to restart Emacs after setting this.")
  3750. (defcustom org-emphasis-alist
  3751. '(("*" bold)
  3752. ("/" italic)
  3753. ("_" underline)
  3754. ("=" org-verbatim verbatim)
  3755. ("~" org-code verbatim)
  3756. ("+" (:strike-through t)))
  3757. "Alist of characters and faces to emphasize text.
  3758. Text starting and ending with a special character will be emphasized,
  3759. for example *bold*, _underlined_ and /italic/. This variable sets the
  3760. marker characters and the face to be used by font-lock for highlighting
  3761. in Org buffers.
  3762. You need to reload Org or to restart Emacs after customizing this."
  3763. :group 'org-appearance
  3764. :set 'org-set-emph-re
  3765. :version "24.4"
  3766. :package-version '(Org . "8.0")
  3767. :type '(repeat
  3768. (list
  3769. (string :tag "Marker character")
  3770. (choice
  3771. (face :tag "Font-lock-face")
  3772. (plist :tag "Face property list"))
  3773. (option (const verbatim)))))
  3774. (defvar org-protecting-blocks '("src" "example" "export")
  3775. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3776. This is needed for font-lock setup.")
  3777. ;;; Functions and variables from their packages
  3778. ;; Declared here to avoid compiler warnings
  3779. (defvar mark-active)
  3780. ;; Various packages
  3781. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3782. (declare-function calendar-forward-day "cal-move" (arg))
  3783. (declare-function calendar-goto-date "cal-move" (date))
  3784. (declare-function calendar-goto-today "cal-move" ())
  3785. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3786. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3787. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3788. (declare-function cdlatex-tab "ext:cdlatex" ())
  3789. (declare-function dired-get-filename
  3790. "dired"
  3791. (&optional localp no-error-if-not-filep))
  3792. (declare-function iswitchb-read-buffer
  3793. "iswitchb"
  3794. (prompt &optional
  3795. default require-match _predicate start matches-set))
  3796. (declare-function org-agenda-change-all-lines
  3797. "org-agenda"
  3798. (newhead hdmarker &optional fixface just-this))
  3799. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3800. "org-agenda"
  3801. (&optional end))
  3802. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3803. (declare-function org-agenda-format-item
  3804. "org-agenda"
  3805. (extra txt &optional level category tags dotime
  3806. remove-re habitp))
  3807. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3808. (declare-function org-agenda-save-markers-for-cut-and-paste
  3809. "org-agenda"
  3810. (beg end))
  3811. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3812. (declare-function org-agenda-skip "org-agenda" ())
  3813. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3814. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3815. (declare-function org-indent-mode "org-indent" (&optional arg))
  3816. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3817. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3818. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3819. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3820. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3821. (declare-function parse-time-string "parse-time" (string))
  3822. (defvar align-mode-rules-list)
  3823. (defvar calc-embedded-close-formula)
  3824. (defvar calc-embedded-open-formula)
  3825. (defvar calc-embedded-open-mode)
  3826. (defvar font-lock-unfontify-region-function)
  3827. (defvar iswitchb-temp-buflist)
  3828. (defvar org-agenda-tags-todo-honor-ignore-options)
  3829. (defvar remember-data-file)
  3830. (defvar texmathp-why)
  3831. ;;;###autoload
  3832. (defun turn-on-orgtbl ()
  3833. "Unconditionally turn on `orgtbl-mode'."
  3834. (require 'org-table)
  3835. (orgtbl-mode 1))
  3836. (defun org-at-table-p (&optional table-type)
  3837. "Non-nil if the cursor is inside an Org table.
  3838. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3839. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3840. (or (not (derived-mode-p 'org-mode))
  3841. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3842. (and e (or table-type
  3843. (eq 'org (org-element-property :type e))))))))
  3844. (defun org-at-table.el-p ()
  3845. "Non-nil when point is at a table.el table."
  3846. (and (org-match-line "[ \t]*[|+]")
  3847. (let ((element (org-element-at-point)))
  3848. (and (eq (org-element-type element) 'table)
  3849. (eq (org-element-property :type element) 'table.el)))))
  3850. (defun org-at-table-hline-p ()
  3851. "Non-nil when point is inside a hline in a table.
  3852. Assume point is already in a table."
  3853. (org-match-line org-table-hline-regexp))
  3854. (defun org-table-map-tables (function &optional quietly)
  3855. "Apply FUNCTION to the start of all tables in the buffer."
  3856. (org-with-wide-buffer
  3857. (goto-char (point-min))
  3858. (while (re-search-forward org-table-any-line-regexp nil t)
  3859. (unless quietly
  3860. (message "Mapping tables: %d%%"
  3861. (floor (* 100.0 (point)) (buffer-size))))
  3862. (beginning-of-line 1)
  3863. (when (and (looking-at org-table-line-regexp)
  3864. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3865. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3866. (save-excursion (funcall function))
  3867. (or (looking-at org-table-line-regexp)
  3868. (forward-char 1)))
  3869. (re-search-forward org-table-any-border-regexp nil 1)))
  3870. (unless quietly (message "Mapping tables: done")))
  3871. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3872. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3873. (declare-function org-resolve-clocks "org-clock"
  3874. (&optional also-non-dangling-p prompt last-valid))
  3875. (defun org-at-TBLFM-p (&optional pos)
  3876. "Non-nil when point (or POS) is in #+TBLFM line."
  3877. (save-excursion
  3878. (goto-char (or pos (point)))
  3879. (beginning-of-line)
  3880. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3881. (eq (org-element-type (org-element-at-point)) 'table))))
  3882. (defvar org-clock-start-time)
  3883. (defvar org-clock-marker (make-marker)
  3884. "Marker recording the last clock-in.")
  3885. (defvar org-clock-hd-marker (make-marker)
  3886. "Marker recording the last clock-in, but the headline position.")
  3887. (defvar org-clock-heading ""
  3888. "The heading of the current clock entry.")
  3889. (defun org-clock-is-active ()
  3890. "Return the buffer where the clock is currently running.
  3891. Return nil if no clock is running."
  3892. (marker-buffer org-clock-marker))
  3893. (defun org-check-running-clock ()
  3894. "Check if the current buffer contains the running clock.
  3895. If yes, offer to stop it and to save the buffer with the changes."
  3896. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3897. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3898. (buffer-name))))
  3899. (org-clock-out)
  3900. (when (y-or-n-p "Save changed buffer?")
  3901. (save-buffer))))
  3902. (defun org-clocktable-try-shift (dir n)
  3903. "Check if this line starts a clock table, if yes, shift the time block."
  3904. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3905. (org-clocktable-shift dir n)))
  3906. ;;;###autoload
  3907. (defun org-clock-persistence-insinuate ()
  3908. "Set up hooks for clock persistence."
  3909. (require 'org-clock)
  3910. (add-hook 'org-mode-hook 'org-clock-load)
  3911. (add-hook 'kill-emacs-hook 'org-clock-save))
  3912. (defgroup org-archive nil
  3913. "Options concerning archiving in Org mode."
  3914. :tag "Org Archive"
  3915. :group 'org-structure)
  3916. (defcustom org-archive-location "%s_archive::"
  3917. "The location where subtrees should be archived.
  3918. The value of this variable is a string, consisting of two parts,
  3919. separated by a double-colon. The first part is a filename and
  3920. the second part is a headline.
  3921. When the filename is omitted, archiving happens in the same file.
  3922. %s in the filename will be replaced by the current file
  3923. name (without the directory part). Archiving to a different file
  3924. is useful to keep archived entries from contributing to the
  3925. Org Agenda.
  3926. The archived entries will be filed as subtrees of the specified
  3927. headline. When the headline is omitted, the subtrees are simply
  3928. filed away at the end of the file, as top-level entries. Also in
  3929. the heading you can use %s to represent the file name, this can be
  3930. useful when using the same archive for a number of different files.
  3931. Here are a few examples:
  3932. \"%s_archive::\"
  3933. If the current file is Projects.org, archive in file
  3934. Projects.org_archive, as top-level trees. This is the default.
  3935. \"::* Archived Tasks\"
  3936. Archive in the current file, under the top-level headline
  3937. \"* Archived Tasks\".
  3938. \"~/org/archive.org::\"
  3939. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3940. \"~/org/archive.org::* From %s\"
  3941. Archive in file ~/org/archive.org (absolute path), under headlines
  3942. \"From FILENAME\" where file name is the current file name.
  3943. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3944. The \"datetree/\" string is special, signifying to archive
  3945. items to the datetree. Items are placed in either the CLOSED
  3946. date of the item, or the current date if there is no CLOSED date.
  3947. The heading will be a subentry to the current date. There doesn't
  3948. need to be a heading, but there always needs to be a slash after
  3949. datetree. For example, to store archived items directly in the
  3950. datetree, use \"~/org/datetree.org::datetree/\".
  3951. \"basement::** Finished Tasks\"
  3952. Archive in file ./basement (relative path), as level 3 trees
  3953. below the level 2 heading \"** Finished Tasks\".
  3954. You may set this option on a per-file basis by adding to the buffer a
  3955. line like
  3956. #+ARCHIVE: basement::** Finished Tasks
  3957. You may also define it locally for a subtree by setting an ARCHIVE property
  3958. in the entry. If such a property is found in an entry, or anywhere up
  3959. the hierarchy, it will be used."
  3960. :group 'org-archive
  3961. :type 'string)
  3962. (defcustom org-agenda-skip-archived-trees t
  3963. "Non-nil means the agenda will skip any items located in archived trees.
  3964. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3965. variable is no longer recommended, you should leave it at the value t.
  3966. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3967. :group 'org-archive
  3968. :group 'org-agenda-skip
  3969. :type 'boolean)
  3970. (defcustom org-columns-skip-archived-trees t
  3971. "Non-nil means ignore archived trees when creating column view."
  3972. :group 'org-archive
  3973. :group 'org-properties
  3974. :type 'boolean)
  3975. (defcustom org-cycle-open-archived-trees nil
  3976. "Non-nil means `org-cycle' will open archived trees.
  3977. An archived tree is a tree marked with the tag ARCHIVE.
  3978. When nil, archived trees will stay folded. You can still open them with
  3979. normal outline commands like `show-all', but not with the cycling commands."
  3980. :group 'org-archive
  3981. :group 'org-cycle
  3982. :type 'boolean)
  3983. (defcustom org-sparse-tree-open-archived-trees nil
  3984. "Non-nil means sparse tree construction shows matches in archived trees.
  3985. When nil, matches in these trees are highlighted, but the trees are kept in
  3986. collapsed state."
  3987. :group 'org-archive
  3988. :group 'org-sparse-trees
  3989. :type 'boolean)
  3990. (defcustom org-sparse-tree-default-date-type nil
  3991. "The default date type when building a sparse tree.
  3992. When this is nil, a date is a scheduled or a deadline timestamp.
  3993. Otherwise, these types are allowed:
  3994. all: all timestamps
  3995. active: only active timestamps (<...>)
  3996. inactive: only inactive timestamps ([...])
  3997. scheduled: only scheduled timestamps
  3998. deadline: only deadline timestamps"
  3999. :type '(choice (const :tag "Scheduled or deadline" nil)
  4000. (const :tag "All timestamps" all)
  4001. (const :tag "Only active timestamps" active)
  4002. (const :tag "Only inactive timestamps" inactive)
  4003. (const :tag "Only scheduled timestamps" scheduled)
  4004. (const :tag "Only deadline timestamps" deadline)
  4005. (const :tag "Only closed timestamps" closed))
  4006. :version "26.1"
  4007. :package-version '(Org . "8.3")
  4008. :group 'org-sparse-trees)
  4009. (defun org-cycle-hide-archived-subtrees (state)
  4010. "Re-hide all archived subtrees after a visibility state change.
  4011. STATE should be one of the symbols listed in the docstring of
  4012. `org-cycle-hook'."
  4013. (when (and (not org-cycle-open-archived-trees)
  4014. (not (memq state '(overview folded))))
  4015. (save-excursion
  4016. (let* ((globalp (memq state '(contents all)))
  4017. (beg (if globalp (point-min) (point)))
  4018. (end (if globalp (point-max) (org-end-of-subtree t))))
  4019. (org-hide-archived-subtrees beg end)
  4020. (goto-char beg)
  4021. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4022. (message "%s" (substitute-command-keys
  4023. "Subtree is archived and stays closed. Use \
  4024. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4025. (defun org-force-cycle-archived ()
  4026. "Cycle subtree even if it is archived."
  4027. (interactive)
  4028. (setq this-command 'org-cycle)
  4029. (let ((org-cycle-open-archived-trees t))
  4030. (call-interactively 'org-cycle)))
  4031. (defun org-hide-archived-subtrees (beg end)
  4032. "Re-hide all archived subtrees after a visibility state change."
  4033. (org-with-wide-buffer
  4034. (let ((case-fold-search nil)
  4035. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4036. (goto-char beg)
  4037. ;; Include headline point is currently on.
  4038. (beginning-of-line)
  4039. (while (and (< (point) end) (re-search-forward re end t))
  4040. (when (member org-archive-tag (org-get-tags nil t))
  4041. (org-flag-subtree t)
  4042. (org-end-of-subtree t))))))
  4043. (defun org-flag-subtree (flag)
  4044. (save-excursion
  4045. (org-back-to-heading t)
  4046. (org-flag-region (line-end-position)
  4047. (progn (org-end-of-subtree t) (point))
  4048. flag
  4049. 'outline)))
  4050. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4051. ;; Declare Column View Code
  4052. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4053. (declare-function org-columns-compute "org-colview" (property))
  4054. ;; Declare ID code
  4055. (declare-function org-id-store-link "org-id")
  4056. (declare-function org-id-locations-load "org-id")
  4057. (declare-function org-id-locations-save "org-id")
  4058. (defvar org-id-track-globally)
  4059. ;;; Variables for pre-computed regular expressions, all buffer local
  4060. (defvar-local org-todo-regexp nil
  4061. "Matches any of the TODO state keywords.
  4062. Since TODO keywords are case-sensitive, `case-fold-search' is
  4063. expected to be bound to nil when matching against this regexp.")
  4064. (defvar-local org-not-done-regexp nil
  4065. "Matches any of the TODO state keywords except the last one.
  4066. Since TODO keywords are case-sensitive, `case-fold-search' is
  4067. expected to be bound to nil when matching against this regexp.")
  4068. (defvar-local org-not-done-heading-regexp nil
  4069. "Matches a TODO headline that is not done.
  4070. Since TODO keywords are case-sensitive, `case-fold-search' is
  4071. expected to be bound to nil when matching against this regexp.")
  4072. (defvar-local org-todo-line-regexp nil
  4073. "Matches a headline and puts TODO state into group 2 if present.
  4074. Since TODO keywords are case-sensitive, `case-fold-search' is
  4075. expected to be bound to nil when matching against this regexp.")
  4076. (defvar-local org-complex-heading-regexp nil
  4077. "Matches a headline and puts everything into groups:
  4078. group 1: Stars
  4079. group 2: The TODO keyword, maybe
  4080. group 3: Priority cookie
  4081. group 4: True headline
  4082. group 5: Tags
  4083. Since TODO keywords are case-sensitive, `case-fold-search' is
  4084. expected to be bound to nil when matching against this regexp.")
  4085. (defvar-local org-complex-heading-regexp-format nil
  4086. "Printf format to make regexp to match an exact headline.
  4087. This regexp will match the headline of any node which has the
  4088. exact headline text that is put into the format, but may have any
  4089. TODO state, priority and tags.")
  4090. (defvar-local org-todo-line-tags-regexp nil
  4091. "Matches a headline and puts TODO state into group 2 if present.
  4092. Also put tags into group 4 if tags are present.")
  4093. (defconst org-plain-time-of-day-regexp
  4094. (concat
  4095. "\\(\\<[012]?[0-9]"
  4096. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4097. "\\(--?"
  4098. "\\(\\<[012]?[0-9]"
  4099. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4100. "\\)?")
  4101. "Regular expression to match a plain time or time range.
  4102. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4103. groups carry important information:
  4104. 0 the full match
  4105. 1 the first time, range or not
  4106. 8 the second time, if it is a range.")
  4107. (defconst org-plain-time-extension-regexp
  4108. (concat
  4109. "\\(\\<[012]?[0-9]"
  4110. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4111. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4112. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4113. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4114. groups carry important information:
  4115. 0 the full match
  4116. 7 hours of duration
  4117. 9 minutes of duration")
  4118. (defconst org-stamp-time-of-day-regexp
  4119. (concat
  4120. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4121. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4122. "\\(--?"
  4123. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4124. "Regular expression to match a timestamp time or time range.
  4125. After a match, the following groups carry important information:
  4126. 0 the full match
  4127. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4128. 2 the first time, range or not
  4129. 4 the second time, if it is a range.")
  4130. (defconst org-startup-options
  4131. '(("fold" org-startup-folded t)
  4132. ("overview" org-startup-folded t)
  4133. ("nofold" org-startup-folded nil)
  4134. ("showall" org-startup-folded nil)
  4135. ("showeverything" org-startup-folded showeverything)
  4136. ("content" org-startup-folded content)
  4137. ("indent" org-startup-indented t)
  4138. ("noindent" org-startup-indented nil)
  4139. ("hidestars" org-hide-leading-stars t)
  4140. ("showstars" org-hide-leading-stars nil)
  4141. ("odd" org-odd-levels-only t)
  4142. ("oddeven" org-odd-levels-only nil)
  4143. ("align" org-startup-align-all-tables t)
  4144. ("noalign" org-startup-align-all-tables nil)
  4145. ("shrink" org-startup-shrink-all-tables t)
  4146. ("inlineimages" org-startup-with-inline-images t)
  4147. ("noinlineimages" org-startup-with-inline-images nil)
  4148. ("latexpreview" org-startup-with-latex-preview t)
  4149. ("nolatexpreview" org-startup-with-latex-preview nil)
  4150. ("customtime" org-display-custom-times t)
  4151. ("logdone" org-log-done time)
  4152. ("lognotedone" org-log-done note)
  4153. ("nologdone" org-log-done nil)
  4154. ("lognoteclock-out" org-log-note-clock-out t)
  4155. ("nolognoteclock-out" org-log-note-clock-out nil)
  4156. ("logrepeat" org-log-repeat state)
  4157. ("lognoterepeat" org-log-repeat note)
  4158. ("logdrawer" org-log-into-drawer t)
  4159. ("nologdrawer" org-log-into-drawer nil)
  4160. ("logstatesreversed" org-log-states-order-reversed t)
  4161. ("nologstatesreversed" org-log-states-order-reversed nil)
  4162. ("nologrepeat" org-log-repeat nil)
  4163. ("logreschedule" org-log-reschedule time)
  4164. ("lognotereschedule" org-log-reschedule note)
  4165. ("nologreschedule" org-log-reschedule nil)
  4166. ("logredeadline" org-log-redeadline time)
  4167. ("lognoteredeadline" org-log-redeadline note)
  4168. ("nologredeadline" org-log-redeadline nil)
  4169. ("logrefile" org-log-refile time)
  4170. ("lognoterefile" org-log-refile note)
  4171. ("nologrefile" org-log-refile nil)
  4172. ("fninline" org-footnote-define-inline t)
  4173. ("nofninline" org-footnote-define-inline nil)
  4174. ("fnlocal" org-footnote-section nil)
  4175. ("fnauto" org-footnote-auto-label t)
  4176. ("fnprompt" org-footnote-auto-label nil)
  4177. ("fnconfirm" org-footnote-auto-label confirm)
  4178. ("fnplain" org-footnote-auto-label plain)
  4179. ("fnadjust" org-footnote-auto-adjust t)
  4180. ("nofnadjust" org-footnote-auto-adjust nil)
  4181. ("constcgs" constants-unit-system cgs)
  4182. ("constSI" constants-unit-system SI)
  4183. ("noptag" org-tag-persistent-alist nil)
  4184. ("hideblocks" org-hide-block-startup t)
  4185. ("nohideblocks" org-hide-block-startup nil)
  4186. ("beamer" org-startup-with-beamer-mode t)
  4187. ("entitiespretty" org-pretty-entities t)
  4188. ("entitiesplain" org-pretty-entities nil))
  4189. "Variable associated with STARTUP options for Org.
  4190. Each element is a list of three items: the startup options (as written
  4191. in the #+STARTUP line), the corresponding variable, and the value to set
  4192. this variable to if the option is found. An optional forth element PUSH
  4193. means to push this value onto the list in the variable.")
  4194. (defcustom org-group-tags t
  4195. "When non-nil (the default), use group tags.
  4196. This can be turned on/off through `org-toggle-tags-groups'."
  4197. :group 'org-tags
  4198. :group 'org-startup
  4199. :type 'boolean)
  4200. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4201. (defun org-toggle-tags-groups ()
  4202. "Toggle support for group tags.
  4203. Support for group tags is controlled by the option
  4204. `org-group-tags', which is non-nil by default."
  4205. (interactive)
  4206. (setq org-group-tags (not org-group-tags))
  4207. (cond ((and (derived-mode-p 'org-agenda-mode)
  4208. org-group-tags)
  4209. (org-agenda-redo))
  4210. ((derived-mode-p 'org-mode)
  4211. (let ((org-inhibit-startup t)) (org-mode))))
  4212. (message "Groups tags support has been turned %s"
  4213. (if org-group-tags "on" "off")))
  4214. (defun org--tag-add-to-alist (alist1 alist2)
  4215. "Merge tags from ALIST1 into ALIST2.
  4216. Duplicates tags outside a group are removed. Keywords and order
  4217. are preserved.
  4218. The function assumes ALIST1 and ALIST2 are proper tag alists.
  4219. See `org-tag-alist' for their structure."
  4220. (cond
  4221. ((null alist2) alist1)
  4222. ((null alist1) alist2)
  4223. (t
  4224. (let ((to-add nil)
  4225. (group-flag nil))
  4226. (dolist (tag-pair alist1)
  4227. (pcase tag-pair
  4228. (`(,(or :startgrouptag :startgroup))
  4229. (setq group-flag t)
  4230. (push tag-pair to-add))
  4231. (`(,(or :endgrouptag :endgroup))
  4232. (setq group-flag nil)
  4233. (push tag-pair to-add))
  4234. (`(,(or :grouptags :newline))
  4235. (push tag-pair to-add))
  4236. (`(,tag . ,_)
  4237. ;; Remove duplicates from ALIST1, unless they are in
  4238. ;; a group. Indeed, it makes sense to have a tag appear in
  4239. ;; multiple groups.
  4240. (when (or group-flag (not (assoc tag alist2)))
  4241. (push tag-pair to-add)))
  4242. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  4243. ;; Preserve order of ALIST1.
  4244. (append (nreverse to-add) alist2)))))
  4245. (defun org-set-regexps-and-options (&optional tags-only)
  4246. "Precompute regular expressions used in the current buffer.
  4247. When optional argument TAGS-ONLY is non-nil, only compute tags
  4248. related expressions."
  4249. (when (derived-mode-p 'org-mode)
  4250. (let ((alist (org--setup-collect-keywords
  4251. (org-make-options-regexp
  4252. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4253. (and (not tags-only)
  4254. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4255. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4256. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4257. ;; Startup options. Get this early since it does change
  4258. ;; behavior for other options (e.g., tags).
  4259. (let ((startup (cdr (assq 'startup alist))))
  4260. (dolist (option startup)
  4261. (let ((entry (assoc-string option org-startup-options t)))
  4262. (when entry
  4263. (let ((var (nth 1 entry))
  4264. (val (nth 2 entry)))
  4265. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4266. (unless (listp (symbol-value var))
  4267. (set (make-local-variable var) nil))
  4268. (add-to-list var val)))))))
  4269. (setq-local org-file-tags
  4270. (mapcar #'org-add-prop-inherited
  4271. (cdr (assq 'filetags alist))))
  4272. (setq org-current-tag-alist
  4273. (org--tag-add-to-alist
  4274. org-tag-persistent-alist
  4275. (let ((tags (cdr (assq 'tags alist))))
  4276. (if tags (org-tag-string-to-alist tags)
  4277. org-tag-alist))))
  4278. (setq org-tag-groups-alist
  4279. (org-tag-alist-to-groups org-current-tag-alist))
  4280. (unless tags-only
  4281. ;; File properties.
  4282. (setq-local org-file-properties (cdr (assq 'property alist)))
  4283. ;; Archive location.
  4284. (let ((archive (cdr (assq 'archive alist))))
  4285. (when archive (setq-local org-archive-location archive)))
  4286. ;; Category.
  4287. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4288. (when cat
  4289. (setq-local org-category (intern cat))
  4290. (setq-local org-file-properties
  4291. (org--update-property-plist
  4292. "CATEGORY" cat org-file-properties))))
  4293. ;; Columns.
  4294. (let ((column (cdr (assq 'columns alist))))
  4295. (when column (setq-local org-columns-default-format column)))
  4296. ;; Constants.
  4297. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4298. ;; Link abbreviations.
  4299. (let ((links (cdr (assq 'link alist))))
  4300. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4301. ;; Priorities.
  4302. (let ((priorities (cdr (assq 'priorities alist))))
  4303. (when priorities
  4304. (setq-local org-highest-priority (nth 0 priorities))
  4305. (setq-local org-lowest-priority (nth 1 priorities))
  4306. (setq-local org-default-priority (nth 2 priorities))))
  4307. ;; Scripts.
  4308. (let ((scripts (assq 'scripts alist)))
  4309. (when scripts
  4310. (setq-local org-use-sub-superscripts (cdr scripts))))
  4311. ;; TODO keywords.
  4312. (setq-local org-todo-kwd-alist nil)
  4313. (setq-local org-todo-key-alist nil)
  4314. (setq-local org-todo-key-trigger nil)
  4315. (setq-local org-todo-keywords-1 nil)
  4316. (setq-local org-done-keywords nil)
  4317. (setq-local org-todo-heads nil)
  4318. (setq-local org-todo-sets nil)
  4319. (setq-local org-todo-log-states nil)
  4320. (let ((todo-sequences
  4321. (or (nreverse (cdr (assq 'todo alist)))
  4322. (let ((d (default-value 'org-todo-keywords)))
  4323. (if (not (stringp (car d))) d
  4324. ;; XXX: Backward compatibility code.
  4325. (list (cons org-todo-interpretation d)))))))
  4326. (dolist (sequence todo-sequences)
  4327. (let* ((sequence (or (run-hook-with-args-until-success
  4328. 'org-todo-setup-filter-hook sequence)
  4329. sequence))
  4330. (sequence-type (car sequence))
  4331. (keywords (cdr sequence))
  4332. (sep (member "|" keywords))
  4333. names alist)
  4334. (dolist (k (remove "|" keywords))
  4335. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4336. k)
  4337. (error "Invalid TODO keyword %s" k))
  4338. (let ((name (match-string 1 k))
  4339. (key (match-string 2 k))
  4340. (log (org-extract-log-state-settings k)))
  4341. (push name names)
  4342. (push (cons name (and key (string-to-char key))) alist)
  4343. (when log (push log org-todo-log-states))))
  4344. (let* ((names (nreverse names))
  4345. (done (if sep (org-remove-keyword-keys (cdr sep))
  4346. (last names)))
  4347. (head (car names))
  4348. (tail (list sequence-type head (car done) (org-last done))))
  4349. (add-to-list 'org-todo-heads head 'append)
  4350. (push names org-todo-sets)
  4351. (setq org-done-keywords (append org-done-keywords done nil))
  4352. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4353. (setq org-todo-key-alist
  4354. (append org-todo-key-alist
  4355. (and alist
  4356. (append '((:startgroup))
  4357. (nreverse alist)
  4358. '((:endgroup))))))
  4359. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4360. (setq org-todo-sets (nreverse org-todo-sets)
  4361. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4362. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4363. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4364. ;; Compute the regular expressions and other local variables.
  4365. ;; Using `org-outline-regexp-bol' would complicate them much,
  4366. ;; because of the fixed white space at the end of that string.
  4367. (unless org-done-keywords
  4368. (setq org-done-keywords
  4369. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4370. (setq org-not-done-keywords
  4371. (org-delete-all org-done-keywords
  4372. (copy-sequence org-todo-keywords-1))
  4373. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4374. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4375. org-not-done-heading-regexp
  4376. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4377. org-todo-line-regexp
  4378. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4379. org-complex-heading-regexp
  4380. (concat "^\\(\\*+\\)"
  4381. "\\(?: +" org-todo-regexp "\\)?"
  4382. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4383. "\\(?: +\\(.*?\\)\\)??"
  4384. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4385. "[ \t]*$")
  4386. org-complex-heading-regexp-format
  4387. (concat "^\\(\\*+\\)"
  4388. "\\(?: +" org-todo-regexp "\\)?"
  4389. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4390. "\\(?: +"
  4391. ;; Stats cookies can be stuck to body.
  4392. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4393. "\\(%s\\)"
  4394. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4395. "\\)"
  4396. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4397. "[ \t]*$")
  4398. org-todo-line-tags-regexp
  4399. (concat "^\\(\\*+\\)"
  4400. "\\(?: +" org-todo-regexp "\\)?"
  4401. "\\(?: +\\(.*?\\)\\)??"
  4402. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4403. "[ \t]*$"))
  4404. (org-compute-latex-and-related-regexp)))))
  4405. (defun org--setup-collect-keywords (regexp &optional files alist)
  4406. "Return setup keywords values as an alist.
  4407. REGEXP matches a subset of setup keywords. FILES is a list of
  4408. file names already visited. It is used to avoid circular setup
  4409. files. ALIST, when non-nil, is the alist computed so far.
  4410. Return value contains the following keys: `archive', `category',
  4411. `columns', `constants', `filetags', `link', `priorities',
  4412. `property', `scripts', `startup', `tags' and `todo'."
  4413. (org-with-wide-buffer
  4414. (goto-char (point-min))
  4415. (let ((case-fold-search t))
  4416. (while (re-search-forward regexp nil t)
  4417. (let ((element (org-element-at-point)))
  4418. (when (eq (org-element-type element) 'keyword)
  4419. (let ((key (org-element-property :key element))
  4420. (value (org-element-property :value element)))
  4421. (cond
  4422. ((equal key "ARCHIVE")
  4423. (when (org-string-nw-p value)
  4424. (push (cons 'archive value) alist)))
  4425. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4426. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4427. ((equal key "CONSTANTS")
  4428. (let* ((constants (assq 'constants alist))
  4429. (store (cdr constants)))
  4430. (dolist (pair (split-string value))
  4431. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4432. pair)
  4433. (let* ((name (match-string 1 pair))
  4434. (value (match-string 2 pair))
  4435. (old (assoc name store)))
  4436. (if old (setcdr old value)
  4437. (push (cons name value) store)))))
  4438. (if constants (setcdr constants store)
  4439. (push (cons 'constants store) alist))))
  4440. ((equal key "FILETAGS")
  4441. (when (org-string-nw-p value)
  4442. (let ((old (assq 'filetags alist))
  4443. (new (apply #'nconc
  4444. (mapcar (lambda (x) (org-split-string x ":"))
  4445. (split-string value)))))
  4446. (if old (setcdr old (append new (cdr old)))
  4447. (push (cons 'filetags new) alist)))))
  4448. ((equal key "LINK")
  4449. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4450. (let ((links (assq 'link alist))
  4451. (pair (cons (match-string-no-properties 1 value)
  4452. (match-string-no-properties 2 value))))
  4453. (if links (push pair (cdr links))
  4454. (push (list 'link pair) alist)))))
  4455. ((equal key "OPTIONS")
  4456. (when (and (org-string-nw-p value)
  4457. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4458. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4459. ((equal key "PRIORITIES")
  4460. (push (cons 'priorities
  4461. (let ((prio (split-string value)))
  4462. (if (< (length prio) 3) '(?A ?C ?B)
  4463. (mapcar #'string-to-char prio))))
  4464. alist))
  4465. ((equal key "PROPERTY")
  4466. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4467. (let* ((property (assq 'property alist))
  4468. (value (org--update-property-plist
  4469. (match-string-no-properties 1 value)
  4470. (match-string-no-properties 2 value)
  4471. (cdr property))))
  4472. (if property (setcdr property value)
  4473. (push (cons 'property value) alist)))))
  4474. ((equal key "STARTUP")
  4475. (let ((startup (assq 'startup alist)))
  4476. (if startup
  4477. (setcdr startup
  4478. (append (cdr startup) (split-string value)))
  4479. (push (cons 'startup (split-string value)) alist))))
  4480. ((equal key "TAGS")
  4481. (let ((tag-cell (assq 'tags alist)))
  4482. (if tag-cell
  4483. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4484. (push (cons 'tags value) alist))))
  4485. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4486. (let ((todo (assq 'todo alist))
  4487. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4488. (split-string value))))
  4489. (if todo (push value (cdr todo))
  4490. (push (list 'todo value) alist))))
  4491. ((equal key "SETUPFILE")
  4492. (unless buffer-read-only ; Do not check in Gnus messages.
  4493. (let ((f (and (org-string-nw-p value)
  4494. (expand-file-name (org-strip-quotes value)))))
  4495. (when (and f (file-readable-p f) (not (member f files)))
  4496. (with-temp-buffer
  4497. (setq default-directory (file-name-directory f))
  4498. (insert-file-contents f)
  4499. (setq alist
  4500. ;; Fake Org mode to benefit from cache
  4501. ;; without recurring needlessly.
  4502. (let ((major-mode 'org-mode))
  4503. (org--setup-collect-keywords
  4504. regexp (cons f files) alist)))))))))))))))
  4505. alist)
  4506. (defun org-tag-string-to-alist (s)
  4507. "Return tag alist associated to string S.
  4508. S is a value for TAGS keyword or produced with
  4509. `org-tag-alist-to-string'. Return value is an alist suitable for
  4510. `org-tag-alist' or `org-tag-persistent-alist'."
  4511. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4512. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4513. "\\(?:(\\(.\\))\\)?\\'"))
  4514. alist group-flag)
  4515. (dolist (tokens lines (cdr (nreverse alist)))
  4516. (push '(:newline) alist)
  4517. (while tokens
  4518. (let ((token (pop tokens)))
  4519. (pcase token
  4520. ("{"
  4521. (push '(:startgroup) alist)
  4522. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4523. ("}"
  4524. (push '(:endgroup) alist)
  4525. (setq group-flag nil))
  4526. ("["
  4527. (push '(:startgrouptag) alist)
  4528. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4529. ("]"
  4530. (push '(:endgrouptag) alist)
  4531. (setq group-flag nil))
  4532. (":"
  4533. (push '(:grouptags) alist))
  4534. ((guard (string-match tag-re token))
  4535. (let ((tag (match-string 1 token))
  4536. (key (and (match-beginning 2)
  4537. (string-to-char (match-string 2 token)))))
  4538. ;; Push all tags in groups, no matter if they already
  4539. ;; appear somewhere else in the list.
  4540. (when (or group-flag (not (assoc tag alist)))
  4541. (push (cons tag key) alist))))))))))
  4542. (defun org-tag-alist-to-string (alist &optional skip-key)
  4543. "Return tag string associated to ALIST.
  4544. ALIST is an alist, as defined in `org-tag-alist' or
  4545. `org-tag-persistent-alist', or produced with
  4546. `org-tag-string-to-alist'.
  4547. Return value is a string suitable as a value for \"TAGS\"
  4548. keyword.
  4549. When optional argument SKIP-KEY is non-nil, skip selection keys
  4550. next to tags."
  4551. (mapconcat (lambda (token)
  4552. (pcase token
  4553. (`(:startgroup) "{")
  4554. (`(:endgroup) "}")
  4555. (`(:startgrouptag) "[")
  4556. (`(:endgrouptag) "]")
  4557. (`(:grouptags) ":")
  4558. (`(:newline) "\\n")
  4559. ((and
  4560. (guard (not skip-key))
  4561. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4562. (format "%s(%c)" tag key))
  4563. (`(,(and tag (pred stringp)) . ,_) tag)
  4564. (_ (user-error "Invalid tag token: %S" token))))
  4565. alist
  4566. " "))
  4567. (defun org-tag-alist-to-groups (alist)
  4568. "Return group alist from tag ALIST.
  4569. ALIST is an alist, as defined in `org-tag-alist' or
  4570. `org-tag-persistent-alist', or produced with
  4571. `org-tag-string-to-alist'. Return value is an alist following
  4572. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4573. a string, summarizing TAGS, as a list of strings."
  4574. (let (groups group-status current-group)
  4575. (dolist (token alist (nreverse groups))
  4576. (pcase token
  4577. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4578. (`(,(or :endgroup :endgrouptag))
  4579. (when (eq group-status 'append)
  4580. (push (nreverse current-group) groups))
  4581. (setq group-status nil current-group nil))
  4582. (`(:grouptags) (setq group-status 'append))
  4583. ((and `(,tag . ,_) (guard group-status))
  4584. (if (eq group-status 'append) (push tag current-group)
  4585. (setq current-group (list tag))))
  4586. (_ nil)))))
  4587. (defvar org--file-cache (make-hash-table :test #'equal)
  4588. "Hash table to store contents of files referenced via a URL.
  4589. This is the cache of file URLs read using `org-file-contents'.")
  4590. (defun org-reset-file-cache ()
  4591. "Reset the cache of files downloaded by `org-file-contents'."
  4592. (clrhash org--file-cache))
  4593. (defun org-file-url-p (file)
  4594. "Non-nil if FILE is a URL."
  4595. (require 'ffap)
  4596. (string-match-p ffap-url-regexp file))
  4597. (defun org-file-contents (file &optional noerror nocache)
  4598. "Return the contents of FILE, as a string.
  4599. FILE can be a file name or URL.
  4600. If FILE is a URL, download the contents. If the URL contents are
  4601. already cached in the `org--file-cache' hash table, the download step
  4602. is skipped.
  4603. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4604. from file or URL.
  4605. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4606. is available. This option applies only if FILE is a URL."
  4607. (let* ((is-url (org-file-url-p file))
  4608. (cache (and is-url
  4609. (not nocache)
  4610. (gethash file org--file-cache))))
  4611. (cond
  4612. (cache)
  4613. (is-url
  4614. (with-current-buffer (url-retrieve-synchronously file)
  4615. (goto-char (point-min))
  4616. ;; Move point to after the url-retrieve header.
  4617. (search-forward "\n\n" nil :move)
  4618. ;; Search for the success code only in the url-retrieve header.
  4619. (if (save-excursion
  4620. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4621. ;; Update the cache `org--file-cache' and return contents.
  4622. (puthash file
  4623. (buffer-substring-no-properties (point) (point-max))
  4624. org--file-cache)
  4625. (funcall (if noerror #'message #'user-error)
  4626. "Unable to fetch file from %S"
  4627. file))))
  4628. (t
  4629. (with-temp-buffer
  4630. (condition-case nil
  4631. (progn
  4632. (insert-file-contents file)
  4633. (buffer-string))
  4634. (file-error
  4635. (funcall (if noerror #'message #'user-error)
  4636. "Unable to read file %S"
  4637. file))))))))
  4638. (defun org-extract-log-state-settings (x)
  4639. "Extract the log state setting from a TODO keyword string.
  4640. This will extract info from a string like \"WAIT(w@/!)\"."
  4641. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4642. (let ((kw (match-string 1 x))
  4643. (log1 (and (match-end 3) (match-string 3 x)))
  4644. (log2 (and (match-end 4) (match-string 4 x))))
  4645. (and (or log1 log2)
  4646. (list kw
  4647. (and log1 (if (equal log1 "!") 'time 'note))
  4648. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4649. (defun org-remove-keyword-keys (list)
  4650. "Remove a pair of parenthesis at the end of each string in LIST."
  4651. (mapcar (lambda (x)
  4652. (if (string-match "(.*)$" x)
  4653. (substring x 0 (match-beginning 0))
  4654. x))
  4655. list))
  4656. (defun org-assign-fast-keys (alist)
  4657. "Assign fast keys to a keyword-key alist.
  4658. Respect keys that are already there."
  4659. (let (new e (alt ?0))
  4660. (while (setq e (pop alist))
  4661. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4662. (cdr e)) ;; Key already assigned.
  4663. (push e new)
  4664. (let ((clist (string-to-list (downcase (car e))))
  4665. (used (append new alist)))
  4666. (when (= (car clist) ?@)
  4667. (pop clist))
  4668. (while (and clist (rassoc (car clist) used))
  4669. (pop clist))
  4670. (unless clist
  4671. (while (rassoc alt used)
  4672. (cl-incf alt)))
  4673. (push (cons (car e) (or (car clist) alt)) new))))
  4674. (nreverse new)))
  4675. ;;; Some variables used in various places
  4676. (defvar org-window-configuration nil
  4677. "Used in various places to store a window configuration.")
  4678. (defvar org-selected-window nil
  4679. "Used in various places to store a window configuration.")
  4680. (defvar org-finish-function nil
  4681. "Function to be called when `C-c C-c' is used.
  4682. This is for getting out of special buffers like capture.")
  4683. (defvar org-last-state)
  4684. ;; Defined somewhere in this file, but used before definition.
  4685. (defvar org-entities) ;; defined in org-entities.el
  4686. (defvar org-struct-menu)
  4687. (defvar org-org-menu)
  4688. (defvar org-tbl-menu)
  4689. ;;;; Define the Org mode
  4690. ;; We use a before-change function to check if a table might need
  4691. ;; an update.
  4692. (defvar org-table-may-need-update t
  4693. "Indicates that a table might need an update.
  4694. This variable is set by `org-before-change-function'.
  4695. `org-table-align' sets it back to nil.")
  4696. (defun org-before-change-function (_beg _end)
  4697. "Every change indicates that a table might need an update."
  4698. (setq org-table-may-need-update t))
  4699. (defvar org-mode-map)
  4700. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4701. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4702. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4703. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4704. (defvar org-table-buffer-is-an nil)
  4705. (defvar bidi-paragraph-direction)
  4706. (defvar buffer-face-mode-face)
  4707. (require 'outline)
  4708. ;; Other stuff we need.
  4709. (require 'time-date)
  4710. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4711. (require 'easymenu)
  4712. (autoload 'easy-menu-add "easymenu")
  4713. (require 'overlay)
  4714. ;; (require 'org-macs) moved higher up in the file before it is first used
  4715. (require 'org-entities)
  4716. ;; (require 'org-compat) moved higher up in the file before it is first used
  4717. (require 'org-faces)
  4718. (require 'org-list)
  4719. (require 'org-pcomplete)
  4720. (require 'org-src)
  4721. (require 'org-footnote)
  4722. (require 'org-macro)
  4723. ;; babel
  4724. (require 'ob)
  4725. ;;;###autoload
  4726. (define-derived-mode org-mode outline-mode "Org"
  4727. "Outline-based notes management and organizer, alias
  4728. \"Carsten's outline-mode for keeping track of everything.\"
  4729. Org mode develops organizational tasks around a NOTES file which
  4730. contains information about projects as plain text. Org mode is
  4731. implemented on top of Outline mode, which is ideal to keep the content
  4732. of large files well structured. It supports ToDo items, deadlines and
  4733. time stamps, which magically appear in the diary listing of the Emacs
  4734. calendar. Tables are easily created with a built-in table editor.
  4735. Plain text URL-like links connect to websites, emails (VM), Usenet
  4736. messages (Gnus), BBDB entries, and any files related to the project.
  4737. For printing and sharing of notes, an Org file (or a part of it)
  4738. can be exported as a structured ASCII or HTML file.
  4739. The following commands are available:
  4740. \\{org-mode-map}"
  4741. ;; Get rid of Outline menus, they are not needed
  4742. ;; Need to do this here because define-derived-mode sets up
  4743. ;; the keymap so late. Still, it is a waste to call this each time
  4744. ;; we switch another buffer into Org mode.
  4745. (define-key org-mode-map [menu-bar headings] 'undefined)
  4746. (define-key org-mode-map [menu-bar hide] 'undefined)
  4747. (define-key org-mode-map [menu-bar show] 'undefined)
  4748. (org-load-modules-maybe)
  4749. (org-install-agenda-files-menu)
  4750. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4751. (add-to-invisibility-spec '(org-hide-block . t))
  4752. (add-to-invisibility-spec '(org-hide-drawer . t))
  4753. (setq-local outline-regexp org-outline-regexp)
  4754. (setq-local outline-level 'org-outline-level)
  4755. (setq bidi-paragraph-direction 'left-to-right)
  4756. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4757. (unless org-display-table
  4758. (setq org-display-table (make-display-table)))
  4759. (set-display-table-slot
  4760. org-display-table 4
  4761. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4762. org-ellipsis)))
  4763. (setq buffer-display-table org-display-table))
  4764. (org-set-regexps-and-options)
  4765. (org-set-font-lock-defaults)
  4766. (when (and org-tag-faces (not org-tags-special-faces-re))
  4767. ;; tag faces set outside customize.... force initialization.
  4768. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4769. ;; Calc embedded
  4770. (setq-local calc-embedded-open-mode "# ")
  4771. ;; Modify a few syntax entries
  4772. (modify-syntax-entry ?\" "\"")
  4773. (modify-syntax-entry ?\\ "_")
  4774. (modify-syntax-entry ?~ "_")
  4775. (modify-syntax-entry ?< "(>")
  4776. (modify-syntax-entry ?> ")<")
  4777. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4778. ;; Activate before-change-function
  4779. (setq-local org-table-may-need-update t)
  4780. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4781. ;; Check for running clock before killing a buffer
  4782. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4783. ;; Initialize macros templates.
  4784. (org-macro-initialize-templates)
  4785. ;; Initialize radio targets.
  4786. (org-update-radio-target-regexp)
  4787. ;; Indentation.
  4788. (setq-local indent-line-function 'org-indent-line)
  4789. (setq-local indent-region-function 'org-indent-region)
  4790. ;; Filling and auto-filling.
  4791. (org-setup-filling)
  4792. ;; Comments.
  4793. (org-setup-comments-handling)
  4794. ;; Initialize cache.
  4795. (org-element-cache-reset)
  4796. ;; Beginning/end of defun
  4797. (setq-local beginning-of-defun-function 'org-backward-element)
  4798. (setq-local end-of-defun-function
  4799. (lambda ()
  4800. (if (not (org-at-heading-p))
  4801. (org-forward-element)
  4802. (org-forward-element)
  4803. (forward-char -1))))
  4804. ;; Next error for sparse trees
  4805. (setq-local next-error-function 'org-occur-next-match)
  4806. ;; Make commit log messages from Org documents easier.
  4807. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4808. ;; Make sure dependence stuff works reliably, even for users who set it
  4809. ;; too late :-(
  4810. (if org-enforce-todo-dependencies
  4811. (add-hook 'org-blocker-hook
  4812. 'org-block-todo-from-children-or-siblings-or-parent)
  4813. (remove-hook 'org-blocker-hook
  4814. 'org-block-todo-from-children-or-siblings-or-parent))
  4815. (if org-enforce-todo-checkbox-dependencies
  4816. (add-hook 'org-blocker-hook
  4817. 'org-block-todo-from-checkboxes)
  4818. (remove-hook 'org-blocker-hook
  4819. 'org-block-todo-from-checkboxes))
  4820. ;; Align options lines
  4821. (setq-local
  4822. align-mode-rules-list
  4823. '((org-in-buffer-settings
  4824. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4825. (modes . '(org-mode)))))
  4826. ;; Make isearch reveal context
  4827. (setq-local outline-isearch-open-invisible-function
  4828. (lambda (&rest _) (org-show-context 'isearch)))
  4829. ;; Setup the pcomplete hooks
  4830. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4831. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4832. (setq-local pcomplete-default-completion-function 'ignore)
  4833. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4834. (setq-local pcomplete-termination-string "")
  4835. (setq-local buffer-face-mode-face 'org-default)
  4836. ;; If empty file that did not turn on Org mode automatically, make
  4837. ;; it to.
  4838. (when (and org-insert-mode-line-in-empty-file
  4839. (called-interactively-p 'any)
  4840. (= (point-min) (point-max)))
  4841. (insert "# -*- mode: org -*-\n\n"))
  4842. (unless org-inhibit-startup
  4843. (org-unmodified
  4844. (when org-startup-with-beamer-mode (org-beamer-mode))
  4845. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4846. (org-table-map-tables
  4847. (cond ((and org-startup-align-all-tables
  4848. org-startup-shrink-all-tables)
  4849. (lambda () (org-table-align) (org-table-shrink)))
  4850. (org-startup-align-all-tables #'org-table-align)
  4851. (t #'org-table-shrink))
  4852. t))
  4853. (when org-startup-with-inline-images (org-display-inline-images))
  4854. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4855. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4856. (when org-startup-truncated (setq truncate-lines t))
  4857. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4858. (org-refresh-effort-properties)))
  4859. ;; Try to set `org-hide' face correctly.
  4860. (let ((foreground (org-find-invisible-foreground)))
  4861. (when foreground
  4862. (set-face-foreground 'org-hide foreground))))
  4863. ;; Update `customize-package-emacs-version-alist'
  4864. (add-to-list 'customize-package-emacs-version-alist
  4865. '(Org ("8.0" . "24.4")
  4866. ("8.1" . "24.4")
  4867. ("8.2" . "24.4")
  4868. ("8.2.7" . "24.4")
  4869. ("8.3" . "26.1")
  4870. ("9.0" . "26.1")
  4871. ("9.1" . "26.1")
  4872. ("9.2" . "27.1")))
  4873. (defvar org-mode-transpose-word-syntax-table
  4874. (let ((st (make-syntax-table text-mode-syntax-table)))
  4875. (dolist (c org-emphasis-alist st)
  4876. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4877. (when (fboundp 'abbrev-table-put)
  4878. (abbrev-table-put org-mode-abbrev-table
  4879. :parents (list text-mode-abbrev-table)))
  4880. (defun org-find-invisible-foreground ()
  4881. (let ((candidates (remove
  4882. "unspecified-bg"
  4883. (nconc
  4884. (list (face-background 'default)
  4885. (face-background 'org-default))
  4886. (mapcar
  4887. (lambda (alist)
  4888. (when (boundp alist)
  4889. (cdr (assq 'background-color (symbol-value alist)))))
  4890. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4891. (list (face-foreground 'org-hide))))))
  4892. (car (remove nil candidates))))
  4893. (defun org-current-time (&optional rounding-minutes past)
  4894. "Current time, possibly rounded to ROUNDING-MINUTES.
  4895. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4896. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4897. the rounding returns a past time."
  4898. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4899. (car org-time-stamp-rounding-minutes)))
  4900. (time (decode-time)) res)
  4901. (if (< r 1)
  4902. (current-time)
  4903. (setq res
  4904. (apply 'encode-time
  4905. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4906. (nthcdr 2 time))))
  4907. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4908. (seconds-to-time (- (float-time res) (* r 60)))
  4909. res))))
  4910. (defun org-today ()
  4911. "Return today date, considering `org-extend-today-until'."
  4912. (time-to-days
  4913. (time-subtract (current-time)
  4914. (list 0 (* 3600 org-extend-today-until) 0))))
  4915. ;;;; Font-Lock stuff, including the activators
  4916. (defvar org-mouse-map (make-sparse-keymap))
  4917. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4918. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4919. (when org-mouse-1-follows-link
  4920. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4921. (when org-tab-follows-link
  4922. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4923. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4924. (require 'font-lock)
  4925. (defconst org-non-link-chars "]\t\n\r<>")
  4926. (defvar org-link-types-re nil
  4927. "Matches a link that has a url-like prefix like \"http:\"")
  4928. (defvar org-link-re-with-space nil
  4929. "Matches a link with spaces, optional angular brackets around it.")
  4930. (defvar org-link-re-with-space2 nil
  4931. "Matches a link with spaces, optional angular brackets around it.")
  4932. (defvar org-link-re-with-space3 nil
  4933. "Matches a link with spaces, only for internal part in bracket links.")
  4934. (defvar org-angle-link-re nil
  4935. "Matches link with angular brackets, spaces are allowed.")
  4936. (defvar org-plain-link-re nil
  4937. "Matches plain link, without spaces.")
  4938. (defvar org-bracket-link-regexp nil
  4939. "Matches a link in double brackets.")
  4940. (defvar org-bracket-link-analytic-regexp nil
  4941. "Regular expression used to analyze links.
  4942. Here is what the match groups contain after a match:
  4943. 1: http:
  4944. 2: http
  4945. 3: path
  4946. 4: [desc]
  4947. 5: desc")
  4948. (defvar org-bracket-link-analytic-regexp++ nil
  4949. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4950. (defvar org-any-link-re nil
  4951. "Regular expression matching any link.")
  4952. (defconst org-match-sexp-depth 3
  4953. "Number of stacked braces for sub/superscript matching.")
  4954. (defun org-create-multibrace-regexp (left right n)
  4955. "Create a regular expression which will match a balanced sexp.
  4956. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4957. as single character strings.
  4958. The regexp returned will match the entire expression including the
  4959. delimiters. It will also define a single group which contains the
  4960. match except for the outermost delimiters. The maximum depth of
  4961. stacked delimiters is N. Escaping delimiters is not possible."
  4962. (let* ((nothing (concat "[^" left right "]*?"))
  4963. (or "\\|")
  4964. (re nothing)
  4965. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4966. (while (> n 1)
  4967. (setq n (1- n)
  4968. re (concat re or next)
  4969. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4970. (concat left "\\(" re "\\)" right)))
  4971. (defconst org-match-substring-regexp
  4972. (concat
  4973. "\\(\\S-\\)\\([_^]\\)\\("
  4974. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4975. "\\|"
  4976. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4977. "\\|"
  4978. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4979. "The regular expression matching a sub- or superscript.")
  4980. (defconst org-match-substring-with-braces-regexp
  4981. (concat
  4982. "\\(\\S-\\)\\([_^]\\)"
  4983. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4984. "The regular expression matching a sub- or superscript, forcing braces.")
  4985. (defun org-make-link-regexps ()
  4986. "Update the link regular expressions.
  4987. This should be called after the variable `org-link-parameters' has changed."
  4988. (let ((types-re (regexp-opt (org-link-types) t)))
  4989. (setq org-link-types-re
  4990. (concat "\\`" types-re ":")
  4991. org-link-re-with-space
  4992. (concat "<?" types-re ":"
  4993. "\\([^" org-non-link-chars " ]"
  4994. "[^" org-non-link-chars "]*"
  4995. "[^" org-non-link-chars " ]\\)>?")
  4996. org-link-re-with-space2
  4997. (concat "<?" types-re ":"
  4998. "\\([^" org-non-link-chars " ]"
  4999. "[^\t\n\r]*"
  5000. "[^" org-non-link-chars " ]\\)>?")
  5001. org-link-re-with-space3
  5002. (concat "<?" types-re ":"
  5003. "\\([^" org-non-link-chars " ]"
  5004. "[^\t\n\r]*\\)")
  5005. org-angle-link-re
  5006. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5007. types-re)
  5008. org-plain-link-re
  5009. (concat
  5010. "\\<" types-re ":"
  5011. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5012. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5013. org-bracket-link-regexp
  5014. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5015. org-bracket-link-analytic-regexp
  5016. (concat
  5017. "\\[\\["
  5018. "\\(" types-re ":\\)?"
  5019. "\\([^]]+\\)"
  5020. "\\]"
  5021. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5022. "\\]")
  5023. org-bracket-link-analytic-regexp++
  5024. (concat
  5025. "\\[\\["
  5026. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5027. "\\([^]]+\\)"
  5028. "\\]"
  5029. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5030. "\\]")
  5031. org-any-link-re
  5032. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5033. org-angle-link-re "\\)\\|\\("
  5034. org-plain-link-re "\\)"))))
  5035. (org-make-link-regexps)
  5036. (defvar org-emph-face nil)
  5037. (defun org-do-emphasis-faces (limit)
  5038. "Run through the buffer and emphasize strings."
  5039. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5040. (car org-emphasis-regexp-components))))
  5041. (catch :exit
  5042. (while (re-search-forward quick-re limit t)
  5043. (let* ((marker (match-string 2))
  5044. (verbatim? (member marker '("~" "="))))
  5045. (when (save-excursion
  5046. (goto-char (match-beginning 0))
  5047. (and
  5048. ;; Do not match table hlines.
  5049. (not (and (equal marker "+")
  5050. (org-match-line
  5051. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5052. ;; Do not match headline stars. Do not consider
  5053. ;; stars of a headline as closing marker for bold
  5054. ;; markup either.
  5055. (not (and (equal marker "*")
  5056. (save-excursion
  5057. (forward-char)
  5058. (skip-chars-backward "*")
  5059. (looking-at-p org-outline-regexp-bol))))
  5060. ;; Match full emphasis markup regexp.
  5061. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5062. ;; Do not span over paragraph boundaries.
  5063. (not (string-match-p org-element-paragraph-separate
  5064. (match-string 2)))
  5065. ;; Do not span over cells in table rows.
  5066. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5067. (string-match-p "|" (match-string 4))))))
  5068. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5069. (font-lock-prepend-text-property
  5070. (match-beginning 2) (match-end 2) 'face face)
  5071. (when verbatim?
  5072. (org-remove-flyspell-overlays-in
  5073. (match-beginning 0) (match-end 0))
  5074. (remove-text-properties (match-beginning 2) (match-end 2)
  5075. '(display t invisible t intangible t)))
  5076. (add-text-properties (match-beginning 2) (match-end 2)
  5077. '(font-lock-multiline t org-emphasis t))
  5078. (when org-hide-emphasis-markers
  5079. (add-text-properties (match-end 4) (match-beginning 5)
  5080. '(invisible org-link))
  5081. (add-text-properties (match-beginning 3) (match-end 3)
  5082. '(invisible org-link)))
  5083. (throw :exit t))))))))
  5084. (defun org-emphasize (&optional char)
  5085. "Insert or change an emphasis, i.e. a font like bold or italic.
  5086. If there is an active region, change that region to a new emphasis.
  5087. If there is no region, just insert the marker characters and position
  5088. the cursor between them.
  5089. CHAR should be the marker character. If it is a space, it means to
  5090. remove the emphasis of the selected region.
  5091. If CHAR is not given (for example in an interactive call) it will be
  5092. prompted for."
  5093. (interactive)
  5094. (let ((erc org-emphasis-regexp-components)
  5095. (string "") beg end move s)
  5096. (if (org-region-active-p)
  5097. (setq beg (region-beginning)
  5098. end (region-end)
  5099. string (buffer-substring beg end))
  5100. (setq move t))
  5101. (unless char
  5102. (message "Emphasis marker or tag: [%s]"
  5103. (mapconcat #'car org-emphasis-alist ""))
  5104. (setq char (read-char-exclusive)))
  5105. (if (equal char ?\s)
  5106. (setq s ""
  5107. move nil)
  5108. (unless (assoc (char-to-string char) org-emphasis-alist)
  5109. (user-error "No such emphasis marker: \"%c\"" char))
  5110. (setq s (char-to-string char)))
  5111. (while (and (> (length string) 1)
  5112. (equal (substring string 0 1) (substring string -1))
  5113. (assoc (substring string 0 1) org-emphasis-alist))
  5114. (setq string (substring string 1 -1)))
  5115. (setq string (concat s string s))
  5116. (when beg (delete-region beg end))
  5117. (unless (or (bolp)
  5118. (string-match (concat "[" (nth 0 erc) "\n]")
  5119. (char-to-string (char-before (point)))))
  5120. (insert " "))
  5121. (unless (or (eobp)
  5122. (string-match (concat "[" (nth 1 erc) "\n]")
  5123. (char-to-string (char-after (point)))))
  5124. (insert " ") (backward-char 1))
  5125. (insert string)
  5126. (and move (backward-char 1))))
  5127. (defconst org-nonsticky-props
  5128. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5129. (defsubst org-rear-nonsticky-at (pos)
  5130. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5131. (defun org-activate-links (limit)
  5132. "Add link properties to links.
  5133. This includes angle, plain, and bracket links."
  5134. (catch :exit
  5135. (while (re-search-forward org-any-link-re limit t)
  5136. (let* ((start (match-beginning 0))
  5137. (end (match-end 0))
  5138. (style (cond ((eq ?< (char-after start)) 'angle)
  5139. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5140. (t 'plain))))
  5141. (when (and (memq style org-highlight-links)
  5142. ;; Do not confuse plain links with tags.
  5143. (not (and (eq style 'plain)
  5144. (let ((face (get-text-property
  5145. (max (1- start) (point-min)) 'face)))
  5146. (if (consp face) (memq 'org-tag face)
  5147. (eq 'org-tag face))))))
  5148. (let* ((link-object (save-excursion
  5149. (goto-char start)
  5150. (save-match-data (org-element-link-parser))))
  5151. (link (org-element-property :raw-link link-object))
  5152. (type (org-element-property :type link-object))
  5153. (path (org-element-property :path link-object))
  5154. (properties ;for link's visible part
  5155. (list
  5156. 'face (pcase (org-link-get-parameter type :face)
  5157. ((and (pred functionp) face) (funcall face path))
  5158. ((and (pred facep) face) face)
  5159. ((and (pred consp) face) face) ;anonymous
  5160. (_ 'org-link))
  5161. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5162. 'highlight)
  5163. 'keymap (or (org-link-get-parameter type :keymap)
  5164. org-mouse-map)
  5165. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5166. ((and (pred stringp) echo) echo)
  5167. ((and (pred functionp) echo) echo)
  5168. (_ (concat "LINK: " link)))
  5169. 'htmlize-link (pcase (org-link-get-parameter type
  5170. :htmlize-link)
  5171. ((and (pred functionp) f) (funcall f))
  5172. (_ `(:uri ,link)))
  5173. 'font-lock-multiline t)))
  5174. (org-remove-flyspell-overlays-in start end)
  5175. (org-rear-nonsticky-at end)
  5176. (if (not (eq 'bracket style))
  5177. (add-text-properties start end properties)
  5178. ;; Handle invisible parts in bracket links.
  5179. (remove-text-properties start end '(invisible nil))
  5180. (let ((hidden
  5181. (append `(invisible
  5182. ,(or (org-link-get-parameter type :display)
  5183. 'org-link))
  5184. properties))
  5185. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5186. (visible-end (or (match-end 4) (match-end 2))))
  5187. (add-text-properties start visible-start hidden)
  5188. (add-text-properties visible-start visible-end properties)
  5189. (add-text-properties visible-end end hidden)
  5190. (org-rear-nonsticky-at visible-start)
  5191. (org-rear-nonsticky-at visible-end)))
  5192. (let ((f (org-link-get-parameter type :activate-func)))
  5193. (when (functionp f)
  5194. (funcall f start end path (eq style 'bracket))))
  5195. (throw :exit t))))) ;signal success
  5196. nil))
  5197. (defun org-activate-code (limit)
  5198. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5199. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5200. (remove-text-properties (match-beginning 0) (match-end 0)
  5201. '(display t invisible t intangible t))
  5202. t))
  5203. (defcustom org-src-fontify-natively t
  5204. "When non-nil, fontify code in code blocks.
  5205. See also the `org-block' face."
  5206. :type 'boolean
  5207. :version "26.1"
  5208. :package-version '(Org . "8.3")
  5209. :group 'org-appearance
  5210. :group 'org-babel)
  5211. (defcustom org-allow-promoting-top-level-subtree nil
  5212. "When non-nil, allow promoting a top level subtree.
  5213. The leading star of the top level headline will be replaced
  5214. by a #."
  5215. :type 'boolean
  5216. :version "24.1"
  5217. :group 'org-appearance)
  5218. (defun org-fontify-meta-lines-and-blocks (limit)
  5219. (condition-case nil
  5220. (org-fontify-meta-lines-and-blocks-1 limit)
  5221. (error (message "Org mode fontification error in %S at %d"
  5222. (current-buffer)
  5223. (line-number-at-pos)))))
  5224. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5225. "Fontify #+ lines and blocks."
  5226. (let ((case-fold-search t))
  5227. (when (re-search-forward
  5228. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5229. limit t)
  5230. (let ((beg (match-beginning 0))
  5231. (block-start (match-end 0))
  5232. (block-end nil)
  5233. (lang (match-string 7))
  5234. (beg1 (line-beginning-position 2))
  5235. (dc1 (downcase (match-string 2)))
  5236. (dc3 (downcase (match-string 3)))
  5237. end end1 quoting block-type)
  5238. (cond
  5239. ((and (match-end 4) (equal dc3 "+begin"))
  5240. ;; Truly a block
  5241. (setq block-type (downcase (match-string 5))
  5242. quoting (member block-type org-protecting-blocks))
  5243. (when (re-search-forward
  5244. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5245. nil t) ;; on purpose, we look further than LIMIT
  5246. (setq end (min (point-max) (match-end 0))
  5247. end1 (min (point-max) (1- (match-beginning 0))))
  5248. (setq block-end (match-beginning 0))
  5249. (when quoting
  5250. (org-remove-flyspell-overlays-in beg1 end1)
  5251. (remove-text-properties beg end
  5252. '(display t invisible t intangible t)))
  5253. (add-text-properties
  5254. beg end '(font-lock-fontified t font-lock-multiline t))
  5255. (add-text-properties beg beg1 '(face org-meta-line))
  5256. (org-remove-flyspell-overlays-in beg beg1)
  5257. (add-text-properties ; For end_src
  5258. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5259. (org-remove-flyspell-overlays-in end1 end)
  5260. (cond
  5261. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5262. (org-src-font-lock-fontify-block lang block-start block-end)
  5263. (add-text-properties beg1 block-end '(src-block t)))
  5264. (quoting
  5265. (add-text-properties beg1 (min (point-max) (1+ end1))
  5266. (list 'face
  5267. (list :inherit
  5268. (let ((face-name
  5269. (intern (format "org-block-%s" lang))))
  5270. (append (and (facep face-name) (list face-name))
  5271. '(org-block))))))) ; end of source block
  5272. ((not org-fontify-quote-and-verse-blocks))
  5273. ((string= block-type "quote")
  5274. (add-face-text-property
  5275. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5276. ((string= block-type "verse")
  5277. (add-face-text-property
  5278. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5279. (add-text-properties beg beg1 '(face org-block-begin-line))
  5280. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5281. '(face org-block-end-line))
  5282. t))
  5283. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5284. (org-remove-flyspell-overlays-in
  5285. (match-beginning 0)
  5286. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5287. (add-text-properties
  5288. beg (match-end 3)
  5289. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5290. '(font-lock-fontified t invisible t)
  5291. '(font-lock-fontified t face org-document-info-keyword)))
  5292. (add-text-properties
  5293. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5294. (if (string-equal dc1 "+title:")
  5295. '(font-lock-fontified t face org-document-title)
  5296. '(font-lock-fontified t face org-document-info))))
  5297. ((string-prefix-p "+caption" dc1)
  5298. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5299. (remove-text-properties (match-beginning 0) (match-end 0)
  5300. '(display t invisible t intangible t))
  5301. ;; Handle short captions.
  5302. (save-excursion
  5303. (beginning-of-line)
  5304. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5305. (add-text-properties (line-beginning-position) (match-end 1)
  5306. '(font-lock-fontified t face org-meta-line))
  5307. (add-text-properties (match-end 0) (line-end-position)
  5308. '(font-lock-fontified t face org-block))
  5309. t)
  5310. ((member dc3 '(" " ""))
  5311. (org-remove-flyspell-overlays-in beg (match-end 0))
  5312. (add-text-properties
  5313. beg (match-end 0)
  5314. '(font-lock-fontified t face font-lock-comment-face)))
  5315. (t ;; just any other in-buffer setting, but not indented
  5316. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5317. (remove-text-properties (match-beginning 0) (match-end 0)
  5318. '(display t invisible t intangible t))
  5319. (add-text-properties beg (match-end 0)
  5320. '(font-lock-fontified t face org-meta-line))
  5321. t))))))
  5322. (defun org-fontify-drawers (limit)
  5323. "Fontify drawers."
  5324. (when (re-search-forward org-drawer-regexp limit t)
  5325. (add-text-properties
  5326. (match-beginning 0) (match-end 0)
  5327. '(font-lock-fontified t face org-special-keyword))
  5328. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5329. t))
  5330. (defun org-fontify-macros (limit)
  5331. "Fontify macros."
  5332. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5333. (let ((begin (match-beginning 0))
  5334. (opening-end (match-beginning 1)))
  5335. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5336. (match-string 1))
  5337. (let ((end (match-end 1))
  5338. (closing-start (match-beginning 1)))
  5339. (add-text-properties
  5340. begin end
  5341. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5342. (org-remove-flyspell-overlays-in begin end)
  5343. (when org-hide-macro-markers
  5344. (add-text-properties begin opening-end '(invisible t))
  5345. (add-text-properties closing-start end '(invisible t)))
  5346. t)))))
  5347. (defun org-activate-footnote-links (limit)
  5348. "Add text properties for footnotes."
  5349. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5350. (when fn
  5351. (let* ((beg (nth 1 fn))
  5352. (end (nth 2 fn))
  5353. (label (car fn))
  5354. (referencep (/= (line-beginning-position) beg)))
  5355. (when (and referencep (nth 3 fn))
  5356. (save-excursion
  5357. (goto-char beg)
  5358. (search-forward (or label "fn:"))
  5359. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5360. (add-text-properties beg end
  5361. (list 'mouse-face 'highlight
  5362. 'keymap org-mouse-map
  5363. 'help-echo
  5364. (if referencep "Footnote reference"
  5365. "Footnote definition")
  5366. 'font-lock-fontified t
  5367. 'font-lock-multiline t
  5368. 'face 'org-footnote))))))
  5369. (defun org-activate-dates (limit)
  5370. "Add text properties for dates."
  5371. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5372. (not (equal (char-before (match-beginning 0)) 91)))
  5373. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5374. (add-text-properties (match-beginning 0) (match-end 0)
  5375. (list 'mouse-face 'highlight
  5376. 'keymap org-mouse-map))
  5377. (org-rear-nonsticky-at (match-end 0))
  5378. (when org-display-custom-times
  5379. ;; If it's a date range, activate custom time for second date.
  5380. (when (match-end 3)
  5381. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5382. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5383. t))
  5384. (defvar-local org-target-link-regexp nil
  5385. "Regular expression matching radio targets in plain text.")
  5386. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5387. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5388. border border border))
  5389. "Regular expression matching a link target.")
  5390. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5391. "Regular expression matching a radio target.")
  5392. (defconst org-any-target-regexp
  5393. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5394. "Regular expression matching any target.")
  5395. (defun org-activate-target-links (limit)
  5396. "Add text properties for target matches."
  5397. (when org-target-link-regexp
  5398. (let ((case-fold-search t))
  5399. (when (re-search-forward org-target-link-regexp limit t)
  5400. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5401. (add-text-properties (match-beginning 1) (match-end 1)
  5402. (list 'mouse-face 'highlight
  5403. 'keymap org-mouse-map
  5404. 'help-echo "Radio target link"
  5405. 'org-linked-text t))
  5406. (org-rear-nonsticky-at (match-end 1))
  5407. t))))
  5408. (defun org-update-radio-target-regexp ()
  5409. "Find all radio targets in this file and update the regular expression.
  5410. Also refresh fontification if needed."
  5411. (interactive)
  5412. (let ((old-regexp org-target-link-regexp)
  5413. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5414. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5415. (targets
  5416. (org-with-wide-buffer
  5417. (goto-char (point-min))
  5418. (let (rtn)
  5419. (while (re-search-forward org-radio-target-regexp nil t)
  5420. ;; Make sure point is really within the object.
  5421. (backward-char)
  5422. (let ((obj (org-element-context)))
  5423. (when (eq (org-element-type obj) 'radio-target)
  5424. (cl-pushnew (org-element-property :value obj) rtn
  5425. :test #'equal))))
  5426. rtn))))
  5427. (setq org-target-link-regexp
  5428. (and targets
  5429. (concat before-re
  5430. (mapconcat
  5431. (lambda (x)
  5432. (replace-regexp-in-string
  5433. " +" "\\s-+" (regexp-quote x) t t))
  5434. targets
  5435. "\\|")
  5436. after-re)))
  5437. (unless (equal old-regexp org-target-link-regexp)
  5438. ;; Clean-up cache.
  5439. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5440. ((not org-target-link-regexp) old-regexp)
  5441. (t
  5442. (concat before-re
  5443. (mapconcat
  5444. (lambda (re)
  5445. (substring re (length before-re)
  5446. (- (length after-re))))
  5447. (list old-regexp org-target-link-regexp)
  5448. "\\|")
  5449. after-re)))))
  5450. (org-with-wide-buffer
  5451. (goto-char (point-min))
  5452. (while (re-search-forward regexp nil t)
  5453. (org-element-cache-refresh (match-beginning 1)))))
  5454. ;; Re fontify buffer.
  5455. (when (memq 'radio org-highlight-links)
  5456. (org-restart-font-lock)))))
  5457. (defvar org-latex-and-related-regexp nil
  5458. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5459. (defun org-compute-latex-and-related-regexp ()
  5460. "Compute regular expression for LaTeX, entities and sub/superscript.
  5461. Result depends on variable `org-highlight-latex-and-related'."
  5462. (setq-local
  5463. org-latex-and-related-regexp
  5464. (let* ((re-sub
  5465. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5466. ((eq org-use-sub-superscripts '{})
  5467. (list org-match-substring-with-braces-regexp))
  5468. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5469. (re-latex
  5470. (when (memq 'latex org-highlight-latex-and-related)
  5471. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5472. (delq nil
  5473. (mapcar (lambda (x)
  5474. (and (member (car x) matchers) (nth 1 x)))
  5475. org-latex-regexps)))))
  5476. (re-entities
  5477. (when (memq 'entities org-highlight-latex-and-related)
  5478. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5479. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5480. (defun org-do-latex-and-related (limit)
  5481. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5482. LIMIT bounds the search for syntax to highlight. Stop at first
  5483. highlighted object, if any. Return t if some highlighting was
  5484. done, nil otherwise."
  5485. (when (org-string-nw-p org-latex-and-related-regexp)
  5486. (catch 'found
  5487. (while (re-search-forward org-latex-and-related-regexp limit t)
  5488. (unless
  5489. (cl-some
  5490. (lambda (f)
  5491. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5492. (save-excursion
  5493. (goto-char (1+ (match-beginning 0)))
  5494. (face-at-point nil t)))
  5495. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5496. '(?_ ?^))
  5497. 1
  5498. 0)))
  5499. (font-lock-prepend-text-property
  5500. (+ offset (match-beginning 0)) (match-end 0)
  5501. 'face 'org-latex-and-related)
  5502. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5503. '(font-lock-multiline t)))
  5504. (throw 'found t)))
  5505. nil)))
  5506. (defun org-restart-font-lock ()
  5507. "Restart `font-lock-mode', to force refontification."
  5508. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5509. (font-lock-mode -1)
  5510. (font-lock-mode 1)))
  5511. (defun org-activate-tags (limit)
  5512. (when (re-search-forward org-tag-line-re limit t)
  5513. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5514. (add-text-properties (match-beginning 1) (match-end 1)
  5515. (list 'mouse-face 'highlight
  5516. 'keymap org-mouse-map))
  5517. (org-rear-nonsticky-at (match-end 1))
  5518. t))
  5519. (defun org-outline-level ()
  5520. "Compute the outline level of the heading at point.
  5521. If this is called at a normal headline, the level is the number
  5522. of stars. Use `org-reduced-level' to remove the effect of
  5523. `org-odd-levels'. Unlike to `org-current-level', this function
  5524. takes into consideration inlinetasks."
  5525. (org-with-wide-buffer
  5526. (end-of-line)
  5527. (if (re-search-backward org-outline-regexp-bol nil t)
  5528. (1- (- (match-end 0) (match-beginning 0)))
  5529. 0)))
  5530. (defvar org-font-lock-keywords nil)
  5531. (defsubst org-re-property (property &optional literal allow-null value)
  5532. "Return a regexp matching a PROPERTY line.
  5533. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5534. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5535. non-nil, match properties even without a value.
  5536. Match group 3 is set to the value when it exists. If there is no
  5537. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5538. With optional argument VALUE, match only property lines with
  5539. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5540. unless LITERAL is non-nil."
  5541. (concat
  5542. "^\\(?4:[ \t]*\\)"
  5543. (format "\\(?1::\\(?2:%s\\):\\)"
  5544. (if literal property (regexp-quote property)))
  5545. (cond (value
  5546. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5547. (if literal value (regexp-quote value))))
  5548. (allow-null
  5549. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5550. (t
  5551. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5552. (defconst org-property-re
  5553. (org-re-property "\\S-+" 'literal t)
  5554. "Regular expression matching a property line.
  5555. There are four matching groups:
  5556. 1: :PROPKEY: including the leading and trailing colon,
  5557. 2: PROPKEY without the leading and trailing colon,
  5558. 3: PROPVAL without leading or trailing spaces,
  5559. 4: the indentation of the current line,
  5560. 5: trailing whitespace.")
  5561. (defvar org-font-lock-hook nil
  5562. "Functions to be called for special font lock stuff.")
  5563. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5564. (defvar org-font-lock-set-keywords-hook nil
  5565. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5566. This is called after `org-font-lock-extra-keywords' is defined, but before
  5567. it is installed to be used by font lock. This can be useful if something
  5568. needs to be inserted at a specific position in the font-lock sequence.")
  5569. (defun org-font-lock-hook (limit)
  5570. "Run `org-font-lock-hook' within LIMIT."
  5571. (run-hook-with-args 'org-font-lock-hook limit))
  5572. (defun org-set-font-lock-defaults ()
  5573. "Set font lock defaults for the current buffer."
  5574. (let* ((em org-fontify-emphasized-text)
  5575. (lk org-highlight-links)
  5576. (org-font-lock-extra-keywords
  5577. (list
  5578. ;; Call the hook
  5579. '(org-font-lock-hook)
  5580. ;; Headlines
  5581. `(,(if org-fontify-whole-heading-line
  5582. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5583. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5584. (1 (org-get-level-face 1))
  5585. (2 (org-get-level-face 2))
  5586. (3 (org-get-level-face 3)))
  5587. ;; Table lines
  5588. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5589. (1 'org-table t))
  5590. ;; Table internals
  5591. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5592. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5593. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5594. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5595. ;; Drawers
  5596. '(org-fontify-drawers)
  5597. ;; Properties
  5598. (list org-property-re
  5599. '(1 'org-special-keyword t)
  5600. '(3 'org-property-value t))
  5601. ;; Link related fontification.
  5602. '(org-activate-links)
  5603. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5604. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5605. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5606. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5607. ;; Targets.
  5608. (list org-any-target-regexp '(0 'org-target t))
  5609. ;; Diary sexps.
  5610. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5611. ;; Macro
  5612. '(org-fontify-macros)
  5613. ;; TODO keyword
  5614. (list (format org-heading-keyword-regexp-format
  5615. org-todo-regexp)
  5616. '(2 (org-get-todo-face 2) t))
  5617. ;; DONE
  5618. (if org-fontify-done-headline
  5619. (list (format org-heading-keyword-regexp-format
  5620. (concat
  5621. "\\(?:"
  5622. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5623. "\\)"))
  5624. '(2 'org-headline-done t))
  5625. nil)
  5626. ;; Priorities
  5627. '(org-font-lock-add-priority-faces)
  5628. ;; Tags
  5629. '(org-font-lock-add-tag-faces)
  5630. ;; Tags groups
  5631. (when (and org-group-tags org-tag-groups-alist)
  5632. (list (concat org-outline-regexp-bol ".+\\(:"
  5633. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5634. ":\\).*$")
  5635. '(1 'org-tag-group prepend)))
  5636. ;; Special keywords
  5637. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5638. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5639. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5640. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5641. ;; Emphasis
  5642. (when em '(org-do-emphasis-faces))
  5643. ;; Checkboxes
  5644. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5645. 1 'org-checkbox prepend)
  5646. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5647. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5648. (0 (org-get-checkbox-statistics-face) t)))
  5649. ;; Description list items
  5650. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5651. 1 'org-list-dt prepend)
  5652. ;; ARCHIVEd headings
  5653. (list (concat
  5654. org-outline-regexp-bol
  5655. "\\(.*:" org-archive-tag ":.*\\)")
  5656. '(1 'org-archived prepend))
  5657. ;; Specials
  5658. '(org-do-latex-and-related)
  5659. '(org-fontify-entities)
  5660. '(org-raise-scripts)
  5661. ;; Code
  5662. '(org-activate-code (1 'org-code t))
  5663. ;; COMMENT
  5664. (list (format
  5665. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5666. org-todo-regexp
  5667. org-comment-string)
  5668. '(9 'org-special-keyword t))
  5669. ;; Blocks and meta lines
  5670. '(org-fontify-meta-lines-and-blocks))))
  5671. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5672. (run-hooks 'org-font-lock-set-keywords-hook)
  5673. ;; Now set the full font-lock-keywords
  5674. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5675. (setq-local font-lock-defaults
  5676. '(org-font-lock-keywords t nil nil backward-paragraph))
  5677. (kill-local-variable 'font-lock-keywords)
  5678. nil))
  5679. (defun org-toggle-pretty-entities ()
  5680. "Toggle the composition display of entities as UTF8 characters."
  5681. (interactive)
  5682. (setq-local org-pretty-entities (not org-pretty-entities))
  5683. (org-restart-font-lock)
  5684. (if org-pretty-entities
  5685. (message "Entities are now displayed as UTF8 characters")
  5686. (save-restriction
  5687. (widen)
  5688. (decompose-region (point-min) (point-max))
  5689. (message "Entities are now displayed as plain text"))))
  5690. (defvar-local org-custom-properties-overlays nil
  5691. "List of overlays used for custom properties.")
  5692. (defun org-toggle-custom-properties-visibility ()
  5693. "Display or hide properties in `org-custom-properties'."
  5694. (interactive)
  5695. (if org-custom-properties-overlays
  5696. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5697. (setq org-custom-properties-overlays nil))
  5698. (when org-custom-properties
  5699. (org-with-wide-buffer
  5700. (goto-char (point-min))
  5701. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5702. (while (re-search-forward regexp nil t)
  5703. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5704. (when (and end (< (point) end))
  5705. ;; Hide first custom property in current drawer.
  5706. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5707. (overlay-put o 'invisible t)
  5708. (overlay-put o 'org-custom-property t)
  5709. (push o org-custom-properties-overlays))
  5710. ;; Hide additional custom properties in the same drawer.
  5711. (while (re-search-forward regexp end t)
  5712. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5713. (overlay-put o 'invisible t)
  5714. (overlay-put o 'org-custom-property t)
  5715. (push o org-custom-properties-overlays)))))
  5716. ;; Each entry is limited to a single property drawer.
  5717. (outline-next-heading)))))))
  5718. (defun org-fontify-entities (limit)
  5719. "Find an entity to fontify."
  5720. (let (ee)
  5721. (when org-pretty-entities
  5722. (catch 'match
  5723. ;; "\_ "-family is left out on purpose. Only the first one,
  5724. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5725. ;; confusing when adding a second white space character.
  5726. (while (re-search-forward
  5727. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5728. limit t)
  5729. (when (and (not (org-at-comment-p))
  5730. (setq ee (org-entity-get (match-string 1)))
  5731. (= (length (nth 6 ee)) 1))
  5732. (let* ((end (if (equal (match-string 2) "{}")
  5733. (match-end 2)
  5734. (match-end 1))))
  5735. (add-text-properties
  5736. (match-beginning 0) end
  5737. (list 'font-lock-fontified t))
  5738. (compose-region (match-beginning 0) end
  5739. (nth 6 ee) nil)
  5740. (backward-char 1)
  5741. (throw 'match t))))
  5742. nil))))
  5743. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5744. "Fontify string S like in Org mode."
  5745. (with-temp-buffer
  5746. (insert s)
  5747. (let ((org-odd-levels-only odd-levels))
  5748. (org-mode)
  5749. (org-font-lock-ensure)
  5750. (buffer-string))))
  5751. (defvar org-m nil)
  5752. (defvar org-l nil)
  5753. (defvar org-f nil)
  5754. (defun org-get-level-face (n)
  5755. "Get the right face for match N in font-lock matching of headlines."
  5756. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5757. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5758. (if org-cycle-level-faces
  5759. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5760. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5761. (cond
  5762. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5763. ((eq n 2) org-f)
  5764. (t (unless org-level-color-stars-only org-f))))
  5765. (defun org-face-from-face-or-color (context inherit face-or-color)
  5766. "Create a face list that inherits INHERIT, but sets the foreground color.
  5767. When FACE-OR-COLOR is not a string, just return it."
  5768. (if (stringp face-or-color)
  5769. (list :inherit inherit
  5770. (cdr (assoc context org-faces-easy-properties))
  5771. face-or-color)
  5772. face-or-color))
  5773. (defun org-get-todo-face (kwd)
  5774. "Get the right face for a TODO keyword KWD.
  5775. If KWD is a number, get the corresponding match group."
  5776. (when (numberp kwd) (setq kwd (match-string kwd)))
  5777. (or (org-face-from-face-or-color
  5778. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5779. (and (member kwd org-done-keywords) 'org-done)
  5780. 'org-todo))
  5781. (defun org-get-priority-face (priority)
  5782. "Get the right face for PRIORITY.
  5783. PRIORITY is a character."
  5784. (or (org-face-from-face-or-color
  5785. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5786. 'org-priority))
  5787. (defun org-get-tag-face (tag)
  5788. "Get the right face for TAG.
  5789. If TAG is a number, get the corresponding match group."
  5790. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5791. (or (org-face-from-face-or-color
  5792. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5793. 'org-tag)))
  5794. (defun org-font-lock-add-priority-faces (limit)
  5795. "Add the special priority faces."
  5796. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5797. (add-text-properties
  5798. (match-beginning 1) (match-end 1)
  5799. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5800. 'font-lock-fontified t))))
  5801. (defun org-font-lock-add-tag-faces (limit)
  5802. "Add the special tag faces."
  5803. (when (and org-tag-faces org-tags-special-faces-re)
  5804. (while (re-search-forward org-tags-special-faces-re limit t)
  5805. (add-text-properties (match-beginning 1) (match-end 1)
  5806. (list 'face (org-get-tag-face 1)
  5807. 'font-lock-fontified t))
  5808. (backward-char 1))))
  5809. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5810. "Remove fontification and activation overlays from links."
  5811. (font-lock-default-unfontify-region beg end)
  5812. (let* ((buffer-undo-list t)
  5813. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5814. (inhibit-modification-hooks t)
  5815. deactivate-mark buffer-file-name buffer-file-truename)
  5816. (decompose-region beg end)
  5817. (remove-text-properties beg end
  5818. '(mouse-face t keymap t org-linked-text t
  5819. invisible t intangible t
  5820. org-emphasis t))
  5821. (org-remove-font-lock-display-properties beg end)))
  5822. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5823. ((raise 0.3) (height 0.7))
  5824. ((raise -0.5))
  5825. ((raise 0.5)))
  5826. "Display properties for showing superscripts and subscripts.")
  5827. (defun org-remove-font-lock-display-properties (beg end)
  5828. "Remove specific display properties that have been added by font lock.
  5829. The will remove the raise properties that are used to show superscripts
  5830. and subscripts."
  5831. (let (next prop)
  5832. (while (< beg end)
  5833. (setq next (next-single-property-change beg 'display nil end)
  5834. prop (get-text-property beg 'display))
  5835. (when (member prop org-script-display)
  5836. (put-text-property beg next 'display nil))
  5837. (setq beg next))))
  5838. (defun org-raise-scripts (limit)
  5839. "Add raise properties to sub/superscripts."
  5840. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5841. (re-search-forward
  5842. (if (eq org-use-sub-superscripts t)
  5843. org-match-substring-regexp
  5844. org-match-substring-with-braces-regexp)
  5845. limit t))
  5846. (let* ((pos (point)) table-p comment-p
  5847. (mpos (match-beginning 3))
  5848. (emph-p (get-text-property mpos 'org-emphasis))
  5849. (link-p (get-text-property mpos 'mouse-face))
  5850. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5851. (goto-char (point-at-bol))
  5852. (setq table-p (looking-at-p org-table-dataline-regexp)
  5853. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5854. (goto-char pos)
  5855. ;; Handle a_b^c
  5856. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5857. (unless (or comment-p emph-p link-p keyw-p)
  5858. (put-text-property (match-beginning 3) (match-end 0)
  5859. 'display
  5860. (if (equal (char-after (match-beginning 2)) ?^)
  5861. (nth (if table-p 3 1) org-script-display)
  5862. (nth (if table-p 2 0) org-script-display)))
  5863. (add-text-properties (match-beginning 2) (match-end 2)
  5864. (list 'invisible t))
  5865. (when (and (eq (char-after (match-beginning 3)) ?{)
  5866. (eq (char-before (match-end 3)) ?}))
  5867. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5868. (list 'invisible t))
  5869. (add-text-properties (1- (match-end 3)) (match-end 3)
  5870. (list 'invisible t))))
  5871. t)))
  5872. (defun org-remove-empty-overlays-at (pos)
  5873. "Remove outline overlays that do not contain non-white stuff."
  5874. (dolist (o (overlays-at pos))
  5875. (and (eq 'outline (overlay-get o 'invisible))
  5876. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5877. (overlay-end o))))
  5878. (delete-overlay o))))
  5879. (defun org-show-empty-lines-in-parent ()
  5880. "Move to the parent and re-show empty lines before visible headlines."
  5881. (save-excursion
  5882. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5883. (org-cycle-show-empty-lines context))))
  5884. (defun org-files-list ()
  5885. "Return `org-agenda-files' list, plus all open Org files.
  5886. This is useful for operations that need to scan all of a user's
  5887. open and agenda-wise Org files."
  5888. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5889. (dolist (buf (buffer-list))
  5890. (with-current-buffer buf
  5891. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5892. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5893. :test #'equal))))
  5894. files))
  5895. (defsubst org-entry-beginning-position ()
  5896. "Return the beginning position of the current entry."
  5897. (save-excursion (org-back-to-heading t) (point)))
  5898. (defsubst org-entry-end-position ()
  5899. "Return the end position of the current entry."
  5900. (save-excursion (outline-next-heading) (point)))
  5901. (defun org-subtree-end-visible-p ()
  5902. "Is the end of the current subtree visible?"
  5903. (pos-visible-in-window-p
  5904. (save-excursion (org-end-of-subtree t) (point))))
  5905. (defun org-first-headline-recenter ()
  5906. "Move cursor to the first headline and recenter the headline."
  5907. (let ((window (get-buffer-window)))
  5908. (when window
  5909. (goto-char (point-min))
  5910. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5911. (set-window-start window (line-beginning-position))))))
  5912. ;;; Visibility (headlines, blocks, drawers)
  5913. ;;;; Headlines visibility
  5914. (defun org-show-entry ()
  5915. "Show the body directly following this heading.
  5916. Show the heading too, if it is currently invisible."
  5917. (interactive)
  5918. (save-excursion
  5919. (ignore-errors
  5920. (org-back-to-heading t)
  5921. (org-flag-region
  5922. (line-end-position 0)
  5923. (save-excursion
  5924. (if (re-search-forward
  5925. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5926. (match-beginning 1)
  5927. (point-max)))
  5928. nil
  5929. 'outline))))
  5930. (defun org-show-children (&optional level)
  5931. "Show all direct subheadings of this heading.
  5932. Prefix arg LEVEL is how many levels below the current level
  5933. should be shown. Default is enough to cause the following
  5934. heading to appear."
  5935. (interactive "p")
  5936. (save-excursion
  5937. (org-back-to-heading t)
  5938. (let* ((current-level (funcall outline-level))
  5939. (max-level (org-get-valid-level
  5940. current-level
  5941. (if level (prefix-numeric-value level) 1)))
  5942. (end (save-excursion (org-end-of-subtree t t)))
  5943. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5944. (past-first-child nil)
  5945. ;; Make sure to skip inlinetasks.
  5946. (re (format regexp-fmt
  5947. current-level
  5948. (cond
  5949. ((not (featurep 'org-inlinetask)) "")
  5950. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5951. 3))
  5952. (t (1- org-inlinetask-min-level))))))
  5953. ;; Display parent heading.
  5954. (org-flag-heading nil)
  5955. (forward-line)
  5956. ;; Display children. First child may be deeper than expected
  5957. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5958. ;; MAX-LEVEL accordingly.
  5959. (while (re-search-forward re end t)
  5960. (unless past-first-child
  5961. (setq re (format regexp-fmt
  5962. current-level
  5963. (max (funcall outline-level) max-level)))
  5964. (setq past-first-child t))
  5965. (org-flag-heading nil)))))
  5966. (defun org-show-subtree ()
  5967. "Show everything after this heading at deeper levels."
  5968. (interactive)
  5969. (org-flag-region
  5970. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5971. ;;;; Blocks visibility
  5972. (defun org-hide-block-toggle-maybe ()
  5973. "Toggle visibility of block at point.
  5974. Unlike to `org-hide-block-toggle', this function does not throw
  5975. an error. Return a non-nil value when toggling is successful."
  5976. (interactive)
  5977. (ignore-errors (org-hide-block-toggle)))
  5978. (defun org-hide-block-toggle (&optional force)
  5979. "Toggle the visibility of the current block.
  5980. When optional argument FORCE is `off', make block visible. If it
  5981. is non-nil, hide it unconditionally. Throw an error when not at
  5982. a block. Return a non-nil value when toggling is successful."
  5983. (interactive)
  5984. (let ((element (org-element-at-point)))
  5985. (unless (memq (org-element-type element)
  5986. '(center-block comment-block dynamic-block example-block
  5987. export-block quote-block special-block
  5988. src-block verse-block))
  5989. (user-error "Not at a block"))
  5990. (let* ((post (org-element-property :post-affiliated element))
  5991. (start (save-excursion
  5992. (goto-char post)
  5993. (line-end-position)))
  5994. (end (save-excursion
  5995. (goto-char (org-element-property :end element))
  5996. (skip-chars-backward " \t\n")
  5997. (line-end-position))))
  5998. ;; Do nothing when not before or at the block opening line or at
  5999. ;; the block closing line.
  6000. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  6001. (cond ((eq force 'off)
  6002. (org-flag-region start end nil 'org-hide-block))
  6003. (force
  6004. (org-flag-region start end t 'org-hide-block))
  6005. ((eq (get-char-property start 'invisible) 'org-hide-block)
  6006. (org-flag-region start end nil 'org-hide-block))
  6007. (t
  6008. (org-flag-region start end t 'org-hide-block)))
  6009. ;; When the block is hidden away, make sure point is left in
  6010. ;; a visible part of the buffer.
  6011. (when (invisible-p (max (1- (point)) (point-min)))
  6012. (goto-char post))
  6013. ;; Signal success.
  6014. t))))
  6015. (defun org-hide-block-toggle-all ()
  6016. "Toggle the visibility of all blocks in the current buffer."
  6017. (org-block-map 'org-hide-block-toggle))
  6018. (defun org-hide-block-all ()
  6019. "Fold all blocks in the current buffer."
  6020. (interactive)
  6021. (org-show-all '(blocks))
  6022. (org-block-map 'org-hide-block-toggle-maybe))
  6023. ;;;; Drawers visibility
  6024. (defun org-cycle-hide-drawers (state &optional exceptions)
  6025. "Re-hide all drawers after a visibility state change.
  6026. STATE should be one of the symbols listed in the docstring of
  6027. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6028. a list of strings specifying which drawers should not be hidden."
  6029. (when (and (derived-mode-p 'org-mode)
  6030. (not (memq state '(overview folded contents))))
  6031. (save-excursion
  6032. (let* ((globalp (eq state 'all))
  6033. (beg (if globalp (point-min) (point)))
  6034. (end (if globalp (point-max)
  6035. (if (eq state 'children)
  6036. (save-excursion (outline-next-heading) (point))
  6037. (org-end-of-subtree t)))))
  6038. (goto-char beg)
  6039. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6040. (unless (member-ignore-case (match-string 1) exceptions)
  6041. (let ((drawer (org-element-at-point)))
  6042. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6043. (org-flag-drawer t drawer)
  6044. ;; Make sure to skip drawer entirely or we might flag
  6045. ;; it another time when matching its ending line with
  6046. ;; `org-drawer-regexp'.
  6047. (goto-char (org-element-property :end drawer))))))))))
  6048. (defun org-flag-drawer (flag &optional element)
  6049. "When FLAG is non-nil, hide the drawer we are at.
  6050. Otherwise make it visible. When optional argument ELEMENT is
  6051. a parsed drawer, as returned by `org-element-at-point', hide or
  6052. show that drawer instead."
  6053. (let ((drawer (or element
  6054. (and (save-excursion
  6055. (beginning-of-line)
  6056. (looking-at-p org-drawer-regexp))
  6057. (org-element-at-point)))))
  6058. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6059. (let ((post (org-element-property :post-affiliated drawer)))
  6060. (org-flag-region
  6061. (save-excursion (goto-char post) (line-end-position))
  6062. (save-excursion (goto-char (org-element-property :end drawer))
  6063. (skip-chars-backward " \t\n")
  6064. (line-end-position))
  6065. flag 'org-hide-drawer)
  6066. ;; When the drawer is hidden away, make sure point lies in
  6067. ;; a visible part of the buffer.
  6068. (when (invisible-p (max (1- (point)) (point-min)))
  6069. (goto-char post))))))
  6070. ;;;; Visibility cycling
  6071. (defvar-local org-cycle-global-status nil)
  6072. (put 'org-cycle-global-status 'org-state t)
  6073. (defvar-local org-cycle-subtree-status nil)
  6074. (put 'org-cycle-subtree-status 'org-state t)
  6075. (defun org-show-all (&optional types)
  6076. "Show all contents in the visible part of the buffer.
  6077. By default, the function expands headings, blocks and drawers.
  6078. When optional argument TYPE is a list of symbols among `blocks',
  6079. `drawers' and `headings', to only expand one specific type."
  6080. (dolist (type (or types '(blocks drawers headings)))
  6081. (org-flag-region (point-min) (point-max) nil
  6082. (pcase type
  6083. (`blocks 'org-hide-block)
  6084. (`drawers 'org-hide-drawer)
  6085. (`headings 'outline)
  6086. (_ (error "Invalid type: %S" type))))))
  6087. ;;;###autoload
  6088. (defun org-cycle (&optional arg)
  6089. "TAB-action and visibility cycling for Org mode.
  6090. This is the command invoked in Org mode by the `TAB' key. Its main
  6091. purpose is outline visibility cycling, but it also invokes other actions
  6092. in special contexts.
  6093. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6094. the entire
  6095. buffer through 3 states (global cycling)
  6096. 1. OVERVIEW: Show only top-level headlines.
  6097. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6098. 3. SHOW ALL: Show everything.
  6099. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6100. switch to the startup visibility,
  6101. determined by the variable `org-startup-folded', and by any VISIBILITY
  6102. properties in the buffer.
  6103. With a `\\[universal-argument] \\[universal-argument] \
  6104. \\[universal-argument]' prefix argument, show the entire buffer, including
  6105. any drawers.
  6106. When inside a table, re-align the table and move to the next field.
  6107. When point is at the beginning of a headline, rotate the subtree started
  6108. by this line through 3 different states (local cycling)
  6109. 1. FOLDED: Only the main headline is shown.
  6110. 2. CHILDREN: The main headline and the direct children are shown.
  6111. From this state, you can move to one of the children
  6112. and zoom in further.
  6113. 3. SUBTREE: Show the entire subtree, including body text.
  6114. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6115. When point is at the beginning of an empty headline and the variable
  6116. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6117. of the headline by demoting and promoting it to likely levels. This
  6118. speeds up creation document structure by pressing `TAB' once or several
  6119. times right after creating a new headline.
  6120. When there is a numeric prefix, go up to a heading with level ARG, do
  6121. a `show-subtree' and return to the previous cursor position. If ARG
  6122. is negative, go up that many levels.
  6123. When point is not at the beginning of a headline, execute the global
  6124. binding for `TAB', which is re-indenting the line. See the option
  6125. `org-cycle-emulate-tab' for details.
  6126. As a special case, if point is at the beginning of the buffer and there is
  6127. no headline in line 1, this function will act as if called with prefix arg
  6128. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6129. prefix arg, but only
  6130. if the variable `org-cycle-global-at-bob' is t."
  6131. (interactive "P")
  6132. (org-load-modules-maybe)
  6133. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6134. (and org-cycle-level-after-item/entry-creation
  6135. (or (org-cycle-level)
  6136. (org-cycle-item-indentation))))
  6137. (let* ((limit-level
  6138. (or org-cycle-max-level
  6139. (and (boundp 'org-inlinetask-min-level)
  6140. org-inlinetask-min-level
  6141. (1- org-inlinetask-min-level))))
  6142. (nstars (and limit-level
  6143. (if org-odd-levels-only
  6144. (and limit-level (1- (* limit-level 2)))
  6145. limit-level)))
  6146. (org-outline-regexp
  6147. (if (not (derived-mode-p 'org-mode))
  6148. outline-regexp
  6149. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6150. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6151. (not (looking-at org-outline-regexp))))
  6152. (org-cycle-hook
  6153. (if bob-special
  6154. (delq 'org-optimize-window-after-visibility-change
  6155. (copy-sequence org-cycle-hook))
  6156. org-cycle-hook))
  6157. (pos (point)))
  6158. (cond
  6159. ((equal arg '(16))
  6160. (setq last-command 'dummy)
  6161. (org-set-startup-visibility)
  6162. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6163. ((equal arg '(64))
  6164. (org-show-all)
  6165. (org-unlogged-message "Entire buffer visible, including drawers"))
  6166. ((equal arg '(4)) (org-cycle-internal-global))
  6167. ;; Try hiding block at point.
  6168. ((org-hide-block-toggle-maybe))
  6169. ;; Try cdlatex TAB completion
  6170. ((org-try-cdlatex-tab))
  6171. ;; Table: enter it or move to the next field.
  6172. ((org-at-table-p 'any)
  6173. (if (org-at-table.el-p)
  6174. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6175. Use `\\[org-edit-special]' to edit table.el tables"))
  6176. (if arg (org-table-edit-field t)
  6177. (org-table-justify-field-maybe)
  6178. (call-interactively 'org-table-next-field))))
  6179. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6180. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6181. (bob-special (org-cycle-internal-global))
  6182. ;; Drawers: delegate to `org-flag-drawer'.
  6183. ((save-excursion
  6184. (beginning-of-line 1)
  6185. (looking-at org-drawer-regexp))
  6186. (org-flag-drawer ; toggle block visibility
  6187. (not (get-char-property (match-end 0) 'invisible))))
  6188. ;; Show-subtree, ARG levels up from here.
  6189. ((integerp arg)
  6190. (save-excursion
  6191. (org-back-to-heading)
  6192. (outline-up-heading (if (< arg 0) (- arg)
  6193. (- (funcall outline-level) arg)))
  6194. (org-show-subtree)))
  6195. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6196. ((and (featurep 'org-inlinetask)
  6197. (org-inlinetask-at-task-p)
  6198. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6199. (org-inlinetask-toggle-visibility))
  6200. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6201. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6202. (save-excursion (move-beginning-of-line 1)
  6203. (looking-at org-outline-regexp)))
  6204. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6205. (org-cycle-internal-local))
  6206. ;; From there: TAB emulation and template completion.
  6207. (buffer-read-only (org-back-to-heading))
  6208. ((run-hook-with-args-until-success
  6209. 'org-tab-after-check-for-cycling-hook))
  6210. ((run-hook-with-args-until-success
  6211. 'org-tab-before-tab-emulation-hook))
  6212. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6213. (or (not (bolp))
  6214. (not (looking-at org-outline-regexp))))
  6215. (call-interactively (global-key-binding "\t")))
  6216. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6217. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6218. (or (and (eq org-cycle-emulate-tab 'white)
  6219. (= (match-end 0) (point-at-eol)))
  6220. (and (eq org-cycle-emulate-tab 'whitestart)
  6221. (>= (match-end 0) pos))))
  6222. t
  6223. (eq org-cycle-emulate-tab t))
  6224. (call-interactively (global-key-binding "\t")))
  6225. (t (save-excursion
  6226. (org-back-to-heading)
  6227. (org-cycle)))))))
  6228. (defun org-cycle-internal-global ()
  6229. "Do the global cycling action."
  6230. ;; Hack to avoid display of messages for .org attachments in Gnus
  6231. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6232. (cond
  6233. ((and (eq last-command this-command)
  6234. (eq org-cycle-global-status 'overview))
  6235. ;; We just created the overview - now do table of contents
  6236. ;; This can be slow in very large buffers, so indicate action
  6237. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6238. (unless ga (org-unlogged-message "CONTENTS..."))
  6239. (org-content)
  6240. (unless ga (org-unlogged-message "CONTENTS...done"))
  6241. (setq org-cycle-global-status 'contents)
  6242. (run-hook-with-args 'org-cycle-hook 'contents))
  6243. ((and (eq last-command this-command)
  6244. (eq org-cycle-global-status 'contents))
  6245. ;; We just showed the table of contents - now show everything
  6246. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6247. (org-show-all '(headings blocks))
  6248. (unless ga (org-unlogged-message "SHOW ALL"))
  6249. (setq org-cycle-global-status 'all)
  6250. (run-hook-with-args 'org-cycle-hook 'all))
  6251. (t
  6252. ;; Default action: go to overview
  6253. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6254. (org-overview)
  6255. (unless ga (org-unlogged-message "OVERVIEW"))
  6256. (setq org-cycle-global-status 'overview)
  6257. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6258. (defvar org-called-with-limited-levels nil
  6259. "Non-nil when `org-with-limited-levels' is currently active.")
  6260. (defun org-cycle-internal-local ()
  6261. "Do the local cycling action."
  6262. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6263. ;; First, determine end of headline (EOH), end of subtree or item
  6264. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6265. (save-excursion
  6266. (if (org-at-item-p)
  6267. (progn
  6268. (beginning-of-line)
  6269. (setq struct (org-list-struct))
  6270. (setq eoh (point-at-eol))
  6271. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6272. (setq has-children (org-list-has-child-p (point) struct)))
  6273. (org-back-to-heading)
  6274. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6275. (setq eos (save-excursion (org-end-of-subtree t t)
  6276. (when (bolp) (backward-char)) (point)))
  6277. (setq has-children
  6278. (or (save-excursion
  6279. (let ((level (funcall outline-level)))
  6280. (outline-next-heading)
  6281. (and (org-at-heading-p t)
  6282. (> (funcall outline-level) level))))
  6283. (save-excursion
  6284. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6285. ;; Determine end invisible part of buffer (EOL)
  6286. (beginning-of-line 2)
  6287. (while (and (not (eobp)) ;This is like `next-line'.
  6288. (get-char-property (1- (point)) 'invisible))
  6289. (goto-char (next-single-char-property-change (point) 'invisible))
  6290. (and (eolp) (beginning-of-line 2)))
  6291. (setq eol (point)))
  6292. ;; Find out what to do next and set `this-command'
  6293. (cond
  6294. ((= eos eoh)
  6295. ;; Nothing is hidden behind this heading
  6296. (unless (org-before-first-heading-p)
  6297. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6298. (org-unlogged-message "EMPTY ENTRY")
  6299. (setq org-cycle-subtree-status nil)
  6300. (save-excursion
  6301. (goto-char eos)
  6302. (outline-next-heading)
  6303. (when (org-invisible-p) (org-flag-heading nil))))
  6304. ((and (or (>= eol eos)
  6305. (not (string-match "\\S-" (buffer-substring eol eos))))
  6306. (or has-children
  6307. (not (setq children-skipped
  6308. org-cycle-skip-children-state-if-no-children))))
  6309. ;; Entire subtree is hidden in one line: children view
  6310. (unless (org-before-first-heading-p)
  6311. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6312. (if (org-at-item-p)
  6313. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6314. (org-show-entry)
  6315. (org-with-limited-levels (org-show-children))
  6316. (org-show-set-visibility 'canonical)
  6317. ;; Fold every list in subtree to top-level items.
  6318. (when (eq org-cycle-include-plain-lists 'integrate)
  6319. (save-excursion
  6320. (org-back-to-heading)
  6321. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6322. (beginning-of-line 1)
  6323. (let* ((struct (org-list-struct))
  6324. (prevs (org-list-prevs-alist struct))
  6325. (end (org-list-get-bottom-point struct)))
  6326. (dolist (e (org-list-get-all-items (point) struct prevs))
  6327. (org-list-set-item-visibility e struct 'folded))
  6328. (goto-char (if (< end eos) end eos)))))))
  6329. (org-unlogged-message "CHILDREN")
  6330. (save-excursion
  6331. (goto-char eos)
  6332. (outline-next-heading)
  6333. (when (org-invisible-p) (org-flag-heading nil)))
  6334. (setq org-cycle-subtree-status 'children)
  6335. (unless (org-before-first-heading-p)
  6336. (run-hook-with-args 'org-cycle-hook 'children)))
  6337. ((or children-skipped
  6338. (and (eq last-command this-command)
  6339. (eq org-cycle-subtree-status 'children)))
  6340. ;; We just showed the children, or no children are there,
  6341. ;; now show everything.
  6342. (unless (org-before-first-heading-p)
  6343. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6344. (org-flag-region eoh eos nil 'outline)
  6345. (org-unlogged-message
  6346. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6347. (setq org-cycle-subtree-status 'subtree)
  6348. (unless (org-before-first-heading-p)
  6349. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6350. (t
  6351. ;; Default action: hide the subtree.
  6352. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6353. (org-flag-region eoh eos t 'outline)
  6354. (org-unlogged-message "FOLDED")
  6355. (setq org-cycle-subtree-status 'folded)
  6356. (unless (org-before-first-heading-p)
  6357. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6358. ;;;###autoload
  6359. (defun org-global-cycle (&optional arg)
  6360. "Cycle the global visibility. For details see `org-cycle'.
  6361. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6362. With a numeric prefix, show all headlines up to that level."
  6363. (interactive "P")
  6364. (let ((org-cycle-include-plain-lists
  6365. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6366. (cond
  6367. ((integerp arg)
  6368. (org-show-all '(headings blocks))
  6369. (outline-hide-sublevels arg)
  6370. (setq org-cycle-global-status 'contents))
  6371. ((equal arg '(4))
  6372. (org-set-startup-visibility)
  6373. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6374. (t
  6375. (org-cycle '(4))))))
  6376. (defun org-set-startup-visibility ()
  6377. "Set the visibility required by startup options and properties."
  6378. (cond
  6379. ((eq org-startup-folded t)
  6380. (org-overview))
  6381. ((eq org-startup-folded 'content)
  6382. (org-content))
  6383. ((or (eq org-startup-folded 'showeverything)
  6384. (eq org-startup-folded nil))
  6385. (org-show-all)))
  6386. (unless (eq org-startup-folded 'showeverything)
  6387. (when org-hide-block-startup (org-hide-block-all))
  6388. (org-set-visibility-according-to-property)
  6389. (org-cycle-hide-archived-subtrees 'all)
  6390. (org-cycle-hide-drawers 'all)
  6391. (org-cycle-show-empty-lines t)))
  6392. (defun org-set-visibility-according-to-property ()
  6393. "Switch subtree visibilities according to :VISIBILITY: property."
  6394. (interactive)
  6395. (org-with-wide-buffer
  6396. (goto-char (point-min))
  6397. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6398. (if (not (org-at-property-p)) (outline-next-heading)
  6399. (let ((state (match-string 3)))
  6400. (save-excursion
  6401. (org-back-to-heading t)
  6402. (outline-hide-subtree)
  6403. (org-reveal)
  6404. (cond
  6405. ((equal state "folded")
  6406. (outline-hide-subtree))
  6407. ((equal state "children")
  6408. (org-show-hidden-entry)
  6409. (org-show-children))
  6410. ((equal state "content")
  6411. (save-excursion
  6412. (save-restriction
  6413. (org-narrow-to-subtree)
  6414. (org-content))))
  6415. ((member state '("all" "showall"))
  6416. (outline-show-subtree)))))))))
  6417. (defun org-overview ()
  6418. "Switch to overview mode, showing only top-level headlines.
  6419. This shows all headlines with a level equal or greater than the level
  6420. of the first headline in the buffer. This is important, because if the
  6421. first headline is not level one, then (hide-sublevels 1) gives confusing
  6422. results."
  6423. (interactive)
  6424. (save-excursion
  6425. (let ((level
  6426. (save-excursion
  6427. (goto-char (point-min))
  6428. (when (re-search-forward org-outline-regexp-bol nil t)
  6429. (goto-char (match-beginning 0))
  6430. (funcall outline-level)))))
  6431. (and level (outline-hide-sublevels level)))))
  6432. (defun org-content (&optional arg)
  6433. "Show all headlines in the buffer, like a table of contents.
  6434. With numerical argument N, show content up to level N."
  6435. (interactive "P")
  6436. (org-overview)
  6437. (save-excursion
  6438. ;; Visit all headings and show their offspring
  6439. (and (integerp arg) (org-overview))
  6440. (goto-char (point-max))
  6441. (catch 'exit
  6442. (while (and (progn (condition-case nil
  6443. (outline-previous-visible-heading 1)
  6444. (error (goto-char (point-min))))
  6445. t)
  6446. (looking-at org-outline-regexp))
  6447. (if (integerp arg)
  6448. (org-show-children (1- arg))
  6449. (outline-show-branches))
  6450. (when (bobp) (throw 'exit nil))))))
  6451. (defun org-optimize-window-after-visibility-change (state)
  6452. "Adjust the window after a change in outline visibility.
  6453. This function is the default value of the hook `org-cycle-hook'."
  6454. (when (get-buffer-window (current-buffer))
  6455. (cond
  6456. ((eq state 'content) nil)
  6457. ((eq state 'all) nil)
  6458. ((eq state 'folded) nil)
  6459. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6460. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6461. (defun org-clean-visibility-after-subtree-move ()
  6462. "Fix visibility issues after moving a subtree."
  6463. ;; First, find a reasonable region to look at:
  6464. ;; Start two siblings above, end three below
  6465. (let* ((beg (save-excursion
  6466. (and (org-get-last-sibling)
  6467. (org-get-last-sibling))
  6468. (point)))
  6469. (end (save-excursion
  6470. (and (org-get-next-sibling)
  6471. (org-get-next-sibling)
  6472. (org-get-next-sibling))
  6473. (if (org-at-heading-p)
  6474. (point-at-eol)
  6475. (point))))
  6476. (level (looking-at "\\*+"))
  6477. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6478. (save-excursion
  6479. (save-restriction
  6480. (narrow-to-region beg end)
  6481. (when re
  6482. ;; Properly fold already folded siblings
  6483. (goto-char (point-min))
  6484. (while (re-search-forward re nil t)
  6485. (when (and (not (org-invisible-p))
  6486. (org-invisible-p (line-end-position)))
  6487. (outline-hide-entry))))
  6488. (org-cycle-hide-drawers 'all)
  6489. (org-cycle-show-empty-lines 'overview)))))
  6490. (defun org-cycle-show-empty-lines (state)
  6491. "Show empty lines above all visible headlines.
  6492. The region to be covered depends on STATE when called through
  6493. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6494. entire buffer covered. Note that an empty line is only shown if there
  6495. are at least `org-cycle-separator-lines' empty lines before the headline."
  6496. (when (/= org-cycle-separator-lines 0)
  6497. (save-excursion
  6498. (let* ((n (abs org-cycle-separator-lines))
  6499. (re (cond
  6500. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6501. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6502. (t (let ((ns (number-to-string (- n 2))))
  6503. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6504. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6505. beg end)
  6506. (cond
  6507. ((memq state '(overview contents t))
  6508. (setq beg (point-min) end (point-max)))
  6509. ((memq state '(children folded))
  6510. (setq beg (point)
  6511. end (progn (org-end-of-subtree t t)
  6512. (line-beginning-position 2)))))
  6513. (when beg
  6514. (goto-char beg)
  6515. (while (re-search-forward re end t)
  6516. (unless (get-char-property (match-end 1) 'invisible)
  6517. (let ((e (match-end 1))
  6518. (b (if (>= org-cycle-separator-lines 0)
  6519. (match-beginning 1)
  6520. (save-excursion
  6521. (goto-char (match-beginning 0))
  6522. (skip-chars-backward " \t\n")
  6523. (line-end-position)))))
  6524. (org-flag-region b e nil 'outline))))))))
  6525. ;; Never hide empty lines at the end of the file.
  6526. (save-excursion
  6527. (goto-char (point-max))
  6528. (outline-previous-heading)
  6529. (outline-end-of-heading)
  6530. (when (and (looking-at "[ \t\n]+")
  6531. (= (match-end 0) (point-max)))
  6532. (org-flag-region (point) (match-end 0) nil 'outline))))
  6533. ;;;; Reveal point location
  6534. (defun org-show-context (&optional key)
  6535. "Make sure point and context are visible.
  6536. Optional argument KEY, when non-nil, is a symbol. See
  6537. `org-show-context-detail' for allowed values and how much is to
  6538. be shown."
  6539. (org-show-set-visibility
  6540. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6541. ((cdr (assq key org-show-context-detail)))
  6542. (t (cdr (assq 'default org-show-context-detail))))))
  6543. (defun org-show-set-visibility (detail)
  6544. "Set visibility around point according to DETAIL.
  6545. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6546. `tree', `canonical' or t. See `org-show-context-detail' for more
  6547. information."
  6548. ;; Show current heading and possibly its entry, following headline
  6549. ;; or all children.
  6550. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6551. (org-flag-heading nil)
  6552. (org-show-entry)
  6553. ;; If point is hidden within a drawer or a block, make sure to
  6554. ;; expose it.
  6555. (dolist (o (overlays-at (point)))
  6556. (when (memq (overlay-get o 'invisible)
  6557. '(org-hide-block org-hide-drawer outline))
  6558. (delete-overlay o)))
  6559. (unless (org-before-first-heading-p)
  6560. (org-with-limited-levels
  6561. (cl-case detail
  6562. ((tree canonical t) (org-show-children))
  6563. ((nil minimal ancestors))
  6564. (t (save-excursion
  6565. (outline-next-heading)
  6566. (org-flag-heading nil)))))))
  6567. ;; Show all siblings.
  6568. (when (eq detail 'lineage) (org-show-siblings))
  6569. ;; Show ancestors, possibly with their children.
  6570. (when (memq detail '(ancestors lineage tree canonical t))
  6571. (save-excursion
  6572. (while (org-up-heading-safe)
  6573. (org-flag-heading nil)
  6574. (when (memq detail '(canonical t)) (org-show-entry))
  6575. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6576. (defvar org-reveal-start-hook nil
  6577. "Hook run before revealing a location.")
  6578. (defun org-reveal (&optional siblings)
  6579. "Show current entry, hierarchy above it, and the following headline.
  6580. This can be used to show a consistent set of context around
  6581. locations exposed with `org-show-context'.
  6582. With optional argument SIBLINGS, on each level of the hierarchy all
  6583. siblings are shown. This repairs the tree structure to what it would
  6584. look like when opened with hierarchical calls to `org-cycle'.
  6585. With a \\[universal-argument] \\[universal-argument] prefix, \
  6586. go to the parent and show the entire tree."
  6587. (interactive "P")
  6588. (run-hooks 'org-reveal-start-hook)
  6589. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6590. ((equal siblings '(16))
  6591. (save-excursion
  6592. (when (org-up-heading-safe)
  6593. (org-show-subtree)
  6594. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6595. (t (org-show-set-visibility 'lineage))))
  6596. ;;; Indirect buffer display of subtrees
  6597. (defvar org-indirect-dedicated-frame nil
  6598. "This is the frame being used for indirect tree display.")
  6599. (defvar org-last-indirect-buffer nil)
  6600. (defun org-tree-to-indirect-buffer (&optional arg)
  6601. "Create indirect buffer and narrow it to current subtree.
  6602. With a numerical prefix ARG, go up to this level and then take that tree.
  6603. If ARG is negative, go up that many levels.
  6604. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6605. indirect buffer previously made with this command, to avoid proliferation of
  6606. indirect buffers. However, when you call the command with a \
  6607. `\\[universal-argument]' prefix, or
  6608. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6609. so that you can work with several indirect buffers at the same time. If
  6610. `org-indirect-buffer-display' is `dedicated-frame', the \
  6611. `\\[universal-argument]' prefix also
  6612. requests that a new frame be made for the new buffer, so that the dedicated
  6613. frame is not changed."
  6614. (interactive "P")
  6615. (let ((cbuf (current-buffer))
  6616. (cwin (selected-window))
  6617. (pos (point))
  6618. beg end level heading ibuf)
  6619. (save-excursion
  6620. (org-back-to-heading t)
  6621. (when (numberp arg)
  6622. (setq level (org-outline-level))
  6623. (when (< arg 0) (setq arg (+ level arg)))
  6624. (while (> (setq level (org-outline-level)) arg)
  6625. (org-up-heading-safe)))
  6626. (setq beg (point)
  6627. heading (org-get-heading 'no-tags))
  6628. (org-end-of-subtree t t)
  6629. (when (org-at-heading-p) (backward-char 1))
  6630. (setq end (point)))
  6631. (when (and (buffer-live-p org-last-indirect-buffer)
  6632. (not (eq org-indirect-buffer-display 'new-frame))
  6633. (not arg))
  6634. (kill-buffer org-last-indirect-buffer))
  6635. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6636. org-last-indirect-buffer ibuf)
  6637. (cond
  6638. ((or (eq org-indirect-buffer-display 'new-frame)
  6639. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6640. (select-frame (make-frame))
  6641. (delete-other-windows)
  6642. (pop-to-buffer-same-window ibuf)
  6643. (org-set-frame-title heading))
  6644. ((eq org-indirect-buffer-display 'dedicated-frame)
  6645. (raise-frame
  6646. (select-frame (or (and org-indirect-dedicated-frame
  6647. (frame-live-p org-indirect-dedicated-frame)
  6648. org-indirect-dedicated-frame)
  6649. (setq org-indirect-dedicated-frame (make-frame)))))
  6650. (delete-other-windows)
  6651. (pop-to-buffer-same-window ibuf)
  6652. (org-set-frame-title (concat "Indirect: " heading)))
  6653. ((eq org-indirect-buffer-display 'current-window)
  6654. (pop-to-buffer-same-window ibuf))
  6655. ((eq org-indirect-buffer-display 'other-window)
  6656. (pop-to-buffer ibuf))
  6657. (t (error "Invalid value")))
  6658. (narrow-to-region beg end)
  6659. (org-show-all '(headings blocks))
  6660. (goto-char pos)
  6661. (run-hook-with-args 'org-cycle-hook 'all)
  6662. (and (window-live-p cwin) (select-window cwin))))
  6663. (defun org-get-indirect-buffer (&optional buffer heading)
  6664. (setq buffer (or buffer (current-buffer)))
  6665. (let ((n 1) (base (buffer-name buffer)) bname)
  6666. (while (buffer-live-p
  6667. (get-buffer
  6668. (setq bname
  6669. (concat base "-"
  6670. (if heading (concat heading "-" (number-to-string n))
  6671. (number-to-string n))))))
  6672. (setq n (1+ n)))
  6673. (condition-case nil
  6674. (make-indirect-buffer buffer bname 'clone)
  6675. (error (make-indirect-buffer buffer bname)))))
  6676. (defun org-set-frame-title (title)
  6677. "Set the title of the current frame to the string TITLE."
  6678. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6679. ;;;; Structure editing
  6680. ;;; Inserting headlines
  6681. (defun org--line-empty-p (n)
  6682. "Is the Nth next line empty?
  6683. Counts the current line as N = 1 and the previous line as N = 0;
  6684. see `beginning-of-line'."
  6685. (save-excursion
  6686. (and (not (bobp))
  6687. (or (beginning-of-line n) t)
  6688. (save-match-data
  6689. (looking-at "[ \t]*$")))))
  6690. (defun org-previous-line-empty-p ()
  6691. "Is the previous line a blank line?
  6692. When NEXT is non-nil, check the next line instead."
  6693. (org--line-empty-p 0))
  6694. (defun org-next-line-empty-p ()
  6695. "Is the previous line a blank line?
  6696. When NEXT is non-nil, check the next line instead."
  6697. (org--line-empty-p 2))
  6698. (defun org--blank-before-heading-p (&optional parent)
  6699. "Non-nil when an empty line should precede a new heading here.
  6700. When optional argument PARENT is non-nil, consider parent
  6701. headline instead of current one."
  6702. (pcase (assq 'heading org-blank-before-new-entry)
  6703. (`(heading . auto)
  6704. (save-excursion
  6705. (org-with-limited-levels
  6706. (unless (and (org-before-first-heading-p)
  6707. (not (outline-next-heading)))
  6708. (org-back-to-heading t)
  6709. (when parent (org-up-heading-safe))
  6710. (cond ((not (bobp))
  6711. (org-previous-line-empty-p))
  6712. ((outline-next-heading)
  6713. (org-previous-line-empty-p))
  6714. ;; Ignore trailing spaces on last buffer line.
  6715. ((progn (skip-chars-backward " \t") (bolp))
  6716. (org-previous-line-empty-p))
  6717. (t nil))))))
  6718. (`(heading . ,value) value)
  6719. (_ nil)))
  6720. (defun org-insert-heading (&optional arg invisible-ok top)
  6721. "Insert a new heading or an item with the same depth at point.
  6722. If point is at the beginning of a heading, insert a new heading
  6723. or a new headline above the current one. When at the beginning
  6724. of a regular line of text, turn it into a heading.
  6725. If point is in the middle of a line, split it and create a new
  6726. headline with the text in the current line after point (see
  6727. `org-M-RET-may-split-line' on how to modify this behavior). As
  6728. a special case, on a headline, splitting can only happen on the
  6729. title itself. E.g., this excludes breaking stars or tags.
  6730. With a `\\[universal-argument]' prefix, set \
  6731. `org-insert-heading-respect-content' to
  6732. a non-nil value for the duration of the command. This forces the
  6733. insertion of a heading after the current subtree, independently
  6734. on the location of point.
  6735. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6736. insert the heading at the end of the tree
  6737. above the current heading. For example, if point is within a
  6738. 2nd-level heading, then it will insert a 2nd-level heading at
  6739. the end of the 1st-level parent subtree.
  6740. When INVISIBLE-OK is set, stop at invisible headlines when going
  6741. back. This is important for non-interactive uses of the
  6742. command.
  6743. When optional argument TOP is non-nil, insert a level 1 heading,
  6744. unconditionally."
  6745. (interactive "P")
  6746. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6747. (level (org-current-level))
  6748. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6749. (cond
  6750. ((or org-insert-heading-respect-content
  6751. (member arg '((4) (16)))
  6752. (and (not invisible-ok)
  6753. (invisible-p (max (1- (point)) (point-min)))))
  6754. ;; Position point at the location of insertion.
  6755. (if (not level) ;before first headline
  6756. (org-with-limited-levels (outline-next-heading))
  6757. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6758. ;; is nil.
  6759. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6760. (cond ((equal arg '(16))
  6761. (org-up-heading-safe)
  6762. (org-end-of-subtree t t))
  6763. (t
  6764. (org-end-of-subtree t t))))
  6765. (unless (bolp) (insert "\n")) ;ensure final newline
  6766. (unless (and blank? (org-previous-line-empty-p))
  6767. (org-N-empty-lines-before-current (if blank? 1 0)))
  6768. (insert stars " \n")
  6769. (forward-char -1))
  6770. ;; At a headline...
  6771. ((org-at-heading-p)
  6772. (cond ((bolp)
  6773. (when blank? (save-excursion (insert "\n")))
  6774. (save-excursion (insert stars " \n"))
  6775. (unless (and blank? (org-previous-line-empty-p))
  6776. (org-N-empty-lines-before-current (if blank? 1 0)))
  6777. (end-of-line))
  6778. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6779. (org-match-line org-complex-heading-regexp)
  6780. (org-pos-in-match-range (point) 4))
  6781. ;; Grab the text that should moved to the new headline.
  6782. ;; Preserve tags.
  6783. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6784. (if (looking-at "[ \t]*$") (replace-match "")
  6785. (org-align-tags))
  6786. (end-of-line)
  6787. (when blank? (insert "\n"))
  6788. (insert "\n" stars " ")
  6789. (when (org-string-nw-p split) (insert split))
  6790. (when (eobp) (save-excursion (insert "\n")))))
  6791. (t
  6792. (end-of-line)
  6793. (when blank? (insert "\n"))
  6794. (insert "\n" stars " ")
  6795. (when (eobp) (save-excursion (insert "\n"))))))
  6796. ;; On regular text, turn line into a headline or split, if
  6797. ;; appropriate.
  6798. ((bolp)
  6799. (insert stars " ")
  6800. (unless (and blank? (org-previous-line-empty-p))
  6801. (org-N-empty-lines-before-current (if blank? 1 0))))
  6802. (t
  6803. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6804. (end-of-line))
  6805. (insert "\n" stars " ")
  6806. (unless (and blank? (org-previous-line-empty-p))
  6807. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6808. (run-hooks 'org-insert-heading-hook))
  6809. (defun org-N-empty-lines-before-current (n)
  6810. "Make the number of empty lines before current exactly N.
  6811. So this will delete or add empty lines."
  6812. (let ((column (current-column)))
  6813. (beginning-of-line)
  6814. (unless (bobp)
  6815. (let ((start (save-excursion
  6816. (skip-chars-backward " \r\t\n")
  6817. (line-end-position))))
  6818. (delete-region start (line-end-position 0))))
  6819. (insert (make-string n ?\n))
  6820. (move-to-column column)))
  6821. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6822. "Return the heading of the current entry, without the stars.
  6823. When NO-TAGS is non-nil, don't include tags.
  6824. When NO-TODO is non-nil, don't include TODO keywords.
  6825. When NO-PRIORITY is non-nil, don't include priority cookie.
  6826. When NO-COMMENT is non-nil, don't include COMMENT string.
  6827. Return nil before first heading."
  6828. (unless (org-before-first-heading-p)
  6829. (save-excursion
  6830. (org-back-to-heading t)
  6831. (let ((case-fold-search nil))
  6832. (looking-at org-complex-heading-regexp)
  6833. (let ((todo (and (not no-todo) (match-string 2)))
  6834. (priority (and (not no-priority) (match-string 3)))
  6835. (headline (pcase (match-string 4)
  6836. (`nil "")
  6837. ((and (guard no-comment) h)
  6838. (replace-regexp-in-string
  6839. (eval-when-compile
  6840. (format "\\`%s[ \t]+" org-comment-string))
  6841. "" h))
  6842. (h h)))
  6843. (tags (and (not no-tags) (match-string 5))))
  6844. (mapconcat #'identity
  6845. (delq nil (list todo priority headline tags))
  6846. " "))))))
  6847. (defun org-heading-components ()
  6848. "Return the components of the current heading.
  6849. This is a list with the following elements:
  6850. - the level as an integer
  6851. - the reduced level, different if `org-odd-levels-only' is set.
  6852. - the TODO keyword, or nil
  6853. - the priority character, like ?A, or nil if no priority is given
  6854. - the headline text itself, or the tags string if no headline text
  6855. - the tags string, or nil."
  6856. (save-excursion
  6857. (org-back-to-heading t)
  6858. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6859. (list (length (match-string 1))
  6860. (org-reduced-level (length (match-string 1)))
  6861. (match-string-no-properties 2)
  6862. (and (match-end 3) (aref (match-string 3) 2))
  6863. (match-string-no-properties 4)
  6864. (match-string-no-properties 5)))))
  6865. (defun org-get-entry ()
  6866. "Get the entry text, after heading, entire subtree."
  6867. (save-excursion
  6868. (org-back-to-heading t)
  6869. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6870. (defun org-edit-headline (&optional heading)
  6871. "Edit the current headline.
  6872. Set it to HEADING when provided."
  6873. (interactive)
  6874. (org-with-wide-buffer
  6875. (org-back-to-heading t)
  6876. (let ((case-fold-search nil))
  6877. (when (looking-at org-complex-heading-regexp)
  6878. (let* ((old (match-string-no-properties 4))
  6879. (new (save-match-data
  6880. (org-trim (or heading (read-string "Edit: " old))))))
  6881. (unless (equal old new)
  6882. (if old (replace-match new t t nil 4)
  6883. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6884. (insert " " new))
  6885. (org-align-tags)
  6886. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6887. (defun org-insert-heading-after-current ()
  6888. "Insert a new heading with same level as current, after current subtree."
  6889. (interactive)
  6890. (org-back-to-heading)
  6891. (org-insert-heading)
  6892. (org-move-subtree-down)
  6893. (end-of-line 1))
  6894. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6895. "Insert heading with `org-insert-heading-respect-content' set to t."
  6896. (interactive)
  6897. (org-insert-heading '(4) invisible-ok))
  6898. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6899. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6900. (interactive)
  6901. (org-insert-todo-heading force-state '(4)))
  6902. (defun org-insert-todo-heading (arg &optional force-heading)
  6903. "Insert a new heading with the same level and TODO state as current heading.
  6904. If the heading has no TODO state, or if the state is DONE, use
  6905. the first state (TODO by default). Also with one prefix arg,
  6906. force first state. With two prefix args, force inserting at the
  6907. end of the parent subtree.
  6908. When called at a plain list item, insert a new item with an
  6909. unchecked check box."
  6910. (interactive "P")
  6911. (when (or force-heading (not (org-insert-item 'checkbox)))
  6912. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6913. force-heading))
  6914. (save-excursion
  6915. (org-forward-heading-same-level -1)
  6916. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6917. (let* ((new-mark-x
  6918. (if (or (equal arg '(4))
  6919. (not (match-beginning 2))
  6920. (member (match-string 2) org-done-keywords))
  6921. (car org-todo-keywords-1)
  6922. (match-string 2)))
  6923. (new-mark
  6924. (or
  6925. (run-hook-with-args-until-success
  6926. 'org-todo-get-default-hook new-mark-x nil)
  6927. new-mark-x)))
  6928. (beginning-of-line 1)
  6929. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6930. (if org-treat-insert-todo-heading-as-state-change
  6931. (org-todo new-mark)
  6932. (insert new-mark " "))))
  6933. (when org-provide-todo-statistics
  6934. (org-update-parent-todo-statistics))))
  6935. (defun org-insert-subheading (arg)
  6936. "Insert a new subheading and demote it.
  6937. Works for outline headings and for plain lists alike."
  6938. (interactive "P")
  6939. (org-insert-heading arg)
  6940. (cond
  6941. ((org-at-heading-p) (org-do-demote))
  6942. ((org-at-item-p) (org-indent-item))))
  6943. (defun org-insert-todo-subheading (arg)
  6944. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6945. Works for outline headings and for plain lists alike."
  6946. (interactive "P")
  6947. (org-insert-todo-heading arg)
  6948. (cond
  6949. ((org-at-heading-p) (org-do-demote))
  6950. ((org-at-item-p) (org-indent-item))))
  6951. ;;; Promotion and Demotion
  6952. (defvar org-after-demote-entry-hook nil
  6953. "Hook run after an entry has been demoted.
  6954. The cursor will be at the beginning of the entry.
  6955. When a subtree is being demoted, the hook will be called for each node.")
  6956. (defvar org-after-promote-entry-hook nil
  6957. "Hook run after an entry has been promoted.
  6958. The cursor will be at the beginning of the entry.
  6959. When a subtree is being promoted, the hook will be called for each node.")
  6960. (defun org-promote-subtree ()
  6961. "Promote the entire subtree.
  6962. See also `org-promote'."
  6963. (interactive)
  6964. (save-excursion
  6965. (org-with-limited-levels (org-map-tree 'org-promote)))
  6966. (org-fix-position-after-promote))
  6967. (defun org-demote-subtree ()
  6968. "Demote the entire subtree.
  6969. See `org-demote' and `org-promote'."
  6970. (interactive)
  6971. (save-excursion
  6972. (org-with-limited-levels (org-map-tree 'org-demote)))
  6973. (org-fix-position-after-promote))
  6974. (defun org-do-promote ()
  6975. "Promote the current heading higher up the tree.
  6976. If the region is active in `transient-mark-mode', promote all
  6977. headings in the region."
  6978. (interactive)
  6979. (save-excursion
  6980. (if (org-region-active-p)
  6981. (org-map-region 'org-promote (region-beginning) (region-end))
  6982. (org-promote)))
  6983. (org-fix-position-after-promote))
  6984. (defun org-do-demote ()
  6985. "Demote the current heading lower down the tree.
  6986. If the region is active in `transient-mark-mode', demote all
  6987. headings in the region."
  6988. (interactive)
  6989. (save-excursion
  6990. (if (org-region-active-p)
  6991. (org-map-region 'org-demote (region-beginning) (region-end))
  6992. (org-demote)))
  6993. (org-fix-position-after-promote))
  6994. (defun org-fix-position-after-promote ()
  6995. "Fix cursor position and indentation after demoting/promoting."
  6996. (let ((pos (point)))
  6997. (when (save-excursion
  6998. (beginning-of-line)
  6999. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7000. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7001. (cond ((eobp) (insert " "))
  7002. ((eolp) (insert " "))
  7003. ((equal (char-after) ?\s) (forward-char 1))))))
  7004. (defun org-current-level ()
  7005. "Return the level of the current entry, or nil if before the first headline.
  7006. The level is the number of stars at the beginning of the
  7007. headline. Use `org-reduced-level' to remove the effect of
  7008. `org-odd-levels'. Unlike to `org-outline-level', this function
  7009. ignores inlinetasks."
  7010. (let ((level (org-with-limited-levels (org-outline-level))))
  7011. (and (> level 0) level)))
  7012. (defun org-get-previous-line-level ()
  7013. "Return the outline depth of the last headline before the current line.
  7014. Returns 0 for the first headline in the buffer, and nil if before the
  7015. first headline."
  7016. (and (org-current-level)
  7017. (or (and (/= (line-beginning-position) (point-min))
  7018. (save-excursion (beginning-of-line 0) (org-current-level)))
  7019. 0)))
  7020. (defun org-reduced-level (l)
  7021. "Compute the effective level of a heading.
  7022. This takes into account the setting of `org-odd-levels-only'."
  7023. (cond
  7024. ((zerop l) 0)
  7025. (org-odd-levels-only (1+ (floor (/ l 2))))
  7026. (t l)))
  7027. (defun org-level-increment ()
  7028. "Return the number of stars that will be added or removed at a
  7029. time to headlines when structure editing, based on the value of
  7030. `org-odd-levels-only'."
  7031. (if org-odd-levels-only 2 1))
  7032. (defun org-get-valid-level (level &optional change)
  7033. "Rectify a level change under the influence of `org-odd-levels-only'.
  7034. LEVEL is a current level, CHANGE is by how much the level should
  7035. be modified. Even if CHANGE is nil, LEVEL may be returned
  7036. modified because even level numbers will become the next higher
  7037. odd number. Returns values greater than 0."
  7038. (if org-odd-levels-only
  7039. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7040. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7041. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7042. (max 1 (+ level (or change 0)))))
  7043. (defun org-promote ()
  7044. "Promote the current heading higher up the tree."
  7045. (org-with-wide-buffer
  7046. (org-back-to-heading t)
  7047. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7048. after-change-functions))
  7049. (level (save-match-data (funcall outline-level)))
  7050. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7051. (diff (abs (- level (length up-head) -1))))
  7052. (cond
  7053. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7054. (replace-match "# " nil t))
  7055. ((= level 1)
  7056. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7057. (t (replace-match up-head nil t)))
  7058. (unless (= level 1)
  7059. (when org-auto-align-tags (org-align-tags))
  7060. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7061. (run-hooks 'org-after-promote-entry-hook))))
  7062. (defun org-demote ()
  7063. "Demote the current heading lower down the tree."
  7064. (org-with-wide-buffer
  7065. (org-back-to-heading t)
  7066. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7067. after-change-functions))
  7068. (level (save-match-data (funcall outline-level)))
  7069. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7070. (diff (abs (- level (length down-head) -1))))
  7071. (replace-match down-head nil t)
  7072. (when org-auto-align-tags (org-align-tags))
  7073. (when org-adapt-indentation (org-fixup-indentation diff))
  7074. (run-hooks 'org-after-demote-entry-hook))))
  7075. (defun org-cycle-level ()
  7076. "Cycle the level of an empty headline through possible states.
  7077. This goes first to child, then to parent, level, then up the hierarchy.
  7078. After top level, it switches back to sibling level."
  7079. (interactive)
  7080. (let ((org-adapt-indentation nil))
  7081. (when (org-point-at-end-of-empty-headline)
  7082. (setq this-command 'org-cycle-level) ; Only needed for caching
  7083. (let ((cur-level (org-current-level))
  7084. (prev-level (org-get-previous-line-level)))
  7085. (cond
  7086. ;; If first headline in file, promote to top-level.
  7087. ((= prev-level 0)
  7088. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7089. do (org-do-promote)))
  7090. ;; If same level as prev, demote one.
  7091. ((= prev-level cur-level)
  7092. (org-do-demote))
  7093. ;; If parent is top-level, promote to top level if not already.
  7094. ((= prev-level 1)
  7095. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7096. do (org-do-promote)))
  7097. ;; If top-level, return to prev-level.
  7098. ((= cur-level 1)
  7099. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7100. do (org-do-demote)))
  7101. ;; If less than prev-level, promote one.
  7102. ((< cur-level prev-level)
  7103. (org-do-promote))
  7104. ;; If deeper than prev-level, promote until higher than
  7105. ;; prev-level.
  7106. ((> cur-level prev-level)
  7107. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7108. do (org-do-promote))))
  7109. t))))
  7110. (defun org-map-tree (fun)
  7111. "Call FUN for every heading underneath the current one."
  7112. (org-back-to-heading t)
  7113. (let ((level (funcall outline-level)))
  7114. (save-excursion
  7115. (funcall fun)
  7116. (while (and (progn
  7117. (outline-next-heading)
  7118. (> (funcall outline-level) level))
  7119. (not (eobp)))
  7120. (funcall fun)))))
  7121. (defun org-map-region (fun beg end)
  7122. "Call FUN for every heading between BEG and END."
  7123. (let ((org-ignore-region t))
  7124. (save-excursion
  7125. (setq end (copy-marker end))
  7126. (goto-char beg)
  7127. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7128. (< (point) end))
  7129. (funcall fun))
  7130. (while (and (progn
  7131. (outline-next-heading)
  7132. (< (point) end))
  7133. (not (eobp)))
  7134. (funcall fun)))))
  7135. (defun org-fixup-indentation (diff)
  7136. "Change the indentation in the current entry by DIFF.
  7137. DIFF is an integer. Indentation is done according to the
  7138. following rules:
  7139. - Planning information and property drawers are always indented
  7140. according to the new level of the headline;
  7141. - Footnote definitions and their contents are ignored;
  7142. - Inlinetasks' boundaries are not shifted;
  7143. - Empty lines are ignored;
  7144. - Other lines' indentation are shifted by DIFF columns, unless
  7145. it would introduce a structural change in the document, in
  7146. which case no shifting is done at all.
  7147. Assume point is at a heading or an inlinetask beginning."
  7148. (org-with-wide-buffer
  7149. (narrow-to-region (line-beginning-position)
  7150. (save-excursion
  7151. (if (org-with-limited-levels (org-at-heading-p))
  7152. (org-with-limited-levels (outline-next-heading))
  7153. (org-inlinetask-goto-end))
  7154. (point)))
  7155. (forward-line)
  7156. ;; Indent properly planning info and property drawer.
  7157. (when (looking-at-p org-planning-line-re)
  7158. (org-indent-line)
  7159. (forward-line))
  7160. (when (looking-at org-property-drawer-re)
  7161. (goto-char (match-end 0))
  7162. (forward-line)
  7163. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7164. (catch 'no-shift
  7165. (when (zerop diff) (throw 'no-shift nil))
  7166. ;; If DIFF is negative, first check if a shift is possible at all
  7167. ;; (e.g., it doesn't break structure). This can only happen if
  7168. ;; some contents are not properly indented.
  7169. (let ((case-fold-search t))
  7170. (when (< diff 0)
  7171. (let ((diff (- diff))
  7172. (forbidden-re (concat org-outline-regexp
  7173. "\\|"
  7174. (substring org-footnote-definition-re 1))))
  7175. (save-excursion
  7176. (while (not (eobp))
  7177. (cond
  7178. ((looking-at-p "[ \t]*$") (forward-line))
  7179. ((and (looking-at-p org-footnote-definition-re)
  7180. (let ((e (org-element-at-point)))
  7181. (and (eq (org-element-type e) 'footnote-definition)
  7182. (goto-char (org-element-property :end e))))))
  7183. ((looking-at-p org-outline-regexp) (forward-line))
  7184. ;; Give up if shifting would move before column 0 or
  7185. ;; if it would introduce a headline or a footnote
  7186. ;; definition.
  7187. (t
  7188. (skip-chars-forward " \t")
  7189. (let ((ind (current-column)))
  7190. (when (or (< ind diff)
  7191. (and (= ind diff) (looking-at-p forbidden-re)))
  7192. (throw 'no-shift nil)))
  7193. ;; Ignore contents of example blocks and source
  7194. ;; blocks if their indentation is meant to be
  7195. ;; preserved. Jump to block's closing line.
  7196. (beginning-of-line)
  7197. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7198. (let ((e (org-element-at-point)))
  7199. (and (memq (org-element-type e)
  7200. '(example-block src-block))
  7201. (or org-src-preserve-indentation
  7202. (org-element-property :preserve-indent e))
  7203. (goto-char (org-element-property :end e))
  7204. (progn (skip-chars-backward " \r\t\n")
  7205. (beginning-of-line)
  7206. t))))
  7207. (forward-line))))))))
  7208. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7209. ;; by DIFF. Also skip contents of source or example blocks
  7210. ;; when indentation is meant to be preserved.
  7211. (while (not (eobp))
  7212. (cond
  7213. ((and (looking-at-p org-footnote-definition-re)
  7214. (let ((e (org-element-at-point)))
  7215. (and (eq (org-element-type e) 'footnote-definition)
  7216. (goto-char (org-element-property :end e))))))
  7217. ((looking-at-p org-outline-regexp) (forward-line))
  7218. ((looking-at-p "[ \t]*$") (forward-line))
  7219. (t
  7220. (indent-line-to (+ (current-indentation) diff))
  7221. (beginning-of-line)
  7222. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7223. (let ((e (org-element-at-point)))
  7224. (and (memq (org-element-type e)
  7225. '(example-block src-block))
  7226. (or org-src-preserve-indentation
  7227. (org-element-property :preserve-indent e))
  7228. (goto-char (org-element-property :end e))
  7229. (progn (skip-chars-backward " \r\t\n")
  7230. (beginning-of-line)
  7231. t))))
  7232. (forward-line)))))))))
  7233. (defun org-convert-to-odd-levels ()
  7234. "Convert an Org file with all levels allowed to one with odd levels.
  7235. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7236. level 5 etc."
  7237. (interactive)
  7238. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7239. (let ((outline-level 'org-outline-level)
  7240. (org-odd-levels-only nil) n)
  7241. (save-excursion
  7242. (goto-char (point-min))
  7243. (while (re-search-forward "^\\*\\*+ " nil t)
  7244. (setq n (- (length (match-string 0)) 2))
  7245. (while (>= (setq n (1- n)) 0)
  7246. (org-demote))
  7247. (end-of-line 1))))))
  7248. (defun org-convert-to-oddeven-levels ()
  7249. "Convert an Org file with only odd levels to one with odd/even levels.
  7250. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7251. file contains a section with an even level, conversion would
  7252. destroy the structure of the file. An error is signaled in this
  7253. case."
  7254. (interactive)
  7255. (goto-char (point-min))
  7256. ;; First check if there are no even levels
  7257. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7258. (org-show-set-visibility 'canonical)
  7259. (error "Not all levels are odd in this file. Conversion not possible"))
  7260. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7261. (let ((outline-regexp org-outline-regexp)
  7262. (outline-level 'org-outline-level)
  7263. (org-odd-levels-only nil) n)
  7264. (save-excursion
  7265. (goto-char (point-min))
  7266. (while (re-search-forward "^\\*\\*+ " nil t)
  7267. (setq n (/ (1- (length (match-string 0))) 2))
  7268. (while (>= (setq n (1- n)) 0)
  7269. (org-promote))
  7270. (end-of-line 1))))))
  7271. (defun org-tr-level (n)
  7272. "Make N odd if required."
  7273. (if org-odd-levels-only (1+ (/ n 2)) n))
  7274. ;;; Vertical tree motion, cutting and pasting of subtrees
  7275. (defun org-move-subtree-up (&optional arg)
  7276. "Move the current subtree up past ARG headlines of the same level."
  7277. (interactive "p")
  7278. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7279. (defun org-move-subtree-down (&optional arg)
  7280. "Move the current subtree down past ARG headlines of the same level."
  7281. (interactive "p")
  7282. (setq arg (prefix-numeric-value arg))
  7283. (org-preserve-local-variables
  7284. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7285. 'org-get-last-sibling))
  7286. (ins-point (make-marker))
  7287. (cnt (abs arg))
  7288. (col (current-column))
  7289. beg end txt folded)
  7290. ;; Select the tree
  7291. (org-back-to-heading)
  7292. (setq beg (point))
  7293. (save-match-data
  7294. (save-excursion (outline-end-of-heading)
  7295. (setq folded (org-invisible-p)))
  7296. (progn (org-end-of-subtree nil t)
  7297. (unless (eobp) (backward-char))))
  7298. (outline-next-heading)
  7299. (setq end (point))
  7300. (goto-char beg)
  7301. ;; Find insertion point, with error handling
  7302. (while (> cnt 0)
  7303. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7304. (goto-char beg)
  7305. (user-error "Cannot move past superior level or buffer limit"))
  7306. (setq cnt (1- cnt)))
  7307. (when (> arg 0)
  7308. ;; Moving forward - still need to move over subtree
  7309. (org-end-of-subtree t t)
  7310. (save-excursion
  7311. (org-back-over-empty-lines)
  7312. (or (bolp) (newline))))
  7313. (move-marker ins-point (point))
  7314. (setq txt (buffer-substring beg end))
  7315. (org-save-markers-in-region beg end)
  7316. (delete-region beg end)
  7317. (org-remove-empty-overlays-at beg)
  7318. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7319. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7320. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7321. (let ((bbb (point)))
  7322. (insert-before-markers txt)
  7323. (org-reinstall-markers-in-region bbb)
  7324. (move-marker ins-point bbb))
  7325. (or (bolp) (insert "\n"))
  7326. (goto-char ins-point)
  7327. (org-skip-whitespace)
  7328. (move-marker ins-point nil)
  7329. (if folded
  7330. (outline-hide-subtree)
  7331. (org-show-entry)
  7332. (org-show-children))
  7333. (org-clean-visibility-after-subtree-move)
  7334. ;; move back to the initial column we were at
  7335. (move-to-column col))))
  7336. (defvar org-subtree-clip ""
  7337. "Clipboard for cut and paste of subtrees.
  7338. This is actually only a copy of the kill, because we use the normal kill
  7339. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7340. (defvar org-subtree-clip-folded nil
  7341. "Was the last copied subtree folded?
  7342. This is used to fold the tree back after pasting.")
  7343. (defun org-cut-subtree (&optional n)
  7344. "Cut the current subtree into the clipboard.
  7345. With prefix arg N, cut this many sequential subtrees.
  7346. This is a short-hand for marking the subtree and then cutting it."
  7347. (interactive "p")
  7348. (org-copy-subtree n 'cut))
  7349. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7350. "Copy the current subtree into the clipboard.
  7351. With prefix arg N, copy this many sequential subtrees.
  7352. This is a short-hand for marking the subtree and then copying it.
  7353. If CUT is non-nil, actually cut the subtree.
  7354. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7355. of some markers in the region, even if CUT is non-nil. This is
  7356. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7357. (interactive "p")
  7358. (org-preserve-local-variables
  7359. (let (beg end folded (beg0 (point)))
  7360. (if (called-interactively-p 'any)
  7361. (org-back-to-heading nil) ; take what looks like a subtree
  7362. (org-back-to-heading t)) ; take what is really there
  7363. (setq beg (point))
  7364. (skip-chars-forward " \t\r\n")
  7365. (save-match-data
  7366. (if nosubtrees
  7367. (outline-next-heading)
  7368. (save-excursion (outline-end-of-heading)
  7369. (setq folded (org-invisible-p)))
  7370. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7371. (org-end-of-subtree t t)))
  7372. ;; Include the end of an inlinetask
  7373. (when (and (featurep 'org-inlinetask)
  7374. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7375. "END[ \t]*$")))
  7376. (end-of-line))
  7377. (setq end (point))
  7378. (goto-char beg0)
  7379. (when (> end beg)
  7380. (setq org-subtree-clip-folded folded)
  7381. (when (or cut force-store-markers)
  7382. (org-save-markers-in-region beg end))
  7383. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7384. (setq org-subtree-clip (current-kill 0))
  7385. (message "%s: Subtree(s) with %d characters"
  7386. (if cut "Cut" "Copied")
  7387. (length org-subtree-clip))))))
  7388. (defun org-paste-subtree (&optional level tree for-yank remove)
  7389. "Paste the clipboard as a subtree, with modification of headline level.
  7390. The entire subtree is promoted or demoted in order to match a new headline
  7391. level.
  7392. If the cursor is at the beginning of a headline, the same level as
  7393. that headline is used to paste the tree.
  7394. If not, the new level is derived from the *visible* headings
  7395. before and after the insertion point, and taken to be the inferior headline
  7396. level of the two. So if the previous visible heading is level 3 and the
  7397. next is level 4 (or vice versa), level 4 will be used for insertion.
  7398. This makes sure that the subtree remains an independent subtree and does
  7399. not swallow low level entries.
  7400. You can also force a different level, either by using a numeric prefix
  7401. argument, or by inserting the heading marker by hand. For example, if the
  7402. cursor is after \"*****\", then the tree will be shifted to level 5.
  7403. If optional TREE is given, use this text instead of the kill ring.
  7404. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7405. move back over whitespace before inserting, and move point to the end of
  7406. the inserted text when done.
  7407. When REMOVE is non-nil, remove the subtree from the clipboard."
  7408. (interactive "P")
  7409. (setq tree (or tree (and kill-ring (current-kill 0))))
  7410. (unless (org-kill-is-subtree-p tree)
  7411. (user-error
  7412. (substitute-command-keys
  7413. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7414. (org-with-limited-levels
  7415. (let* ((visp (not (org-invisible-p)))
  7416. (txt tree)
  7417. (old-level (if (string-match org-outline-regexp-bol txt)
  7418. (- (match-end 0) (match-beginning 0) 1)
  7419. -1))
  7420. (force-level
  7421. (cond
  7422. (level (prefix-numeric-value level))
  7423. ;; When point is after the stars in an otherwise empty
  7424. ;; headline, use the number of stars as the forced level.
  7425. ((and (org-match-line "^\\*+[ \t]*$")
  7426. (not (eq ?* (char-after))))
  7427. (org-outline-level))
  7428. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7429. (previous-level
  7430. (save-excursion
  7431. (org-previous-visible-heading 1)
  7432. (if (org-at-heading-p) (org-outline-level) 1)))
  7433. (next-level
  7434. (save-excursion
  7435. (if (org-at-heading-p) (org-outline-level)
  7436. (org-next-visible-heading 1)
  7437. (if (org-at-heading-p) (org-outline-level) 1))))
  7438. (new-level (or force-level (max previous-level next-level)))
  7439. (shift (if (or (= old-level -1)
  7440. (= new-level -1)
  7441. (= old-level new-level))
  7442. 0
  7443. (- new-level old-level)))
  7444. (delta (if (> shift 0) -1 1))
  7445. (func (if (> shift 0) #'org-demote #'org-promote))
  7446. (org-odd-levels-only nil)
  7447. beg end newend)
  7448. ;; Remove the forced level indicator.
  7449. (when (and force-level (not level))
  7450. (delete-region (line-beginning-position) (point)))
  7451. ;; Paste before the next visible heading or at end of buffer,
  7452. ;; unless point is at the beginning of a headline.
  7453. (unless (and (bolp) (org-at-heading-p))
  7454. (org-next-visible-heading 1)
  7455. (unless (bolp) (insert "\n")))
  7456. (setq beg (point))
  7457. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7458. (insert-before-markers txt)
  7459. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7460. (setq newend (point))
  7461. (org-reinstall-markers-in-region beg)
  7462. (setq end (point))
  7463. (goto-char beg)
  7464. (skip-chars-forward " \t\n\r")
  7465. (setq beg (point))
  7466. (when (and (org-invisible-p) visp)
  7467. (save-excursion (outline-show-heading)))
  7468. ;; Shift if necessary.
  7469. (unless (= shift 0)
  7470. (save-restriction
  7471. (narrow-to-region beg end)
  7472. (while (not (= shift 0))
  7473. (org-map-region func (point-min) (point-max))
  7474. (setq shift (+ delta shift)))
  7475. (goto-char (point-min))
  7476. (setq newend (point-max))))
  7477. (when (or for-yank (called-interactively-p 'interactive))
  7478. (message "Clipboard pasted as level %d subtree" new-level))
  7479. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7480. kill-ring
  7481. (equal org-subtree-clip (current-kill 0))
  7482. org-subtree-clip-folded)
  7483. ;; The tree was folded before it was killed/copied
  7484. (outline-hide-subtree))
  7485. (when for-yank (goto-char newend))
  7486. (when remove (pop kill-ring)))))
  7487. (defun org-kill-is-subtree-p (&optional txt)
  7488. "Check if the current kill is an outline subtree, or a set of trees.
  7489. Returns nil if kill does not start with a headline, or if the first
  7490. headline level is not the largest headline level in the tree.
  7491. So this will actually accept several entries of equal levels as well,
  7492. which is OK for `org-paste-subtree'.
  7493. If optional TXT is given, check this string instead of the current kill."
  7494. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7495. (re (org-get-limited-outline-regexp))
  7496. (^re (concat "^" re))
  7497. (start-level (and kill
  7498. (string-match
  7499. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7500. kill)
  7501. (- (match-end 2) (match-beginning 2) 1)))
  7502. (start (1+ (or (match-beginning 2) -1))))
  7503. (if (not start-level)
  7504. (progn
  7505. nil) ;; does not even start with a heading
  7506. (catch 'exit
  7507. (while (setq start (string-match ^re kill (1+ start)))
  7508. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7509. (throw 'exit nil)))
  7510. t))))
  7511. (defvar org-markers-to-move nil
  7512. "Markers that should be moved with a cut-and-paste operation.
  7513. Those markers are stored together with their positions relative to
  7514. the start of the region.")
  7515. (defun org-save-markers-in-region (beg end)
  7516. "Check markers in region.
  7517. If these markers are between BEG and END, record their position relative
  7518. to BEG, so that after moving the block of text, we can put the markers back
  7519. into place.
  7520. This function gets called just before an entry or tree gets cut from the
  7521. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7522. called immediately, to move the markers with the entries."
  7523. (setq org-markers-to-move nil)
  7524. (when (featurep 'org-clock)
  7525. (org-clock-save-markers-for-cut-and-paste beg end))
  7526. (when (featurep 'org-agenda)
  7527. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7528. (defun org-check-and-save-marker (marker beg end)
  7529. "Check if MARKER is between BEG and END.
  7530. If yes, remember the marker and the distance to BEG."
  7531. (when (and (marker-buffer marker)
  7532. (equal (marker-buffer marker) (current-buffer))
  7533. (>= marker beg) (< marker end))
  7534. (push (cons marker (- marker beg)) org-markers-to-move)))
  7535. (defun org-reinstall-markers-in-region (beg)
  7536. "Move all remembered markers to their position relative to BEG."
  7537. (dolist (x org-markers-to-move)
  7538. (move-marker (car x) (+ beg (cdr x))))
  7539. (setq org-markers-to-move nil))
  7540. (defun org-narrow-to-subtree ()
  7541. "Narrow buffer to the current subtree."
  7542. (interactive)
  7543. (save-excursion
  7544. (save-match-data
  7545. (org-with-limited-levels
  7546. (narrow-to-region
  7547. (progn (org-back-to-heading t) (point))
  7548. (progn (org-end-of-subtree t t)
  7549. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7550. (point)))))))
  7551. (defun org-toggle-narrow-to-subtree ()
  7552. "Narrow to the subtree at point or widen a narrowed buffer."
  7553. (interactive)
  7554. (if (buffer-narrowed-p)
  7555. (widen)
  7556. (org-narrow-to-subtree)))
  7557. (defun org-narrow-to-block ()
  7558. "Narrow buffer to the current block."
  7559. (interactive)
  7560. (let* ((case-fold-search t)
  7561. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7562. "^[ \t]*#\\+end_.*")))
  7563. (if blockp
  7564. (narrow-to-region (car blockp) (cdr blockp))
  7565. (user-error "Not in a block"))))
  7566. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7567. "Clone the task (subtree) at point N times.
  7568. The clones will be inserted as siblings.
  7569. In interactive use, the user will be prompted for the number of
  7570. clones to be produced. If the entry has a timestamp, the user
  7571. will also be prompted for a time shift, which may be a repeater
  7572. as used in time stamps, for example `+3d'. To disable this,
  7573. you can call the function with a universal prefix argument.
  7574. When a valid repeater is given and the entry contains any time
  7575. stamps, the clones will become a sequence in time, with time
  7576. stamps in the subtree shifted for each clone produced. If SHIFT
  7577. is nil or the empty string, time stamps will be left alone. The
  7578. ID property of the original subtree is removed.
  7579. In each clone, all the CLOCK entries will be removed. This
  7580. prevents Org from considering that the clocked times overlap.
  7581. If the original subtree did contain time stamps with a repeater,
  7582. the following will happen:
  7583. - the repeater will be removed in each clone
  7584. - an additional clone will be produced, with the current, unshifted
  7585. date(s) in the entry.
  7586. - the original entry will be placed *after* all the clones, with
  7587. repeater intact.
  7588. - the start days in the repeater in the original entry will be shifted
  7589. to past the last clone.
  7590. In this way you can spell out a number of instances of a repeating task,
  7591. and still retain the repeater to cover future instances of the task.
  7592. As described above, N+1 clones are produced when the original
  7593. subtree has a repeater. Setting N to 0, then, can be used to
  7594. remove the repeater from a subtree and create a shifted clone
  7595. with the original repeater."
  7596. (interactive "nNumber of clones to produce: ")
  7597. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7598. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7599. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7600. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7601. (shift
  7602. (or shift
  7603. (if (and (not (equal current-prefix-arg '(4)))
  7604. (save-excursion
  7605. (goto-char beg)
  7606. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7607. (read-from-minibuffer
  7608. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7609. ""))) ;No time shift
  7610. (doshift
  7611. (and (org-string-nw-p shift)
  7612. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7613. shift)
  7614. (user-error "Invalid shift specification %s" shift)))))
  7615. (goto-char end-of-tree)
  7616. (unless (bolp) (insert "\n"))
  7617. (let* ((end (point))
  7618. (template (buffer-substring beg end))
  7619. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7620. (shift-what (pcase (and doshift (match-string 2 shift))
  7621. (`nil nil)
  7622. ("d" 'day)
  7623. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7624. ("m" 'month)
  7625. ("y" 'year)
  7626. (_ (error "Unsupported time unit"))))
  7627. (nmin 1)
  7628. (nmax n)
  7629. (n-no-remove -1)
  7630. (idprop (org-entry-get nil "ID")))
  7631. (when (and doshift
  7632. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7633. template))
  7634. (delete-region beg end)
  7635. (setq end beg)
  7636. (setq nmin 0)
  7637. (setq nmax (1+ nmax))
  7638. (setq n-no-remove nmax))
  7639. (goto-char end)
  7640. (cl-loop for n from nmin to nmax do
  7641. (insert
  7642. ;; Prepare clone.
  7643. (with-temp-buffer
  7644. (insert template)
  7645. (org-mode)
  7646. (goto-char (point-min))
  7647. (org-show-subtree)
  7648. (and idprop (if org-clone-delete-id
  7649. (org-entry-delete nil "ID")
  7650. (org-id-get-create t)))
  7651. (unless (= n 0)
  7652. (while (re-search-forward org-clock-line-re nil t)
  7653. (delete-region (line-beginning-position)
  7654. (line-beginning-position 2)))
  7655. (goto-char (point-min))
  7656. (while (re-search-forward org-drawer-regexp nil t)
  7657. (org-remove-empty-drawer-at (point))))
  7658. (goto-char (point-min))
  7659. (when doshift
  7660. (while (re-search-forward org-ts-regexp-both nil t)
  7661. (org-timestamp-change (* n shift-n) shift-what))
  7662. (unless (= n n-no-remove)
  7663. (goto-char (point-min))
  7664. (while (re-search-forward org-ts-regexp nil t)
  7665. (save-excursion
  7666. (goto-char (match-beginning 0))
  7667. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7668. (delete-region (match-beginning 1) (match-end 1)))))))
  7669. (buffer-string)))))
  7670. (goto-char beg)))
  7671. ;;; Outline Sorting
  7672. (defun org-sort (&optional with-case)
  7673. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7674. Optional argument WITH-CASE means sort case-sensitively."
  7675. (interactive "P")
  7676. (org-call-with-arg
  7677. (cond ((org-at-table-p) #'org-table-sort-lines)
  7678. ((org-at-item-p) #'org-sort-list)
  7679. (t #'org-sort-entries))
  7680. with-case))
  7681. (defun org-sort-remove-invisible (s)
  7682. "Remove invisible part of links and emphasis markers from string S."
  7683. (remove-text-properties 0 (length s) org-rm-props s)
  7684. (replace-regexp-in-string
  7685. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7686. (replace-regexp-in-string
  7687. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7688. (org-link-display-format s)
  7689. t t) t t))
  7690. (defvar org-priority-regexp) ; defined later in the file
  7691. (defvar org-after-sorting-entries-or-items-hook nil
  7692. "Hook that is run after a bunch of entries or items have been sorted.
  7693. When children are sorted, the cursor is in the parent line when this
  7694. hook gets called. When a region or a plain list is sorted, the cursor
  7695. will be in the first entry of the sorted region/list.")
  7696. (defun org-sort-entries
  7697. (&optional with-case sorting-type getkey-func compare-func property
  7698. interactive?)
  7699. "Sort entries on a certain level of an outline tree.
  7700. If there is an active region, the entries in the region are sorted.
  7701. Else, if the cursor is before the first entry, sort the top-level items.
  7702. Else, the children of the entry at point are sorted.
  7703. Sorting can be alphabetically, numerically, by date/time as given by
  7704. a time stamp, by a property, by priority order, or by a custom function.
  7705. The command prompts for the sorting type unless it has been given to the
  7706. function through the SORTING-TYPE argument, which needs to be a character,
  7707. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7708. the precise meaning of each character:
  7709. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7710. c By creation time, which is assumed to be the first inactive time stamp
  7711. at the beginning of a line.
  7712. d By deadline date/time.
  7713. k By clocking time.
  7714. n Numerically, by converting the beginning of the entry/item to a number.
  7715. o By order of TODO keywords.
  7716. p By priority according to the cookie.
  7717. r By the value of a property.
  7718. s By scheduled date/time.
  7719. t By date/time, either the first active time stamp in the entry, or, if
  7720. none exist, by the first inactive one.
  7721. Capital letters will reverse the sort order.
  7722. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7723. called with point at the beginning of the record. It must return a
  7724. value that is compatible with COMPARE-FUNC, the function used to
  7725. compare entries.
  7726. Comparing entries ignores case by default. However, with an optional argument
  7727. WITH-CASE, the sorting considers case as well.
  7728. Sorting is done against the visible part of the headlines, it ignores hidden
  7729. links.
  7730. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7731. A non-nil value for INTERACTIVE? is used to signal that this
  7732. function is being called interactively."
  7733. (interactive (list current-prefix-arg nil nil nil nil t))
  7734. (let ((case-func (if with-case 'identity 'downcase))
  7735. start beg end stars re re2
  7736. txt what tmp)
  7737. ;; Find beginning and end of region to sort
  7738. (cond
  7739. ((org-region-active-p)
  7740. ;; we will sort the region
  7741. (setq end (region-end)
  7742. what "region")
  7743. (goto-char (region-beginning))
  7744. (unless (org-at-heading-p) (outline-next-heading))
  7745. (setq start (point)))
  7746. ((or (org-at-heading-p)
  7747. (ignore-errors (progn (org-back-to-heading) t)))
  7748. ;; we will sort the children of the current headline
  7749. (org-back-to-heading)
  7750. (setq start (point)
  7751. end (progn (org-end-of-subtree t t)
  7752. (or (bolp) (insert "\n"))
  7753. (when (>= (org-back-over-empty-lines) 1)
  7754. (forward-line 1))
  7755. (point))
  7756. what "children")
  7757. (goto-char start)
  7758. (outline-show-subtree)
  7759. (outline-next-heading))
  7760. (t
  7761. ;; we will sort the top-level entries in this file
  7762. (goto-char (point-min))
  7763. (or (org-at-heading-p) (outline-next-heading))
  7764. (setq start (point))
  7765. (goto-char (point-max))
  7766. (beginning-of-line 1)
  7767. (when (looking-at ".*?\\S-")
  7768. ;; File ends in a non-white line
  7769. (end-of-line 1)
  7770. (insert "\n"))
  7771. (setq end (point-max))
  7772. (setq what "top-level")
  7773. (goto-char start)
  7774. (org-show-all '(headings blocks))))
  7775. (setq beg (point))
  7776. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7777. (looking-at "\\(\\*+\\)")
  7778. (setq stars (match-string 1)
  7779. re (concat "^" (regexp-quote stars) " +")
  7780. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7781. txt (buffer-substring beg end))
  7782. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7783. (when (and (not (equal stars "*")) (string-match re2 txt))
  7784. (user-error "Region to sort contains a level above the first entry"))
  7785. (unless sorting-type
  7786. (message
  7787. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7788. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7789. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7790. what)
  7791. (setq sorting-type (read-char-exclusive)))
  7792. (unless getkey-func
  7793. (and (= (downcase sorting-type) ?f)
  7794. (setq getkey-func
  7795. (or (and interactive?
  7796. (org-read-function
  7797. "Function for extracting keys: "))
  7798. (error "Missing key extractor")))))
  7799. (and (= (downcase sorting-type) ?r)
  7800. (not property)
  7801. (setq property
  7802. (completing-read "Property: "
  7803. (mapcar #'list (org-buffer-property-keys t))
  7804. nil t)))
  7805. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7806. (message "Sorting entries...")
  7807. (save-restriction
  7808. (narrow-to-region start end)
  7809. (let ((restore-clock?
  7810. ;; The clock marker is lost when using `sort-subr'; mark
  7811. ;; the clock with temporary `:org-clock-marker-backup'
  7812. ;; text property.
  7813. (when (and (eq (org-clock-is-active) (current-buffer))
  7814. (<= start (marker-position org-clock-marker))
  7815. (>= end (marker-position org-clock-marker)))
  7816. (with-silent-modifications
  7817. (put-text-property (1- org-clock-marker) org-clock-marker
  7818. :org-clock-marker-backup t))
  7819. t))
  7820. (dcst (downcase sorting-type))
  7821. (case-fold-search nil)
  7822. (now (current-time)))
  7823. (org-preserve-local-variables
  7824. (sort-subr
  7825. (/= dcst sorting-type)
  7826. ;; This function moves to the beginning character of the
  7827. ;; "record" to be sorted.
  7828. (lambda nil
  7829. (if (re-search-forward re nil t)
  7830. (goto-char (match-beginning 0))
  7831. (goto-char (point-max))))
  7832. ;; This function moves to the last character of the "record" being
  7833. ;; sorted.
  7834. (lambda nil
  7835. (save-match-data
  7836. (condition-case nil
  7837. (outline-forward-same-level 1)
  7838. (error
  7839. (goto-char (point-max))))))
  7840. ;; This function returns the value that gets sorted against.
  7841. (lambda ()
  7842. (cond
  7843. ((= dcst ?n)
  7844. (string-to-number
  7845. (org-sort-remove-invisible (org-get-heading t t t t))))
  7846. ((= dcst ?a)
  7847. (funcall case-func
  7848. (org-sort-remove-invisible (org-get-heading t t t t))))
  7849. ((= dcst ?k)
  7850. (or (get-text-property (point) :org-clock-minutes) 0))
  7851. ((= dcst ?t)
  7852. (let ((end (save-excursion (outline-next-heading) (point))))
  7853. (if (or (re-search-forward org-ts-regexp end t)
  7854. (re-search-forward org-ts-regexp-both end t))
  7855. (org-time-string-to-seconds (match-string 0))
  7856. (float-time now))))
  7857. ((= dcst ?c)
  7858. (let ((end (save-excursion (outline-next-heading) (point))))
  7859. (if (re-search-forward
  7860. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7861. end t)
  7862. (org-time-string-to-seconds (match-string 0))
  7863. (float-time now))))
  7864. ((= dcst ?s)
  7865. (let ((end (save-excursion (outline-next-heading) (point))))
  7866. (if (re-search-forward org-scheduled-time-regexp end t)
  7867. (org-time-string-to-seconds (match-string 1))
  7868. (float-time now))))
  7869. ((= dcst ?d)
  7870. (let ((end (save-excursion (outline-next-heading) (point))))
  7871. (if (re-search-forward org-deadline-time-regexp end t)
  7872. (org-time-string-to-seconds (match-string 1))
  7873. (float-time now))))
  7874. ((= dcst ?p)
  7875. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7876. (string-to-char (match-string 2))
  7877. org-default-priority))
  7878. ((= dcst ?r)
  7879. (or (org-entry-get nil property) ""))
  7880. ((= dcst ?o)
  7881. (when (looking-at org-complex-heading-regexp)
  7882. (let* ((m (match-string 2))
  7883. (s (if (member m org-done-keywords) '- '+)))
  7884. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7885. ((= dcst ?f)
  7886. (if getkey-func
  7887. (progn
  7888. (setq tmp (funcall getkey-func))
  7889. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7890. tmp)
  7891. (error "Invalid key function `%s'" getkey-func)))
  7892. (t (error "Invalid sorting type `%c'" sorting-type))))
  7893. nil
  7894. (cond
  7895. ((= dcst ?a) 'org-string-collate-lessp)
  7896. ((= dcst ?f)
  7897. (or compare-func
  7898. (and interactive?
  7899. (org-read-function
  7900. (concat "Function for comparing keys "
  7901. "(empty for default `sort-subr' predicate): ")
  7902. 'allow-empty))))
  7903. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7904. (when restore-clock?
  7905. (move-marker org-clock-marker
  7906. (1+ (next-single-property-change
  7907. start :org-clock-marker-backup)))
  7908. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7909. '(:org-clock-marker-backup t)))))
  7910. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7911. (message "Sorting entries...done")))
  7912. (defun org-contextualize-keys (alist contexts)
  7913. "Return valid elements in ALIST depending on CONTEXTS.
  7914. `org-agenda-custom-commands' or `org-capture-templates' are the
  7915. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7916. or `org-capture-templates-contexts' are the associated contexts
  7917. definitions."
  7918. (let ((contexts
  7919. ;; normalize contexts
  7920. (mapcar
  7921. (lambda(c) (cond ((listp (cadr c))
  7922. (list (car c) (car c) (nth 1 c)))
  7923. ((string= "" (cadr c))
  7924. (list (car c) (car c) (nth 2 c)))
  7925. (t c)))
  7926. contexts))
  7927. (a alist) r s)
  7928. ;; loop over all commands or templates
  7929. (dolist (c a)
  7930. (let (vrules repl)
  7931. (cond
  7932. ((not (assoc (car c) contexts))
  7933. (push c r))
  7934. ((and (assoc (car c) contexts)
  7935. (setq vrules (org-contextualize-validate-key
  7936. (car c) contexts)))
  7937. (mapc (lambda (vr)
  7938. (unless (equal (car vr) (cadr vr))
  7939. (setq repl vr)))
  7940. vrules)
  7941. (if (not repl) (push c r)
  7942. (push (cadr repl) s)
  7943. (push
  7944. (cons (car c)
  7945. (cdr (or (assoc (cadr repl) alist)
  7946. (error "Undefined key `%s' as contextual replacement for `%s'"
  7947. (cadr repl) (car c)))))
  7948. r))))))
  7949. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7950. (delq
  7951. nil
  7952. (delete-dups
  7953. (mapcar (lambda (x)
  7954. (let ((tpl (car x)))
  7955. (unless (delq
  7956. nil
  7957. (mapcar (lambda (y)
  7958. (equal y tpl))
  7959. s))
  7960. x)))
  7961. (reverse r))))))
  7962. (defun org-contextualize-validate-key (key contexts)
  7963. "Check CONTEXTS for agenda or capture KEY."
  7964. (let (res)
  7965. (dolist (r contexts)
  7966. (dolist (rr (car (last r)))
  7967. (when
  7968. (and (equal key (car r))
  7969. (if (functionp rr) (funcall rr)
  7970. (or (and (eq (car rr) 'in-file)
  7971. (buffer-file-name)
  7972. (string-match (cdr rr) (buffer-file-name)))
  7973. (and (eq (car rr) 'in-mode)
  7974. (string-match (cdr rr) (symbol-name major-mode)))
  7975. (and (eq (car rr) 'in-buffer)
  7976. (string-match (cdr rr) (buffer-name)))
  7977. (when (and (eq (car rr) 'not-in-file)
  7978. (buffer-file-name))
  7979. (not (string-match (cdr rr) (buffer-file-name))))
  7980. (when (eq (car rr) 'not-in-mode)
  7981. (not (string-match (cdr rr) (symbol-name major-mode))))
  7982. (when (eq (car rr) 'not-in-buffer)
  7983. (not (string-match (cdr rr) (buffer-name)))))))
  7984. (push r res))))
  7985. (delete-dups (delq nil res))))
  7986. ;; Defined to provide a value for defcustom, since there is no
  7987. ;; string-collate-greaterp in Emacs.
  7988. (defun org-string-collate-greaterp (s1 s2)
  7989. "Return non-nil if S1 is greater than S2 in collation order."
  7990. (not (org-string-collate-lessp s1 s2)))
  7991. ;;;###autoload
  7992. (defun org-run-like-in-org-mode (cmd)
  7993. "Run a command, pretending that the current buffer is in Org mode.
  7994. This will temporarily bind local variables that are typically bound in
  7995. Org mode to the values they have in Org mode, and then interactively
  7996. call CMD."
  7997. (org-load-modules-maybe)
  7998. (let (binds)
  7999. (dolist (var (org-get-local-variables))
  8000. (when (or (not (boundp (car var)))
  8001. (eq (symbol-value (car var))
  8002. (default-value (car var))))
  8003. (push (list (car var) `(quote ,(cadr var))) binds)))
  8004. (eval `(let ,binds
  8005. (call-interactively (quote ,cmd))))))
  8006. (defun org-get-category (&optional pos force-refresh)
  8007. "Get the category applying to position POS."
  8008. (save-match-data
  8009. (when force-refresh (org-refresh-category-properties))
  8010. (let ((pos (or pos (point))))
  8011. (or (get-text-property pos 'org-category)
  8012. (progn (org-refresh-category-properties)
  8013. (get-text-property pos 'org-category))))))
  8014. ;;; Refresh properties
  8015. (defun org-refresh-properties (dprop tprop)
  8016. "Refresh buffer text properties.
  8017. DPROP is the drawer property and TPROP is either the
  8018. corresponding text property to set, or an alist with each element
  8019. being a text property (as a symbol) and a function to apply to
  8020. the value of the drawer property."
  8021. (let* ((case-fold-search t)
  8022. (inhibit-read-only t)
  8023. (inherit? (org-property-inherit-p dprop))
  8024. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8025. (global (and inherit? (org--property-global-value dprop nil))))
  8026. (with-silent-modifications
  8027. (org-with-point-at 1
  8028. ;; Set global values (e.g., values defined through
  8029. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8030. (when global (put-text-property (point-min) (point-max) tprop global))
  8031. ;; Set local values.
  8032. (while (re-search-forward property-re nil t)
  8033. (when (org-at-property-p)
  8034. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8035. (outline-next-heading))))))
  8036. (defun org-refresh-property (tprop p &optional inherit)
  8037. "Refresh the buffer text property TPROP from the drawer property P.
  8038. The refresh happens only for the current headline, or the whole
  8039. sub-tree if optional argument INHERIT is non-nil."
  8040. (unless (org-before-first-heading-p)
  8041. (save-excursion
  8042. (org-back-to-heading t)
  8043. (let ((start (point))
  8044. (end (save-excursion
  8045. (if inherit (org-end-of-subtree t t)
  8046. (or (outline-next-heading) (point-max))))))
  8047. (if (symbolp tprop)
  8048. ;; TPROP is a text property symbol.
  8049. (put-text-property start end tprop p)
  8050. ;; TPROP is an alist with (property . function) elements.
  8051. (pcase-dolist (`(,prop . ,f) tprop)
  8052. (put-text-property start end prop (funcall f p))))))))
  8053. (defun org-refresh-category-properties ()
  8054. "Refresh category text properties in the buffer."
  8055. (let ((case-fold-search t)
  8056. (inhibit-read-only t)
  8057. (default-category
  8058. (cond ((null org-category)
  8059. (if buffer-file-name
  8060. (file-name-sans-extension
  8061. (file-name-nondirectory buffer-file-name))
  8062. "???"))
  8063. ((symbolp org-category) (symbol-name org-category))
  8064. (t org-category))))
  8065. (with-silent-modifications
  8066. (org-with-wide-buffer
  8067. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8068. ;; This is the default category for the buffer. If none is
  8069. ;; found, fall-back to `org-category' or buffer file name.
  8070. (put-text-property
  8071. (point-min) (point-max)
  8072. 'org-category
  8073. (catch 'buffer-category
  8074. (goto-char (point-max))
  8075. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8076. (let ((element (org-element-at-point)))
  8077. (when (eq (org-element-type element) 'keyword)
  8078. (throw 'buffer-category
  8079. (org-element-property :value element)))))
  8080. default-category))
  8081. ;; Set sub-tree specific categories.
  8082. (goto-char (point-min))
  8083. (let ((regexp (org-re-property "CATEGORY")))
  8084. (while (re-search-forward regexp nil t)
  8085. (let ((value (match-string-no-properties 3)))
  8086. (when (org-at-property-p)
  8087. (put-text-property
  8088. (save-excursion (org-back-to-heading t) (point))
  8089. (save-excursion (org-end-of-subtree t t) (point))
  8090. 'org-category
  8091. value)))))))))
  8092. (defun org-refresh-stats-properties ()
  8093. "Refresh stats text properties in the buffer."
  8094. (with-silent-modifications
  8095. (org-with-point-at 1
  8096. (let ((regexp (concat org-outline-regexp-bol
  8097. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8098. (while (re-search-forward regexp nil t)
  8099. (let* ((numerator (string-to-number (match-string 1)))
  8100. (denominator (and (match-end 2)
  8101. (string-to-number (match-string 2))))
  8102. (stats (cond ((not denominator) numerator) ;percent
  8103. ((= denominator 0) 0)
  8104. (t (/ (* numerator 100) denominator)))))
  8105. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8106. 'org-stats stats)))))))
  8107. (defun org-refresh-effort-properties ()
  8108. "Refresh effort properties"
  8109. (org-refresh-properties
  8110. org-effort-property
  8111. '((effort . identity)
  8112. (effort-minutes . org-duration-to-minutes))))
  8113. ;;;; Link Stuff
  8114. ;;; Link abbreviations
  8115. (defun org-link-expand-abbrev (link)
  8116. "Apply replacements as defined in `org-link-abbrev-alist'."
  8117. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8118. (let* ((key (match-string 1 link))
  8119. (as (or (assoc key org-link-abbrev-alist-local)
  8120. (assoc key org-link-abbrev-alist)))
  8121. (tag (and (match-end 2) (match-string 3 link)))
  8122. rpl)
  8123. (if (not as)
  8124. link
  8125. (setq rpl (cdr as))
  8126. (cond
  8127. ((symbolp rpl) (funcall rpl tag))
  8128. ((string-match "%(\\([^)]+\\))" rpl)
  8129. (replace-match
  8130. (save-match-data
  8131. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8132. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8133. ((string-match "%h" rpl)
  8134. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8135. (t (concat rpl tag)))))
  8136. link))
  8137. ;;; Storing and inserting links
  8138. (defvar org-insert-link-history nil
  8139. "Minibuffer history for links inserted with `org-insert-link'.")
  8140. (defvar org-stored-links nil
  8141. "Contains the links stored with `org-store-link'.")
  8142. (defvar org-store-link-plist nil
  8143. "Plist with info about the most recently link created with `org-store-link'.")
  8144. (defun org-store-link-functions ()
  8145. "Return a list of functions that are called to create and store a link.
  8146. The functions defined in the :store property of
  8147. `org-link-parameters'.
  8148. Each function will be called in turn until one returns a non-nil
  8149. value. Each function should check if it is responsible for
  8150. creating this link (for example by looking at the major mode).
  8151. If not, it must exit and return nil. If yes, it should return
  8152. a non-nil value after calling `org-store-link-props' with a list
  8153. of properties and values. Special properties are:
  8154. :type The link prefix, like \"http\". This must be given.
  8155. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8156. This is obligatory as well.
  8157. :description Optional default description for the second pair
  8158. of brackets in an Org mode link. The user can still change
  8159. this when inserting this link into an Org mode buffer.
  8160. In addition to these, any additional properties can be specified
  8161. and then used in capture templates."
  8162. (cl-loop for link in org-link-parameters
  8163. with store-func
  8164. do (setq store-func (org-link-get-parameter (car link) :store))
  8165. if store-func
  8166. collect store-func))
  8167. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8168. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8169. ;;;###autoload
  8170. (defun org-store-link (arg &optional interactive?)
  8171. "Store a link to the current location.
  8172. \\<org-mode-map>
  8173. This link is added to `org-stored-links' and can later be inserted
  8174. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8175. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8176. A single
  8177. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8178. `org-gnus-prefer-web-links' for links to Usenet articles.
  8179. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8180. skipping storing functions that are not
  8181. part of Org core.
  8182. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8183. prefix ARG forces storing a link for each line in the
  8184. active region.
  8185. Assume the function is called interactively if INTERACTIVE? is
  8186. non-nil."
  8187. (interactive "P\np")
  8188. (org-load-modules-maybe)
  8189. (if (and (equal arg '(64)) (org-region-active-p))
  8190. (save-excursion
  8191. (let ((end (region-end)))
  8192. (goto-char (region-beginning))
  8193. (set-mark (point))
  8194. (while (< (point-at-eol) end)
  8195. (move-end-of-line 1) (activate-mark)
  8196. (let (current-prefix-arg)
  8197. (call-interactively 'org-store-link))
  8198. (move-beginning-of-line 2)
  8199. (set-mark (point)))))
  8200. (setq org-store-link-plist nil)
  8201. (let (link cpltxt desc description search txt custom-id agenda-link)
  8202. (cond
  8203. ;; Store a link using an external link type, if any function is
  8204. ;; available. If more than one can generate a link from current
  8205. ;; location, ask which one to use.
  8206. ((and (not (equal arg '(16)))
  8207. (let ((results-alist nil))
  8208. (dolist (f (org-store-link-functions))
  8209. (when (funcall f)
  8210. ;; XXX: return value is not link's plist, so we
  8211. ;; store the new value before it is modified. It
  8212. ;; would be cleaner to ask store link functions to
  8213. ;; return the plist instead.
  8214. (push (cons f (copy-sequence org-store-link-plist))
  8215. results-alist)))
  8216. (pcase results-alist
  8217. (`nil nil)
  8218. (`((,_ . ,_)) t) ;single choice: nothing to do
  8219. (`((,name . ,_) . ,_)
  8220. ;; Reinstate link plist associated to the chosen
  8221. ;; function.
  8222. (apply #'org-store-link-props
  8223. (cdr (assoc-string
  8224. (completing-read
  8225. "Which function for creating the link? "
  8226. (mapcar #'car results-alist)
  8227. nil t (symbol-name name))
  8228. results-alist)))
  8229. t))))
  8230. (setq link (plist-get org-store-link-plist :link))
  8231. (setq desc (or (plist-get org-store-link-plist :description)
  8232. link)))
  8233. ;; Store a link from a remote editing buffer.
  8234. ((org-src-edit-buffer-p)
  8235. (let ((coderef-format (org-src-coderef-format))
  8236. (format-link
  8237. (lambda (label)
  8238. (if org-src-source-file-name
  8239. (format "file:%s::(%s)" org-src-source-file-name label)
  8240. (format "(%s)" label)))))
  8241. (cond
  8242. ;; Code references do not exist in this type of buffer.
  8243. ;; Pretend we're linking from the source buffer directly.
  8244. ((not (memq (org-src-source-type) '(example-block src-block)))
  8245. (with-current-buffer (org-src-source-buffer)
  8246. (org-store-link arg interactive?))
  8247. (setq link nil))
  8248. ;; A code reference exists. Use it.
  8249. ((save-excursion
  8250. (beginning-of-line)
  8251. (re-search-forward (org-src-coderef-regexp coderef-format)
  8252. (line-end-position)
  8253. t))
  8254. (setq link (funcall format-link (match-string-no-properties 3))))
  8255. ;; No code reference. Create a new one then store the link
  8256. ;; to it, but only in the function is called interactively.
  8257. (interactive?
  8258. (end-of-line)
  8259. (let* ((label (read-string "Code line label: "))
  8260. (reference (format coderef-format label))
  8261. (gc (- 79 (length reference))))
  8262. (if (< (current-column) gc)
  8263. (org-move-to-column gc t)
  8264. (insert " "))
  8265. (insert reference)
  8266. (setq link (funcall format-link label))))
  8267. ;; No code reference, and non-interactive call. Don't know
  8268. ;; what to do. Give up.
  8269. (t (setq link nil)))))
  8270. ;; We are in the agenda, link to referenced location
  8271. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8272. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8273. (get-text-property (point) 'org-marker))))
  8274. (when m
  8275. (org-with-point-at m
  8276. (setq agenda-link (org-store-link nil interactive?))))))
  8277. ((eq major-mode 'calendar-mode)
  8278. (let ((cd (calendar-cursor-to-date)))
  8279. (setq link
  8280. (format-time-string
  8281. (car org-time-stamp-formats)
  8282. (apply 'encode-time
  8283. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8284. nil nil nil))))
  8285. (org-store-link-props :type "calendar" :date cd)))
  8286. ((eq major-mode 'help-mode)
  8287. (setq link (concat "help:" (save-excursion
  8288. (goto-char (point-min))
  8289. (looking-at "^[^ ]+")
  8290. (match-string 0))))
  8291. (org-store-link-props :type "help"))
  8292. ((eq major-mode 'w3-mode)
  8293. (setq cpltxt (if (and (buffer-name)
  8294. (not (string-match "Untitled" (buffer-name))))
  8295. (buffer-name)
  8296. (url-view-url t))
  8297. link (url-view-url t))
  8298. (org-store-link-props :type "w3" :url (url-view-url t)))
  8299. ((eq major-mode 'image-mode)
  8300. (setq cpltxt (concat "file:"
  8301. (abbreviate-file-name buffer-file-name))
  8302. link cpltxt)
  8303. (org-store-link-props :type "image" :file buffer-file-name))
  8304. ;; In dired, store a link to the file of the current line
  8305. ((derived-mode-p 'dired-mode)
  8306. (let ((file (dired-get-filename nil t)))
  8307. (setq file (if file
  8308. (abbreviate-file-name
  8309. (expand-file-name (dired-get-filename nil t)))
  8310. ;; otherwise, no file so use current directory.
  8311. default-directory))
  8312. (setq cpltxt (concat "file:" file)
  8313. link cpltxt)))
  8314. ((setq search (run-hook-with-args-until-success
  8315. 'org-create-file-search-functions))
  8316. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8317. "::" search))
  8318. (setq cpltxt (or description link)))
  8319. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8320. (org-with-limited-levels
  8321. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8322. (cond
  8323. ;; Store a link using the target at point
  8324. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8325. (setq cpltxt
  8326. (concat "file:"
  8327. (abbreviate-file-name
  8328. (buffer-file-name (buffer-base-buffer)))
  8329. "::" (match-string 1))
  8330. link cpltxt))
  8331. ((and (featurep 'org-id)
  8332. (or (eq org-id-link-to-org-use-id t)
  8333. (and interactive?
  8334. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8335. (and (eq org-id-link-to-org-use-id
  8336. 'create-if-interactive-and-no-custom-id)
  8337. (not custom-id))))
  8338. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8339. ;; Store a link using the ID at point
  8340. (setq link (condition-case nil
  8341. (prog1 (org-id-store-link)
  8342. (setq desc (or (plist-get org-store-link-plist
  8343. :description)
  8344. "")))
  8345. (error
  8346. ;; Probably before first headline, link only to file
  8347. (concat "file:"
  8348. (abbreviate-file-name
  8349. (buffer-file-name (buffer-base-buffer))))))))
  8350. (t
  8351. ;; Just link to current headline
  8352. (setq cpltxt (concat "file:"
  8353. (abbreviate-file-name
  8354. (buffer-file-name (buffer-base-buffer)))))
  8355. ;; Add a context search string
  8356. (when (org-xor org-context-in-file-links
  8357. (equal arg '(4)))
  8358. (let* ((element (org-element-at-point))
  8359. (name (org-element-property :name element)))
  8360. (setq txt (cond
  8361. ((org-at-heading-p) nil)
  8362. (name)
  8363. ((org-region-active-p)
  8364. (buffer-substring (region-beginning) (region-end)))))
  8365. (when (or (null txt) (string-match "\\S-" txt))
  8366. (setq cpltxt
  8367. (concat cpltxt "::"
  8368. (condition-case nil
  8369. (org-make-org-heading-search-string txt)
  8370. (error "")))
  8371. desc (or name
  8372. (nth 4 (ignore-errors (org-heading-components)))
  8373. "NONE")))))
  8374. (when (string-match "::\\'" cpltxt)
  8375. (setq cpltxt (substring cpltxt 0 -2)))
  8376. (setq link cpltxt)))))
  8377. ((buffer-file-name (buffer-base-buffer))
  8378. ;; Just link to this file here.
  8379. (setq cpltxt (concat "file:"
  8380. (abbreviate-file-name
  8381. (buffer-file-name (buffer-base-buffer)))))
  8382. ;; Add a context string.
  8383. (when (org-xor org-context-in-file-links
  8384. (equal arg '(4)))
  8385. (setq txt (if (org-region-active-p)
  8386. (buffer-substring (region-beginning) (region-end))
  8387. (buffer-substring (point-at-bol) (point-at-eol))))
  8388. ;; Only use search option if there is some text.
  8389. (when (string-match "\\S-" txt)
  8390. (setq cpltxt
  8391. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8392. desc "NONE")))
  8393. (setq link cpltxt))
  8394. (interactive?
  8395. (user-error "No method for storing a link from this buffer"))
  8396. (t (setq link nil)))
  8397. ;; We're done setting link and desc, clean up
  8398. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8399. (setq link (or link cpltxt)
  8400. desc (or desc cpltxt))
  8401. (cond ((not desc))
  8402. ((equal desc "NONE") (setq desc nil))
  8403. (t (setq desc
  8404. (replace-regexp-in-string
  8405. org-bracket-link-analytic-regexp
  8406. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8407. desc))))
  8408. ;; Return the link
  8409. (if (not (and interactive? link))
  8410. (or agenda-link (and link (org-make-link-string link desc)))
  8411. (push (list link desc) org-stored-links)
  8412. (message "Stored: %s" (or desc link))
  8413. (when custom-id
  8414. (setq link (concat "file:" (abbreviate-file-name
  8415. (buffer-file-name)) "::#" custom-id))
  8416. (push (list link desc) org-stored-links))
  8417. (car org-stored-links)))))
  8418. (defun org-store-link-props (&rest plist)
  8419. "Store link properties.
  8420. The properties are pre-processed by extracting names, addresses
  8421. and dates."
  8422. (let ((x (plist-get plist :from)))
  8423. (when x
  8424. (let ((adr (mail-extract-address-components x)))
  8425. (setq plist (plist-put plist :fromname (car adr)))
  8426. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8427. (let ((x (plist-get plist :to)))
  8428. (when x
  8429. (let ((adr (mail-extract-address-components x)))
  8430. (setq plist (plist-put plist :toname (car adr)))
  8431. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8432. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8433. (when x
  8434. (setq plist (plist-put plist :date-timestamp
  8435. (format-time-string
  8436. (org-time-stamp-format t) x)))
  8437. (setq plist (plist-put plist :date-timestamp-inactive
  8438. (format-time-string
  8439. (org-time-stamp-format t t) x)))))
  8440. (let ((from (plist-get plist :from))
  8441. (to (plist-get plist :to)))
  8442. (when (and from to org-from-is-user-regexp)
  8443. (setq plist
  8444. (plist-put plist :fromto
  8445. (if (string-match org-from-is-user-regexp from)
  8446. (concat "to %t")
  8447. (concat "from %f"))))))
  8448. (setq org-store-link-plist plist))
  8449. (defun org-add-link-props (&rest plist)
  8450. "Add these properties to the link property list."
  8451. (let (key value)
  8452. (while plist
  8453. (setq key (pop plist) value (pop plist))
  8454. (setq org-store-link-plist
  8455. (plist-put org-store-link-plist key value)))))
  8456. (defun org-email-link-description (&optional fmt)
  8457. "Return the description part of an email link.
  8458. This takes information from `org-store-link-plist' and formats it
  8459. according to FMT (default from `org-email-link-description-format')."
  8460. (setq fmt (or fmt org-email-link-description-format))
  8461. (let* ((p org-store-link-plist)
  8462. (to (plist-get p :toaddress))
  8463. (from (plist-get p :fromaddress))
  8464. (table
  8465. (list
  8466. (cons "%c" (plist-get p :fromto))
  8467. (cons "%F" (plist-get p :from))
  8468. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8469. (cons "%T" (plist-get p :to))
  8470. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8471. (cons "%s" (plist-get p :subject))
  8472. (cons "%d" (plist-get p :date))
  8473. (cons "%m" (plist-get p :message-id)))))
  8474. (when (string-match "%c" fmt)
  8475. ;; Check if the user wrote this message
  8476. (if (and org-from-is-user-regexp from to
  8477. (save-match-data (string-match org-from-is-user-regexp from)))
  8478. (setq fmt (replace-match "to %t" t t fmt))
  8479. (setq fmt (replace-match "from %f" t t fmt))))
  8480. (org-replace-escapes fmt table)))
  8481. (defun org-make-org-heading-search-string (&optional string)
  8482. "Make search string for the current headline or STRING."
  8483. (let ((s (or string
  8484. (and (derived-mode-p 'org-mode)
  8485. (save-excursion
  8486. (org-back-to-heading t)
  8487. (org-element-property :raw-value (org-element-at-point))))))
  8488. (lines org-context-in-file-links))
  8489. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8490. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8491. (when (and string (integerp lines) (> lines 0))
  8492. (let ((slines (org-split-string s "\n")))
  8493. (when (< lines (length slines))
  8494. (setq s (mapconcat
  8495. 'identity
  8496. (reverse (nthcdr (- (length slines) lines)
  8497. (reverse slines))) "\n")))))
  8498. (mapconcat #'identity (split-string s) " ")))
  8499. (defconst org-link-escape-chars
  8500. ;;%20 %5B %5D %25
  8501. '(?\s ?\[ ?\] ?%)
  8502. "List of characters that should be escaped in a link when stored to Org.
  8503. This is the list that is used for internal purposes.")
  8504. (defun org-make-link-string (link &optional description)
  8505. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8506. (unless (org-string-nw-p link) (error "Empty link"))
  8507. (let ((uri (cond ((string-match org-link-types-re link)
  8508. (concat (match-string 1 link)
  8509. (org-link-escape (substring link (match-end 1)))))
  8510. ((or (file-name-absolute-p link)
  8511. (string-match-p "\\`\\.\\.?/" link))
  8512. (org-link-escape link))
  8513. ;; For readability, do not encode space characters
  8514. ;; in fuzzy links.
  8515. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8516. (description
  8517. (and (org-string-nw-p description)
  8518. ;; Remove brackets from description, as they are fatal.
  8519. (replace-regexp-in-string
  8520. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8521. (org-trim description)))))
  8522. (format "[[%s]%s]"
  8523. uri
  8524. (if description (format "[%s]" description) ""))))
  8525. (defun org-link-escape (text &optional table merge)
  8526. "Return percent escaped representation of TEXT.
  8527. TEXT is a string with the text to escape.
  8528. Optional argument TABLE is a list with characters that should be
  8529. escaped. When nil, `org-link-escape-chars' is used.
  8530. If optional argument MERGE is set, merge TABLE into
  8531. `org-link-escape-chars'."
  8532. (let ((characters-to-encode
  8533. (cond ((null table) org-link-escape-chars)
  8534. (merge (append org-link-escape-chars table))
  8535. (t table))))
  8536. (mapconcat
  8537. (lambda (c)
  8538. (if (or (memq c characters-to-encode)
  8539. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8540. (mapconcat (lambda (e) (format "%%%.2X" e))
  8541. (or (encode-coding-char c 'utf-8)
  8542. (error "Unable to percent escape character: %c" c))
  8543. "")
  8544. (char-to-string c)))
  8545. text "")))
  8546. (defun org-link-unescape (str)
  8547. "Unhex hexified Unicode parts in string STR.
  8548. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8549. reciprocal of `org-link-escape', which see."
  8550. (if (org-string-nw-p str)
  8551. (replace-regexp-in-string
  8552. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8553. str))
  8554. (defun org-link-unescape-compound (hex)
  8555. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8556. Note: this function also decodes single byte encodings like
  8557. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8558. (save-match-data
  8559. (let* ((bytes (cdr (split-string hex "%")))
  8560. (ret "")
  8561. (eat 0)
  8562. (sum 0))
  8563. (while bytes
  8564. (let* ((val (string-to-number (pop bytes) 16))
  8565. (shift-xor
  8566. (if (= 0 eat)
  8567. (cond
  8568. ((>= val 252) (cons 6 252))
  8569. ((>= val 248) (cons 5 248))
  8570. ((>= val 240) (cons 4 240))
  8571. ((>= val 224) (cons 3 224))
  8572. ((>= val 192) (cons 2 192))
  8573. (t (cons 0 0)))
  8574. (cons 6 128))))
  8575. (when (>= val 192) (setq eat (car shift-xor)))
  8576. (setq val (logxor val (cdr shift-xor)))
  8577. (setq sum (+ (lsh sum (car shift-xor)) val))
  8578. (when (> eat 0) (setq eat (- eat 1)))
  8579. (cond
  8580. ((= 0 eat) ;multi byte
  8581. (setq ret (concat ret (char-to-string sum)))
  8582. (setq sum 0))
  8583. ((not bytes) ; single byte(s)
  8584. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8585. ret)))
  8586. (defun org-link-unescape-single-byte-sequence (hex)
  8587. "Unhexify hex-encoded single byte character sequences."
  8588. (mapconcat (lambda (byte)
  8589. (char-to-string (string-to-number byte 16)))
  8590. (cdr (split-string hex "%")) ""))
  8591. (defun org-fixup-message-id-for-http (s)
  8592. "Replace special characters in a message id, so it can be used in an http query."
  8593. (when (string-match "%" s)
  8594. (setq s (mapconcat (lambda (c)
  8595. (if (eq c ?%)
  8596. "%25"
  8597. (char-to-string c)))
  8598. s "")))
  8599. (while (string-match "<" s)
  8600. (setq s (replace-match "%3C" t t s)))
  8601. (while (string-match ">" s)
  8602. (setq s (replace-match "%3E" t t s)))
  8603. (while (string-match "@" s)
  8604. (setq s (replace-match "%40" t t s)))
  8605. s)
  8606. (defun org-link-prettify (link)
  8607. "Return a human-readable representation of LINK.
  8608. The car of LINK must be a raw link.
  8609. The cdr of LINK must be either a link description or nil."
  8610. (let ((desc (or (cadr link) "<no description>")))
  8611. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8612. "<" (car link) ">")))
  8613. ;;;###autoload
  8614. (defun org-insert-link-global ()
  8615. "Insert a link like Org mode does.
  8616. This command can be called in any mode to insert a link in Org syntax."
  8617. (interactive)
  8618. (org-load-modules-maybe)
  8619. (org-run-like-in-org-mode 'org-insert-link))
  8620. (defun org-insert-all-links (arg &optional pre post)
  8621. "Insert all links in `org-stored-links'.
  8622. When a universal prefix, do not delete the links from `org-stored-links'.
  8623. When `ARG' is a number, insert the last N link(s).
  8624. `PRE' and `POST' are optional arguments to define a string to
  8625. prepend or to append."
  8626. (interactive "P")
  8627. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8628. (links (copy-sequence org-stored-links))
  8629. (pr (or pre "- "))
  8630. (po (or post "\n"))
  8631. (cnt 1) l)
  8632. (if (null org-stored-links)
  8633. (message "No link to insert")
  8634. (while (and (or (listp arg) (>= arg cnt))
  8635. (setq l (if (listp arg)
  8636. (pop links)
  8637. (pop org-stored-links))))
  8638. (setq cnt (1+ cnt))
  8639. (insert pr)
  8640. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8641. (insert po)))))
  8642. (defun org-insert-last-stored-link (arg)
  8643. "Insert the last link stored in `org-stored-links'."
  8644. (interactive "p")
  8645. (org-insert-all-links arg "" "\n"))
  8646. (defun org-link-fontify-links-to-this-file ()
  8647. "Fontify links to the current file in `org-stored-links'."
  8648. (let ((f (buffer-file-name)) a b)
  8649. (setq a (mapcar (lambda(l)
  8650. (let ((ll (car l)))
  8651. (when (and (string-match "^file:\\(.+\\)::" ll)
  8652. (equal f (expand-file-name (match-string 1 ll))))
  8653. ll)))
  8654. org-stored-links))
  8655. (when (featurep 'org-id)
  8656. (setq b (mapcar (lambda(l)
  8657. (let ((ll (car l)))
  8658. (when (and (string-match "^id:\\(.+\\)$" ll)
  8659. (equal f (expand-file-name
  8660. (or (org-id-find-id-file
  8661. (match-string 1 ll)) ""))))
  8662. ll)))
  8663. org-stored-links)))
  8664. (mapcar (lambda(l)
  8665. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8666. (delq nil (append a b)))))
  8667. (defvar org--links-history nil)
  8668. (defun org-insert-link (&optional complete-file link-location default-description)
  8669. "Insert a link. At the prompt, enter the link.
  8670. Completion can be used to insert any of the link protocol prefixes in use.
  8671. The history can be used to select a link previously stored with
  8672. `org-store-link'. When the empty string is entered (i.e. if you just
  8673. press `RET' at the prompt), the link defaults to the most recently
  8674. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8675. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8676. You will also be prompted for a description, and if one is given, it will
  8677. be displayed in the buffer instead of the link.
  8678. If there is already a link at point, this command will allow you to edit
  8679. link and description parts.
  8680. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8681. file name can be
  8682. selected using completion. The path to the file will be relative to the
  8683. current directory if the file is in the current directory or a subdirectory.
  8684. Otherwise, the link will be the absolute path as completed in the minibuffer
  8685. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8686. option `org-link-file-path-type'.
  8687. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8688. absolute path even if the file is in
  8689. the current directory or below.
  8690. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8691. prefix negates `org-keep-stored-link-after-insertion'.
  8692. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8693. the link location instead of reading one interactively.
  8694. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8695. be used as the default description. Otherwise, if
  8696. `org-make-link-description-function' is non-nil, this function
  8697. will be called with the link target, and the result will be the
  8698. default link description. When called non-interactivily, don't
  8699. allow to edit the default description."
  8700. (interactive "P")
  8701. (let* ((wcf (current-window-configuration))
  8702. (origbuf (current-buffer))
  8703. (region (when (org-region-active-p)
  8704. (buffer-substring (region-beginning) (region-end))))
  8705. (remove (and region (list (region-beginning) (region-end))))
  8706. (desc region)
  8707. (link link-location)
  8708. (abbrevs org-link-abbrev-alist-local)
  8709. entry all-prefixes auto-desc)
  8710. (cond
  8711. (link-location) ; specified by arg, just use it.
  8712. ((org-in-regexp org-bracket-link-regexp 1)
  8713. ;; We do have a link at point, and we are going to edit it.
  8714. (setq remove (list (match-beginning 0) (match-end 0)))
  8715. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8716. (setq link (read-string "Link: "
  8717. (org-link-unescape
  8718. (match-string-no-properties 1)))))
  8719. ((or (org-in-regexp org-angle-link-re)
  8720. (org-in-regexp org-plain-link-re))
  8721. ;; Convert to bracket link
  8722. (setq remove (list (match-beginning 0) (match-end 0))
  8723. link (read-string "Link: "
  8724. (org-unbracket-string "<" ">" (match-string 0)))))
  8725. ((member complete-file '((4) (16)))
  8726. ;; Completing read for file names.
  8727. (setq link (org-file-complete-link complete-file)))
  8728. (t
  8729. ;; Read link, with completion for stored links.
  8730. (org-link-fontify-links-to-this-file)
  8731. (org-switch-to-buffer-other-window "*Org Links*")
  8732. (with-current-buffer "*Org Links*"
  8733. (erase-buffer)
  8734. (insert "Insert a link.
  8735. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8736. (when org-stored-links
  8737. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8738. (insert (mapconcat 'org-link-prettify
  8739. (reverse org-stored-links) "\n")))
  8740. (goto-char (point-min)))
  8741. (let ((cw (selected-window)))
  8742. (select-window (get-buffer-window "*Org Links*" 'visible))
  8743. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8744. (unless (pos-visible-in-window-p (point-max))
  8745. (org-fit-window-to-buffer))
  8746. (and (window-live-p cw) (select-window cw)))
  8747. (setq all-prefixes (append (mapcar 'car abbrevs)
  8748. (mapcar 'car org-link-abbrev-alist)
  8749. (org-link-types)))
  8750. (unwind-protect
  8751. ;; Fake a link history, containing the stored links.
  8752. (let ((org--links-history
  8753. (append (mapcar #'car org-stored-links)
  8754. org-insert-link-history)))
  8755. (setq link
  8756. (org-completing-read
  8757. "Link: "
  8758. (append
  8759. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8760. (mapcar #'car org-stored-links))
  8761. nil nil nil
  8762. 'org--links-history
  8763. (caar org-stored-links)))
  8764. (unless (org-string-nw-p link) (user-error "No link selected"))
  8765. (dolist (l org-stored-links)
  8766. (when (equal link (cadr l))
  8767. (setq link (car l))
  8768. (setq auto-desc t)))
  8769. (when (or (member link all-prefixes)
  8770. (and (equal ":" (substring link -1))
  8771. (member (substring link 0 -1) all-prefixes)
  8772. (setq link (substring link 0 -1))))
  8773. (setq link (with-current-buffer origbuf
  8774. (org-link-try-special-completion link)))))
  8775. (set-window-configuration wcf)
  8776. (kill-buffer "*Org Links*"))
  8777. (setq entry (assoc link org-stored-links))
  8778. (or entry (push link org-insert-link-history))
  8779. (setq desc (or desc (nth 1 entry)))))
  8780. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8781. (not org-keep-stored-link-after-insertion))
  8782. (setq org-stored-links (delq (assoc link org-stored-links)
  8783. org-stored-links)))
  8784. (when (and (string-match org-plain-link-re link)
  8785. (not (string-match org-ts-regexp link)))
  8786. ;; URL-like link, normalize the use of angular brackets.
  8787. (setq link (org-unbracket-string "<" ">" link)))
  8788. ;; Check if we are linking to the current file with a search
  8789. ;; option If yes, simplify the link by using only the search
  8790. ;; option.
  8791. (when (and buffer-file-name
  8792. (let ((case-fold-search nil))
  8793. (string-match "\\`file:\\(.+?\\)::" link)))
  8794. (let ((path (match-string-no-properties 1 link))
  8795. (search (substring-no-properties link (match-end 0))))
  8796. (save-match-data
  8797. (when (equal (file-truename buffer-file-name) (file-truename path))
  8798. ;; We are linking to this same file, with a search option
  8799. (setq link search)))))
  8800. ;; Check if we can/should use a relative path. If yes, simplify
  8801. ;; the link.
  8802. (let ((case-fold-search nil))
  8803. (when (string-match "\\`\\(file\\|docview\\):" link)
  8804. (let* ((type (match-string-no-properties 0 link))
  8805. (path-start (match-end 0))
  8806. (search (and (string-match "::\\(.*\\)\\'" link)
  8807. (match-string 1 link)))
  8808. (path
  8809. (if search
  8810. (substring-no-properties
  8811. link path-start (match-beginning 0))
  8812. (substring-no-properties link (match-end 0))))
  8813. (origpath path))
  8814. (cond
  8815. ((or (eq org-link-file-path-type 'absolute)
  8816. (equal complete-file '(16)))
  8817. (setq path (abbreviate-file-name (expand-file-name path))))
  8818. ((eq org-link-file-path-type 'noabbrev)
  8819. (setq path (expand-file-name path)))
  8820. ((eq org-link-file-path-type 'relative)
  8821. (setq path (file-relative-name path)))
  8822. (t
  8823. (save-match-data
  8824. (if (string-match (concat "^" (regexp-quote
  8825. (expand-file-name
  8826. (file-name-as-directory
  8827. default-directory))))
  8828. (expand-file-name path))
  8829. ;; We are linking a file with relative path name.
  8830. (setq path (substring (expand-file-name path)
  8831. (match-end 0)))
  8832. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8833. (setq link (concat type path (and search (concat "::" search))))
  8834. (when (equal desc origpath)
  8835. (setq desc path)))))
  8836. (unless auto-desc
  8837. (let ((initial-input
  8838. (cond
  8839. (default-description)
  8840. ((not org-make-link-description-function) desc)
  8841. (t (condition-case nil
  8842. (funcall org-make-link-description-function link desc)
  8843. (error
  8844. (message "Can't get link description from `%s'"
  8845. (symbol-name org-make-link-description-function))
  8846. (sit-for 2)
  8847. nil))))))
  8848. (setq desc (if (called-interactively-p 'any)
  8849. (read-string "Description: " initial-input)
  8850. initial-input))))
  8851. (unless (string-match "\\S-" desc) (setq desc nil))
  8852. (when remove (apply 'delete-region remove))
  8853. (insert (org-make-link-string link desc))
  8854. ;; Redisplay so as the new link has proper invisible characters.
  8855. (sit-for 0)))
  8856. (defun org-link-try-special-completion (type)
  8857. "If there is completion support for link type TYPE, offer it."
  8858. (let ((fun (org-link-get-parameter type :complete)))
  8859. (if (functionp fun)
  8860. (funcall fun)
  8861. (read-string "Link (no completion support): " (concat type ":")))))
  8862. (defun org-file-complete-link (&optional arg)
  8863. "Create a file link using completion."
  8864. (let ((file (read-file-name "File: "))
  8865. (pwd (file-name-as-directory (expand-file-name ".")))
  8866. (pwd1 (file-name-as-directory (abbreviate-file-name
  8867. (expand-file-name ".")))))
  8868. (cond ((equal arg '(16))
  8869. (concat "file:"
  8870. (abbreviate-file-name (expand-file-name file))))
  8871. ((string-match
  8872. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8873. (concat "file:" (match-string 1 file)))
  8874. ((string-match
  8875. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8876. (expand-file-name file))
  8877. (concat "file:"
  8878. (match-string 1 (expand-file-name file))))
  8879. (t (concat "file:" file)))))
  8880. ;;; Opening/following a link
  8881. (defvar org-link-search-failed nil)
  8882. (defvar org-open-link-functions nil
  8883. "Hook for functions finding a plain text link.
  8884. These functions must take a single argument, the link content.
  8885. They will be called for links that look like [[link text][description]]
  8886. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8887. like a filename (e.g. \"./blue.png\").
  8888. These functions will be called *before* Org attempts to resolve the
  8889. link by doing text searches in the current buffer - so if you want a
  8890. link \"[[target]]\" to still find \"<<target>>\", your function should
  8891. handle this as a special case.
  8892. When the function does handle the link, it must return a non-nil value.
  8893. If it decides that it is not responsible for this link, it must return
  8894. nil to indicate that that Org can continue with other options like
  8895. exact and fuzzy text search.")
  8896. (defun org-next-link (&optional search-backward)
  8897. "Move forward to the next link.
  8898. If the link is in hidden text, expose it."
  8899. (interactive "P")
  8900. (when (and org-link-search-failed (eq this-command last-command))
  8901. (goto-char (point-min))
  8902. (message "Link search wrapped back to beginning of buffer"))
  8903. (setq org-link-search-failed nil)
  8904. (let* ((pos (point))
  8905. (ct (org-context))
  8906. (a (assq :link ct))
  8907. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8908. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8909. ((looking-at org-any-link-re)
  8910. ;; Don't stay stuck at link without an org-link face
  8911. (forward-char (if search-backward -1 1))))
  8912. (if (funcall srch-fun org-any-link-re nil t)
  8913. (progn
  8914. (goto-char (match-beginning 0))
  8915. (when (org-invisible-p) (org-show-context)))
  8916. (goto-char pos)
  8917. (setq org-link-search-failed t)
  8918. (message "No further link found"))))
  8919. (defun org-previous-link ()
  8920. "Move backward to the previous link.
  8921. If the link is in hidden text, expose it."
  8922. (interactive)
  8923. (org-next-link t))
  8924. (defun org-translate-link (s)
  8925. "Translate a link string if a translation function has been defined."
  8926. (with-temp-buffer
  8927. (insert (org-trim s))
  8928. (org-trim (org-element-interpret-data (org-element-context)))))
  8929. (defun org-translate-link-from-planner (type path)
  8930. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8931. This is still an experimental function, your mileage may vary."
  8932. (cond
  8933. ((member type '("http" "https" "news" "ftp"))
  8934. ;; standard Internet links are the same.
  8935. nil)
  8936. ((and (equal type "irc") (string-match "^//" path))
  8937. ;; Planner has two / at the beginning of an irc link, we have 1.
  8938. ;; We should have zero, actually....
  8939. (setq path (substring path 1)))
  8940. ((and (equal type "lisp") (string-match "^/" path))
  8941. ;; Planner has a slash, we do not.
  8942. (setq type "elisp" path (substring path 1)))
  8943. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8944. ;; A typical message link. Planner has the id after the final slash,
  8945. ;; we separate it with a hash mark
  8946. (setq path (concat (match-string 1 path) "#"
  8947. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8948. (cons type path))
  8949. (defun org-find-file-at-mouse (ev)
  8950. "Open file link or URL at mouse."
  8951. (interactive "e")
  8952. (mouse-set-point ev)
  8953. (org-open-at-point 'in-emacs))
  8954. (defun org-open-at-mouse (ev)
  8955. "Open file link or URL at mouse.
  8956. See the docstring of `org-open-file' for details."
  8957. (interactive "e")
  8958. (mouse-set-point ev)
  8959. (when (eq major-mode 'org-agenda-mode)
  8960. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8961. (org-open-at-point))
  8962. (defvar org-window-config-before-follow-link nil
  8963. "The window configuration before following a link.
  8964. This is saved in case the need arises to restore it.")
  8965. ;;;###autoload
  8966. (defun org-open-at-point-global ()
  8967. "Follow a link or a time-stamp like Org mode does.
  8968. Also follow links and emails as seen by `thing-at-point'.
  8969. This command can be called in any mode to follow an external
  8970. link or a time-stamp that has Org mode syntax. Its behavior
  8971. is undefined when called on internal links like fuzzy links.
  8972. Raise a user error when there is nothing to follow."
  8973. (interactive)
  8974. (let ((tap-url (thing-at-point 'url))
  8975. (tap-email (thing-at-point 'email)))
  8976. (cond ((org-in-regexp org-any-link-re)
  8977. (org-open-link-from-string (match-string-no-properties 0)))
  8978. ((or (org-in-regexp org-ts-regexp-both nil t)
  8979. (org-in-regexp org-tsr-regexp-both nil t))
  8980. (org-follow-timestamp-link))
  8981. (tap-url (org-open-link-from-string tap-url))
  8982. (tap-email (org-open-link-from-string
  8983. (concat "mailto:" tap-email)))
  8984. (t (user-error "No link found")))))
  8985. ;;;###autoload
  8986. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8987. "Open a link in the string S, as if it was in Org mode."
  8988. (interactive "sLink: \nP")
  8989. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8990. (with-temp-buffer
  8991. (let ((org-inhibit-startup (not reference-buffer)))
  8992. (org-mode)
  8993. (insert s)
  8994. (goto-char (point-min))
  8995. (when reference-buffer
  8996. (setq org-link-abbrev-alist-local
  8997. (with-current-buffer reference-buffer
  8998. org-link-abbrev-alist-local)))
  8999. (org-open-at-point arg reference-buffer)))))
  9000. (defvar org-open-at-point-functions nil
  9001. "Hook that is run when following a link at point.
  9002. Functions in this hook must return t if they identify and follow
  9003. a link at point. If they don't find anything interesting at point,
  9004. they must return nil.")
  9005. (defvar org-link-search-inhibit-query nil)
  9006. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9007. (defun org--open-doi-link (path)
  9008. "Open a \"doi\" type link.
  9009. PATH is a the path to search for, as a string."
  9010. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9011. (defun org--open-elisp-link (path)
  9012. "Open a \"elisp\" type link.
  9013. PATH is the sexp to evaluate, as a string."
  9014. (let ((cmd path))
  9015. (if (or (and (org-string-nw-p
  9016. org-confirm-elisp-link-not-regexp)
  9017. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9018. (not org-confirm-elisp-link-function)
  9019. (funcall org-confirm-elisp-link-function
  9020. (format "Execute \"%s\" as elisp? "
  9021. (org-add-props cmd nil 'face 'org-warning))))
  9022. (message "%s => %s" cmd
  9023. (if (eq (string-to-char cmd) ?\()
  9024. (eval (read cmd))
  9025. (call-interactively (read cmd))))
  9026. (user-error "Abort"))))
  9027. (defun org--open-help-link (path)
  9028. "Open a \"help\" type link.
  9029. PATH is a symbol name, as a string."
  9030. (pcase (intern path)
  9031. ((and (pred fboundp) variable) (describe-function variable))
  9032. ((and (pred boundp) function) (describe-variable function))
  9033. (name (user-error "Unknown function or variable: %s" name))))
  9034. (defun org--open-shell-link (path)
  9035. "Open a \"shell\" type link.
  9036. PATH is the command to execute, as a string."
  9037. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9038. (cmd path))
  9039. (if (or (and (org-string-nw-p
  9040. org-confirm-shell-link-not-regexp)
  9041. (string-match
  9042. org-confirm-shell-link-not-regexp cmd))
  9043. (not org-confirm-shell-link-function)
  9044. (funcall org-confirm-shell-link-function
  9045. (format "Execute \"%s\" in shell? "
  9046. (org-add-props cmd nil
  9047. 'face 'org-warning))))
  9048. (progn
  9049. (message "Executing %s" cmd)
  9050. (shell-command cmd buf)
  9051. (when (featurep 'midnight)
  9052. (setq clean-buffer-list-kill-buffer-names
  9053. (cons (buffer-name buf)
  9054. clean-buffer-list-kill-buffer-names))))
  9055. (user-error "Abort"))))
  9056. (defun org-open-at-point (&optional arg reference-buffer)
  9057. "Open link, timestamp, footnote or tags at point.
  9058. When point is on a link, follow it. Normally, files will be
  9059. opened by an appropriate application. If the optional prefix
  9060. argument ARG is non-nil, Emacs will visit the file. With
  9061. a double prefix argument, try to open outside of Emacs, in the
  9062. application the system uses for this file type.
  9063. When point is on a timestamp, open the agenda at the day
  9064. specified.
  9065. When point is a footnote definition, move to the first reference
  9066. found. If it is on a reference, move to the associated
  9067. definition.
  9068. When point is on a headline, display a list of every link in the
  9069. entry, so it is possible to pick one, or all, of them. If point
  9070. is on a tag, call `org-tags-view' instead.
  9071. When optional argument REFERENCE-BUFFER is non-nil, it should
  9072. specify a buffer from where the link search should happen. This
  9073. is used internally by `org-open-link-from-string'.
  9074. On top of syntactically correct links, this function also tries
  9075. to open links and time-stamps in comments, node properties, and
  9076. keywords if point is on something looking like a timestamp or
  9077. a link."
  9078. (interactive "P")
  9079. (org-load-modules-maybe)
  9080. (setq org-window-config-before-follow-link (current-window-configuration))
  9081. (org-remove-occur-highlights nil nil t)
  9082. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9083. (let* ((context
  9084. ;; Only consider supported types, even if they are not the
  9085. ;; closest one.
  9086. (org-element-lineage
  9087. (org-element-context)
  9088. '(clock comment comment-block footnote-definition
  9089. footnote-reference headline inline-src-block inlinetask
  9090. keyword link node-property src-block timestamp)
  9091. t))
  9092. (type (org-element-type context))
  9093. (value (org-element-property :value context)))
  9094. (cond
  9095. ((not type) (user-error "No link found"))
  9096. ;; No valid link at point. For convenience, look if something
  9097. ;; looks like a link under point in some specific places.
  9098. ((memq type '(comment comment-block node-property keyword))
  9099. (call-interactively #'org-open-at-point-global))
  9100. ;; On a headline or an inlinetask, but not on a timestamp,
  9101. ;; a link, a footnote reference.
  9102. ((memq type '(headline inlinetask))
  9103. (org-match-line org-complex-heading-regexp)
  9104. (if (and (match-beginning 5)
  9105. (>= (point) (match-beginning 5))
  9106. (< (point) (match-end 5)))
  9107. ;; On tags.
  9108. (org-tags-view arg (substring (match-string 5) 0 -1))
  9109. ;; Not on tags.
  9110. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9111. (`(nil . ,_)
  9112. (require 'org-attach)
  9113. (org-attach-reveal 'if-exists))
  9114. (`(,links . ,links-end)
  9115. (dolist (link (if (stringp links) (list links) links))
  9116. (search-forward link nil links-end)
  9117. (goto-char (match-beginning 0))
  9118. (org-open-at-point))))))
  9119. ;; On a footnote reference or at definition's label.
  9120. ((or (eq type 'footnote-reference)
  9121. (and (eq type 'footnote-definition)
  9122. (save-excursion
  9123. ;; Do not validate action when point is on the
  9124. ;; spaces right after the footnote label, in order
  9125. ;; to be on par with behavior on links.
  9126. (skip-chars-forward " \t")
  9127. (let ((begin
  9128. (org-element-property :contents-begin context)))
  9129. (if begin (< (point) begin)
  9130. (= (org-element-property :post-affiliated context)
  9131. (line-beginning-position)))))))
  9132. (org-footnote-action))
  9133. ;; On a clock line, make sure point is on the timestamp
  9134. ;; before opening it.
  9135. ((and (eq type 'clock)
  9136. value
  9137. (>= (point) (org-element-property :begin value))
  9138. (<= (point) (org-element-property :end value)))
  9139. (org-follow-timestamp-link))
  9140. ((eq type 'src-block) (org-babel-open-src-block-result))
  9141. ;; Do nothing on white spaces after an object.
  9142. ((>= (point)
  9143. (save-excursion
  9144. (goto-char (org-element-property :end context))
  9145. (skip-chars-backward " \t")
  9146. (point)))
  9147. (user-error "No link found"))
  9148. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  9149. ((eq type 'timestamp) (org-follow-timestamp-link))
  9150. ((eq type 'link)
  9151. (let ((type (org-element-property :type context))
  9152. (path (org-link-unescape (org-element-property :path context))))
  9153. ;; Switch back to REFERENCE-BUFFER needed when called in
  9154. ;; a temporary buffer through `org-open-link-from-string'.
  9155. (with-current-buffer (or reference-buffer (current-buffer))
  9156. (cond
  9157. ((equal type "file")
  9158. (if (string-match "[*?{]" (file-name-nondirectory path))
  9159. (dired path)
  9160. ;; Look into `org-link-parameters' in order to find
  9161. ;; a DEDICATED-FUNCTION to open file. The function
  9162. ;; will be applied on raw link instead of parsed link
  9163. ;; due to the limitation in `org-add-link-type'
  9164. ;; ("open" function called with a single argument).
  9165. ;; If no such function is found, fallback to
  9166. ;; `org-open-file'.
  9167. (let* ((option (org-element-property :search-option context))
  9168. (app (org-element-property :application context))
  9169. (dedicated-function
  9170. (org-link-get-parameter
  9171. (if app (concat type "+" app) type)
  9172. :follow)))
  9173. (if dedicated-function
  9174. (funcall dedicated-function
  9175. (concat path
  9176. (and option (concat "::" option))))
  9177. (apply #'org-open-file
  9178. path
  9179. (cond (arg)
  9180. ((equal app "emacs") 'emacs)
  9181. ((equal app "sys") 'system))
  9182. (cond ((not option) nil)
  9183. ((string-match-p "\\`[0-9]+\\'" option)
  9184. (list (string-to-number option)))
  9185. (t (list nil
  9186. (org-link-unescape option)))))))))
  9187. ((functionp (org-link-get-parameter type :follow))
  9188. (funcall (org-link-get-parameter type :follow) path))
  9189. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9190. (unless (run-hook-with-args-until-success
  9191. 'org-open-link-functions path)
  9192. (if (not arg) (org-mark-ring-push)
  9193. (switch-to-buffer-other-window
  9194. (org-get-buffer-for-internal-link (current-buffer))))
  9195. (let ((destination
  9196. (org-with-wide-buffer
  9197. (if (equal type "radio")
  9198. (org-search-radio-target
  9199. (org-element-property :path context))
  9200. (org-link-search
  9201. (if (member type '("custom-id" "coderef"))
  9202. (org-element-property :raw-link context)
  9203. path)
  9204. ;; Prevent fuzzy links from matching
  9205. ;; themselves.
  9206. (and (equal type "fuzzy")
  9207. (+ 2 (org-element-property :begin context)))))
  9208. (point))))
  9209. (unless (and (<= (point-min) destination)
  9210. (>= (point-max) destination))
  9211. (widen))
  9212. (goto-char destination))))
  9213. (t (browse-url-at-point))))))
  9214. (t (user-error "No link found")))))
  9215. (run-hook-with-args 'org-follow-link-hook))
  9216. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9217. "Offer links in the current entry and return the selected link.
  9218. If there is only one link, return it.
  9219. If NTH is an integer, return the NTH link found.
  9220. If ZERO is a string, check also this string for a link, and if
  9221. there is one, return it."
  9222. (with-current-buffer buffer
  9223. (org-with-wide-buffer
  9224. (goto-char marker)
  9225. (let ((cnt ?0)
  9226. have-zero end links link c)
  9227. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9228. (push (match-string 0 zero) links)
  9229. (setq cnt (1- cnt) have-zero t))
  9230. (save-excursion
  9231. (org-back-to-heading t)
  9232. (setq end (save-excursion (outline-next-heading) (point)))
  9233. (while (re-search-forward org-any-link-re end t)
  9234. (push (match-string 0) links))
  9235. (setq links (org-uniquify (reverse links))))
  9236. (cond
  9237. ((null links)
  9238. (message "No links"))
  9239. ((equal (length links) 1)
  9240. (setq link (car links)))
  9241. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9242. (setq link (nth (if have-zero nth (1- nth)) links)))
  9243. (t ; we have to select a link
  9244. (save-excursion
  9245. (save-window-excursion
  9246. (delete-other-windows)
  9247. (with-output-to-temp-buffer "*Select Link*"
  9248. (dolist (l links)
  9249. (cond
  9250. ((not (string-match org-bracket-link-regexp l))
  9251. (princ (format "[%c] %s\n" (cl-incf cnt)
  9252. (org-unbracket-string "<" ">" l))))
  9253. ((match-end 3)
  9254. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9255. (match-string 3 l) (match-string 1 l))))
  9256. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9257. (match-string 1 l)))))))
  9258. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9259. (message "Select link to open, RET to open all:")
  9260. (setq c (read-char-exclusive))
  9261. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9262. (when (equal c ?q) (user-error "Abort"))
  9263. (if (equal c ?\C-m)
  9264. (setq link links)
  9265. (setq nth (- c ?0))
  9266. (when have-zero (setq nth (1+ nth)))
  9267. (unless (and (integerp nth) (>= (length links) nth))
  9268. (user-error "Invalid link selection"))
  9269. (setq link (nth (1- nth) links)))))
  9270. (cons link end)))))
  9271. ;; TODO: These functions are deprecated since `org-open-at-point'
  9272. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9273. (defun org-open-file-with-system (path)
  9274. "Open file at PATH using the system way of opening it."
  9275. (org-open-file path 'system))
  9276. (defun org-open-file-with-emacs (path)
  9277. "Open file at PATH in Emacs."
  9278. (org-open-file path 'emacs))
  9279. ;;; File search
  9280. (defvar org-create-file-search-functions nil
  9281. "List of functions to construct the right search string for a file link.
  9282. These functions are called in turn with point at the location to
  9283. which the link should point.
  9284. A function in the hook should first test if it would like to
  9285. handle this file type, for example by checking the `major-mode'
  9286. or the file extension. If it decides not to handle this file, it
  9287. should just return nil to give other functions a chance. If it
  9288. does handle the file, it must return the search string to be used
  9289. when following the link. The search string will be part of the
  9290. file link, given after a double colon, and `org-open-at-point'
  9291. will automatically search for it. If special measures must be
  9292. taken to make the search successful, another function should be
  9293. added to the companion hook `org-execute-file-search-functions',
  9294. which see.
  9295. A function in this hook may also use `setq' to set the variable
  9296. `description' to provide a suggestion for the descriptive text to
  9297. be used for this link when it gets inserted into an Org buffer
  9298. with \\[org-insert-link].")
  9299. (defvar org-execute-file-search-functions nil
  9300. "List of functions to execute a file search triggered by a link.
  9301. Functions added to this hook must accept a single argument, the
  9302. search string that was part of the file link, the part after the
  9303. double colon. The function must first check if it would like to
  9304. handle this search, for example by checking the `major-mode' or
  9305. the file extension. If it decides not to handle this search, it
  9306. should just return nil to give other functions a chance. If it
  9307. does handle the search, it must return a non-nil value to keep
  9308. other functions from trying.
  9309. Each function can access the current prefix argument through the
  9310. variable `current-prefix-arg'. Note that a single prefix is used
  9311. to force opening a link in Emacs, so it may be good to only use a
  9312. numeric or double prefix to guide the search function.
  9313. In case this is needed, a function in this hook can also restore
  9314. the window configuration before `org-open-at-point' was called using:
  9315. (set-window-configuration org-window-config-before-follow-link)")
  9316. (defun org-search-radio-target (target)
  9317. "Search a radio target matching TARGET in current buffer.
  9318. White spaces are not significant."
  9319. (let ((re (format "<<<%s>>>"
  9320. (mapconcat #'regexp-quote
  9321. (split-string target)
  9322. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9323. (origin (point)))
  9324. (goto-char (point-min))
  9325. (catch :radio-match
  9326. (while (re-search-forward re nil t)
  9327. (backward-char)
  9328. (let ((object (org-element-context)))
  9329. (when (eq (org-element-type object) 'radio-target)
  9330. (goto-char (org-element-property :begin object))
  9331. (org-show-context 'link-search)
  9332. (throw :radio-match nil))))
  9333. (goto-char origin)
  9334. (user-error "No match for radio target: %s" target))))
  9335. (defun org-link-search (s &optional avoid-pos stealth)
  9336. "Search for a search string S.
  9337. If S starts with \"#\", it triggers a custom ID search.
  9338. If S is enclosed within parenthesis, it initiates a coderef
  9339. search.
  9340. If S is surrounded by forward slashes, it is interpreted as
  9341. a regular expression. In Org mode files, this will create an
  9342. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9343. to list matches. If the current buffer is in `dired-mode', grep
  9344. will be used to search in all files.
  9345. When AVOID-POS is given, ignore matches near that position.
  9346. When optional argument STEALTH is non-nil, do not modify
  9347. visibility around point, thus ignoring `org-show-context-detail'
  9348. variable.
  9349. Search is case-insensitive and ignores white spaces. Return type
  9350. of matched result, which is either `dedicated' or `fuzzy'."
  9351. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9352. (let* ((case-fold-search t)
  9353. (origin (point))
  9354. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9355. (starred (eq (string-to-char normalized) ?*))
  9356. (words (split-string (if starred (substring s 1) s)))
  9357. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9358. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9359. type)
  9360. (cond
  9361. ;; Check if there are any special search functions.
  9362. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9363. ((eq (string-to-char s) ?#)
  9364. ;; Look for a custom ID S if S starts with "#".
  9365. (let* ((id (substring normalized 1))
  9366. (match (org-find-property "CUSTOM_ID" id)))
  9367. (if match (progn (goto-char match) (setf type 'dedicated))
  9368. (error "No match for custom ID: %s" id))))
  9369. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9370. ;; Look for coderef targets if S is enclosed within parenthesis.
  9371. (let ((coderef (match-string-no-properties 1 normalized))
  9372. (re (substring s-single-re 1 -1)))
  9373. (goto-char (point-min))
  9374. (catch :coderef-match
  9375. (while (re-search-forward re nil t)
  9376. (let ((element (org-element-at-point)))
  9377. (when (and (memq (org-element-type element)
  9378. '(example-block src-block))
  9379. (org-match-line
  9380. (concat ".*?" (org-src-coderef-regexp
  9381. (org-src-coderef-format element)
  9382. coderef))))
  9383. (setq type 'dedicated)
  9384. (goto-char (match-beginning 2))
  9385. (throw :coderef-match nil))))
  9386. (goto-char origin)
  9387. (error "No match for coderef: %s" coderef))))
  9388. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9389. ;; Look for a regular expression.
  9390. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9391. (match-string 1 s)))
  9392. ;; From here, we handle fuzzy links.
  9393. ;;
  9394. ;; Look for targets, only if not in a headline search.
  9395. ((and (not starred)
  9396. (let ((target (format "<<%s>>" s-multi-re)))
  9397. (catch :target-match
  9398. (goto-char (point-min))
  9399. (while (re-search-forward target nil t)
  9400. (backward-char)
  9401. (let ((context (org-element-context)))
  9402. (when (eq (org-element-type context) 'target)
  9403. (setq type 'dedicated)
  9404. (goto-char (org-element-property :begin context))
  9405. (throw :target-match t))))
  9406. nil))))
  9407. ;; Look for elements named after S, only if not in a headline
  9408. ;; search.
  9409. ((and (not starred)
  9410. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9411. (catch :name-match
  9412. (goto-char (point-min))
  9413. (while (re-search-forward name nil t)
  9414. (let ((element (org-element-at-point)))
  9415. (when (equal words
  9416. (split-string
  9417. (org-element-property :name element)))
  9418. (setq type 'dedicated)
  9419. (beginning-of-line)
  9420. (throw :name-match t))))
  9421. nil))))
  9422. ;; Regular text search. Prefer headlines in Org mode buffers.
  9423. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9424. ;; statistics cookies and tags.
  9425. ((and (derived-mode-p 'org-mode)
  9426. (let ((title-re
  9427. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9428. org-outline-regexp-bol
  9429. org-comment-string
  9430. (mapconcat #'regexp-quote words ".+")))
  9431. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9432. (comment-re (eval-when-compile
  9433. (format "\\`%s[ \t]+" org-comment-string))))
  9434. (goto-char (point-min))
  9435. (catch :found
  9436. (while (re-search-forward title-re nil t)
  9437. (when (equal words
  9438. (split-string
  9439. (replace-regexp-in-string
  9440. cookie-re ""
  9441. (replace-regexp-in-string
  9442. comment-re "" (org-get-heading t t t)))))
  9443. (throw :found t)))
  9444. nil)))
  9445. (beginning-of-line)
  9446. (setq type 'dedicated))
  9447. ;; Offer to create non-existent headline depending on
  9448. ;; `org-link-search-must-match-exact-headline'.
  9449. ((and (derived-mode-p 'org-mode)
  9450. (not org-link-search-inhibit-query)
  9451. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9452. (yes-or-no-p "No match - create this as a new heading? "))
  9453. (goto-char (point-max))
  9454. (unless (bolp) (newline))
  9455. (org-insert-heading nil t t)
  9456. (insert s "\n")
  9457. (beginning-of-line 0))
  9458. ;; Only headlines are looked after. No need to process
  9459. ;; further: throw an error.
  9460. ((and (derived-mode-p 'org-mode)
  9461. (or starred org-link-search-must-match-exact-headline))
  9462. (goto-char origin)
  9463. (error "No match for fuzzy expression: %s" normalized))
  9464. ;; Regular text search.
  9465. ((catch :fuzzy-match
  9466. (goto-char (point-min))
  9467. (while (re-search-forward s-multi-re nil t)
  9468. ;; Skip match if it contains AVOID-POS or it is included in
  9469. ;; a link with a description but outside the description.
  9470. (unless (or (and avoid-pos
  9471. (<= (match-beginning 0) avoid-pos)
  9472. (> (match-end 0) avoid-pos))
  9473. (and (save-match-data
  9474. (org-in-regexp org-bracket-link-regexp))
  9475. (match-beginning 3)
  9476. (or (> (match-beginning 3) (point))
  9477. (<= (match-end 3) (point)))
  9478. (org-element-lineage
  9479. (save-match-data (org-element-context))
  9480. '(link) t)))
  9481. (goto-char (match-beginning 0))
  9482. (setq type 'fuzzy)
  9483. (throw :fuzzy-match t)))
  9484. nil))
  9485. ;; All failed. Throw an error.
  9486. (t (goto-char origin)
  9487. (error "No match for fuzzy expression: %s" normalized)))
  9488. ;; Disclose surroundings of match, if appropriate.
  9489. (when (and (derived-mode-p 'org-mode) (not stealth))
  9490. (org-show-context 'link-search))
  9491. type))
  9492. (defun org-get-buffer-for-internal-link (buffer)
  9493. "Return a buffer to be used for displaying the link target of internal links."
  9494. (cond
  9495. ((not org-display-internal-link-with-indirect-buffer)
  9496. buffer)
  9497. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9498. (message "Buffer is already a clone, not making another one")
  9499. ;; we also do not modify visibility in this case
  9500. buffer)
  9501. (t ; make a new indirect buffer for displaying the link
  9502. (let* ((bn (buffer-name buffer))
  9503. (ibn (concat bn "(Clone)"))
  9504. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9505. (with-current-buffer ib (org-overview))
  9506. ib))))
  9507. (defun org-do-occur (regexp &optional cleanup)
  9508. "Call the Emacs command `occur'.
  9509. If CLEANUP is non-nil, remove the printout of the regular expression
  9510. in the *Occur* buffer. This is useful if the regex is long and not useful
  9511. to read."
  9512. (occur regexp)
  9513. (when cleanup
  9514. (let ((cwin (selected-window)) win beg end)
  9515. (when (setq win (get-buffer-window "*Occur*"))
  9516. (select-window win))
  9517. (goto-char (point-min))
  9518. (when (re-search-forward "match[a-z]+" nil t)
  9519. (setq beg (match-end 0))
  9520. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9521. (setq end (1- (match-beginning 0)))))
  9522. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9523. (goto-char (point-min))
  9524. (select-window cwin))))
  9525. ;;; The Mark Ring
  9526. (defvar org-mark-ring nil
  9527. "Mark ring for positions before jumps in Org mode.")
  9528. (defvar org-mark-ring-last-goto nil
  9529. "Last position in the mark ring used to go back.")
  9530. ;; Fill and close the ring
  9531. (setq org-mark-ring nil)
  9532. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9533. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9534. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9535. org-mark-ring)
  9536. (defun org-mark-ring-push (&optional pos buffer)
  9537. "Put the current position into the mark ring and rotate it.
  9538. Also push position into the Emacs mark ring. If optional
  9539. argument POS and BUFFER are not nil, mark this location instead."
  9540. (interactive)
  9541. (let ((pos (or pos (point)))
  9542. (buffer (or buffer (current-buffer))))
  9543. (with-current-buffer buffer
  9544. (org-with-point-at pos (push-mark nil t)))
  9545. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9546. (move-marker (car org-mark-ring) pos buffer))
  9547. (message
  9548. (substitute-command-keys
  9549. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9550. (defun org-mark-ring-goto (&optional n)
  9551. "Jump to the previous position in the mark ring.
  9552. With prefix arg N, jump back that many stored positions. When
  9553. called several times in succession, walk through the entire ring.
  9554. Org mode commands jumping to a different position in the current file,
  9555. or to another Org file, automatically push the old position onto the ring."
  9556. (interactive "p")
  9557. (let (p m)
  9558. (if (eq last-command this-command)
  9559. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9560. (setq p org-mark-ring))
  9561. (setq org-mark-ring-last-goto p)
  9562. (setq m (car p))
  9563. (pop-to-buffer-same-window (marker-buffer m))
  9564. (goto-char m)
  9565. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9566. (defun org-add-angle-brackets (s)
  9567. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9568. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9569. s)
  9570. ;;; Following specific links
  9571. (defvar org-agenda-buffer-tmp-name)
  9572. (defvar org-agenda-start-on-weekday)
  9573. (defun org-follow-timestamp-link ()
  9574. "Open an agenda view for the time-stamp date/range at point."
  9575. (cond
  9576. ((org-at-date-range-p t)
  9577. (let ((org-agenda-start-on-weekday)
  9578. (t1 (match-string 1))
  9579. (t2 (match-string 2)) tt1 tt2)
  9580. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9581. tt2 (time-to-days (org-time-string-to-time t2)))
  9582. (let ((org-agenda-buffer-tmp-name
  9583. (format "*Org Agenda(a:%s)"
  9584. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9585. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9586. ((org-at-timestamp-p 'lax)
  9587. (let ((org-agenda-buffer-tmp-name
  9588. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9589. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9590. (substring (match-string 1) 0 10)))
  9591. 1)))
  9592. (t (error "This should not happen"))))
  9593. ;;; Following file links
  9594. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9595. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9596. (declare-function mailcap-mime-info
  9597. "mailcap" (string &optional request no-decode))
  9598. (defvar org-wait nil)
  9599. (defun org-open-file (path &optional in-emacs line search)
  9600. "Open the file at PATH.
  9601. First, this expands any special file name abbreviations. Then the
  9602. configuration variable `org-file-apps' is checked if it contains an
  9603. entry for this file type, and if yes, the corresponding command is launched.
  9604. If no application is found, Emacs simply visits the file.
  9605. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9606. With a double \\[universal-argument] \\[universal-argument] \
  9607. prefix arg, Org tries to avoid opening in Emacs
  9608. and to use an external application to visit the file.
  9609. Optional LINE specifies a line to go to, optional SEARCH a string
  9610. to search for. If LINE or SEARCH is given, the file will be
  9611. opened in Emacs, unless an entry from org-file-apps that makes
  9612. use of groups in a regexp matches.
  9613. If you want to change the way frames are used when following a
  9614. link, please customize `org-link-frame-setup'.
  9615. If the file does not exist, an error is thrown."
  9616. (let* ((file (if (equal path "")
  9617. buffer-file-name
  9618. (substitute-in-file-name (expand-file-name path))))
  9619. (file-apps (append org-file-apps (org-default-apps)))
  9620. (apps (cl-remove-if
  9621. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9622. (apps-dlink (cl-remove-if-not
  9623. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9624. (remp (and (assq 'remote apps) (file-remote-p file)))
  9625. (dirp (unless remp (file-directory-p file)))
  9626. (file (if (and dirp org-open-directory-means-index-dot-org)
  9627. (concat (file-name-as-directory file) "index.org")
  9628. file))
  9629. (a-m-a-p (assq 'auto-mode apps))
  9630. (dfile (downcase file))
  9631. ;; Reconstruct the original link from the PATH, LINE and
  9632. ;; SEARCH args.
  9633. (link (cond (line (concat file "::" (number-to-string line)))
  9634. (search (concat file "::" search))
  9635. (t file)))
  9636. (dlink (downcase link))
  9637. (ext
  9638. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9639. (match-string 1 dfile)))
  9640. (save-position-maybe
  9641. (let ((old-buffer (current-buffer))
  9642. (old-pos (point))
  9643. (old-mode major-mode))
  9644. (lambda ()
  9645. (and (derived-mode-p 'org-mode)
  9646. (eq old-mode 'org-mode)
  9647. (or (not (eq old-buffer (current-buffer)))
  9648. (not (eq old-pos (point))))
  9649. (org-mark-ring-push old-pos old-buffer)))))
  9650. cmd link-match-data)
  9651. (cond
  9652. ((member in-emacs '((16) system))
  9653. (setq cmd (cdr (assq 'system apps))))
  9654. (in-emacs (setq cmd 'emacs))
  9655. (t
  9656. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9657. (and dirp (cdr (assq 'directory apps)))
  9658. ;; First, try matching against apps-dlink if we
  9659. ;; get a match here, store the match data for
  9660. ;; later.
  9661. (let ((match (assoc-default dlink apps-dlink
  9662. 'string-match)))
  9663. (if match
  9664. (progn (setq link-match-data (match-data))
  9665. match)
  9666. (progn (setq in-emacs (or in-emacs line search))
  9667. nil))) ; if we have no match in apps-dlink,
  9668. ; always open the file in emacs if line or search
  9669. ; is given (for backwards compatibility)
  9670. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9671. 'string-match)
  9672. (cdr (assoc ext apps))
  9673. (cdr (assq t apps))))))
  9674. (when (eq cmd 'system)
  9675. (setq cmd (cdr (assq 'system apps))))
  9676. (when (eq cmd 'default)
  9677. (setq cmd (cdr (assoc t apps))))
  9678. (when (eq cmd 'mailcap)
  9679. (require 'mailcap)
  9680. (mailcap-parse-mailcaps)
  9681. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9682. (command (mailcap-mime-info mime-type)))
  9683. (if (stringp command)
  9684. (setq cmd command)
  9685. (setq cmd 'emacs))))
  9686. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9687. (not (file-exists-p file))
  9688. (not org-open-non-existing-files))
  9689. (user-error "No such file: %s" file))
  9690. (cond
  9691. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9692. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9693. (while (string-match "['\"]%s['\"]" cmd)
  9694. (setq cmd (replace-match "%s" t t cmd)))
  9695. (setq cmd (replace-regexp-in-string
  9696. "%s"
  9697. (shell-quote-argument (convert-standard-filename file))
  9698. cmd
  9699. nil t))
  9700. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9701. (save-match-data
  9702. (let ((match-index 1)
  9703. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9704. (set-match-data link-match-data)
  9705. (while (<= match-index number-of-groups)
  9706. (let ((regex (concat "%" (number-to-string match-index)))
  9707. (replace-with (match-string match-index dlink)))
  9708. (while (string-match regex cmd)
  9709. (setq cmd (replace-match replace-with t t cmd))))
  9710. (setq match-index (+ match-index 1)))))
  9711. (save-window-excursion
  9712. (message "Running %s...done" cmd)
  9713. (start-process-shell-command cmd nil cmd)
  9714. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9715. ((or (stringp cmd)
  9716. (eq cmd 'emacs))
  9717. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9718. (widen)
  9719. (cond (line (org-goto-line line)
  9720. (when (derived-mode-p 'org-mode) (org-reveal)))
  9721. (search (condition-case err
  9722. (org-link-search search)
  9723. ;; Save position before error-ing out so user
  9724. ;; can easily move back to the original buffer.
  9725. (error (funcall save-position-maybe)
  9726. (error (nth 1 err)))))))
  9727. ((functionp cmd)
  9728. (save-match-data
  9729. (set-match-data link-match-data)
  9730. (condition-case nil
  9731. (funcall cmd file link)
  9732. ;; FIXME: Remove this check when most default installations
  9733. ;; of Emacs have at least Org 9.0.
  9734. ((debug wrong-number-of-arguments wrong-type-argument
  9735. invalid-function)
  9736. (user-error "Please see Org News for version 9.0 about \
  9737. `org-file-apps'--Lisp error: %S" cmd)))))
  9738. ((consp cmd)
  9739. ;; FIXME: Remove this check when most default installations of
  9740. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9741. ;; fall back to `org-link-frame-setup' for an old usage of
  9742. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9743. (user-error "Please see Org News for version 9.0 about \
  9744. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9745. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9746. (funcall save-position-maybe)))
  9747. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9748. "This function returns non-nil if `entry' uses a regular
  9749. expression which should be matched against the whole link by
  9750. org-open-file.
  9751. It assumes that is the case when the entry uses a regular
  9752. expression which has at least one grouping construct and the
  9753. action is either a lisp form or a command string containing
  9754. `%1', i.e. using at least one subexpression match as a
  9755. parameter."
  9756. (let ((selector (car entry))
  9757. (action (cdr entry)))
  9758. (if (stringp selector)
  9759. (and (> (regexp-opt-depth selector) 0)
  9760. (or (and (stringp action)
  9761. (string-match "%[0-9]" action))
  9762. (consp action)))
  9763. nil)))
  9764. (defun org-default-apps ()
  9765. "Return the default applications for this operating system."
  9766. (cond
  9767. ((eq system-type 'darwin)
  9768. org-file-apps-defaults-macosx)
  9769. ((eq system-type 'windows-nt)
  9770. org-file-apps-defaults-windowsnt)
  9771. (t org-file-apps-defaults-gnu)))
  9772. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9773. "Convert extensions to regular expressions in the cars of LIST.
  9774. Also, weed out any non-string entries, because the return value is used
  9775. only for regexp matching.
  9776. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9777. point to the symbol `emacs', indicating that the file should
  9778. be opened in Emacs."
  9779. (append
  9780. (delq nil
  9781. (mapcar (lambda (x)
  9782. (unless (not (stringp (car x)))
  9783. (if (string-match "\\W" (car x))
  9784. x
  9785. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9786. list))
  9787. (when add-auto-mode
  9788. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9789. ;;;; Refiling
  9790. (defun org-get-org-file ()
  9791. "Read a filename, with default directory `org-directory'."
  9792. (let ((default (or org-default-notes-file remember-data-file)))
  9793. (read-file-name (format "File name [%s]: " default)
  9794. (file-name-as-directory org-directory)
  9795. default)))
  9796. (defun org-notes-order-reversed-p ()
  9797. "Check if the current file should receive notes in reversed order."
  9798. (cond
  9799. ((not org-reverse-note-order) nil)
  9800. ((eq t org-reverse-note-order) t)
  9801. ((not (listp org-reverse-note-order)) nil)
  9802. (t (catch 'exit
  9803. (dolist (entry org-reverse-note-order)
  9804. (when (string-match (car entry) buffer-file-name)
  9805. (throw 'exit (cdr entry))))))))
  9806. (defvar org-refile-target-table nil
  9807. "The list of refile targets, created by `org-refile'.")
  9808. (defvar org-agenda-new-buffers nil
  9809. "Buffers created to visit agenda files.")
  9810. (defvar org-refile-cache nil
  9811. "Cache for refile targets.")
  9812. (defvar org-refile-markers nil
  9813. "All the markers used for caching refile locations.")
  9814. (defun org-refile-marker (pos)
  9815. "Get a new refile marker, but only if caching is in use."
  9816. (if (not org-refile-use-cache)
  9817. pos
  9818. (let ((m (make-marker)))
  9819. (move-marker m pos)
  9820. (push m org-refile-markers)
  9821. m)))
  9822. (defun org-refile-cache-clear ()
  9823. "Clear the refile cache and disable all the markers."
  9824. (dolist (m org-refile-markers) (move-marker m nil))
  9825. (setq org-refile-markers nil)
  9826. (setq org-refile-cache nil)
  9827. (message "Refile cache has been cleared"))
  9828. (defun org-refile-cache-check-set (set)
  9829. "Check if all the markers in the cache still have live buffers."
  9830. (let (marker)
  9831. (catch 'exit
  9832. (while (and set (setq marker (nth 3 (pop set))))
  9833. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9834. (when (and marker (null (marker-buffer marker)))
  9835. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9836. (sit-for 3)
  9837. (throw 'exit nil)))
  9838. t)))
  9839. (defun org-refile-cache-put (set &rest identifiers)
  9840. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9841. (let* ((key (sha1 (prin1-to-string identifiers)))
  9842. (entry (assoc key org-refile-cache)))
  9843. (if entry
  9844. (setcdr entry set)
  9845. (push (cons key set) org-refile-cache))))
  9846. (defun org-refile-cache-get (&rest identifiers)
  9847. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9848. (cond
  9849. ((not org-refile-cache) nil)
  9850. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9851. (t
  9852. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9853. org-refile-cache))))
  9854. (and set (org-refile-cache-check-set set) set)))))
  9855. (defvar org-outline-path-cache nil
  9856. "Alist between buffer positions and outline paths.
  9857. It value is an alist (POSITION . PATH) where POSITION is the
  9858. buffer position at the beginning of an entry and PATH is a list
  9859. of strings describing the outline path for that entry, in reverse
  9860. order.")
  9861. (defun org-refile-get-targets (&optional default-buffer)
  9862. "Produce a table with refile targets."
  9863. (let ((case-fold-search nil)
  9864. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9865. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9866. targets tgs files desc descre)
  9867. (message "Getting targets...")
  9868. (with-current-buffer (or default-buffer (current-buffer))
  9869. (dolist (entry entries)
  9870. (setq files (car entry) desc (cdr entry))
  9871. (cond
  9872. ((null files) (setq files (list (current-buffer))))
  9873. ((eq files 'org-agenda-files)
  9874. (setq files (org-agenda-files 'unrestricted)))
  9875. ((and (symbolp files) (fboundp files))
  9876. (setq files (funcall files)))
  9877. ((and (symbolp files) (boundp files))
  9878. (setq files (symbol-value files))))
  9879. (when (stringp files) (setq files (list files)))
  9880. (cond
  9881. ((eq (car desc) :tag)
  9882. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9883. ((eq (car desc) :todo)
  9884. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9885. ((eq (car desc) :regexp)
  9886. (setq descre (cdr desc)))
  9887. ((eq (car desc) :level)
  9888. (setq descre (concat "^\\*\\{" (number-to-string
  9889. (if org-odd-levels-only
  9890. (1- (* 2 (cdr desc)))
  9891. (cdr desc)))
  9892. "\\}[ \t]")))
  9893. ((eq (car desc) :maxlevel)
  9894. (setq descre (concat "^\\*\\{1," (number-to-string
  9895. (if org-odd-levels-only
  9896. (1- (* 2 (cdr desc)))
  9897. (cdr desc)))
  9898. "\\}[ \t]")))
  9899. (t (error "Bad refiling target description %s" desc)))
  9900. (dolist (f files)
  9901. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9902. (or
  9903. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9904. (progn
  9905. (when (bufferp f)
  9906. (setq f (buffer-file-name (buffer-base-buffer f))))
  9907. (setq f (and f (expand-file-name f)))
  9908. (when (eq org-refile-use-outline-path 'file)
  9909. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9910. (when (eq org-refile-use-outline-path 'buffer-name)
  9911. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9912. (when (eq org-refile-use-outline-path 'full-file-path)
  9913. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9914. (org-with-wide-buffer
  9915. (goto-char (point-min))
  9916. (setq org-outline-path-cache nil)
  9917. (while (re-search-forward descre nil t)
  9918. (beginning-of-line)
  9919. (let ((case-fold-search nil))
  9920. (looking-at org-complex-heading-regexp))
  9921. (let ((begin (point))
  9922. (heading (match-string-no-properties 4)))
  9923. (unless (or (and
  9924. org-refile-target-verify-function
  9925. (not
  9926. (funcall org-refile-target-verify-function)))
  9927. (not heading))
  9928. (let ((re (format org-complex-heading-regexp-format
  9929. (regexp-quote heading)))
  9930. (target
  9931. (if (not org-refile-use-outline-path) heading
  9932. (mapconcat
  9933. #'identity
  9934. (append
  9935. (pcase org-refile-use-outline-path
  9936. (`file (list (file-name-nondirectory
  9937. (buffer-file-name
  9938. (buffer-base-buffer)))))
  9939. (`full-file-path
  9940. (list (buffer-file-name
  9941. (buffer-base-buffer))))
  9942. (`buffer-name
  9943. (list (buffer-name
  9944. (buffer-base-buffer))))
  9945. (_ nil))
  9946. (mapcar (lambda (s) (replace-regexp-in-string
  9947. "/" "\\/" s nil t))
  9948. (org-get-outline-path t t)))
  9949. "/"))))
  9950. (push (list target f re (org-refile-marker (point)))
  9951. tgs)))
  9952. (when (= (point) begin)
  9953. ;; Verification function has not moved point.
  9954. (end-of-line)))))))
  9955. (when org-refile-use-cache
  9956. (org-refile-cache-put tgs (buffer-file-name) descre))
  9957. (setq targets (append tgs targets))))))
  9958. (message "Getting targets...done")
  9959. (delete-dups (nreverse targets))))
  9960. (defun org--get-outline-path-1 (&optional use-cache)
  9961. "Return outline path to current headline.
  9962. Outline path is a list of strings, in reverse order. When
  9963. optional argument USE-CACHE is non-nil, make use of a cache. See
  9964. `org-get-outline-path' for details.
  9965. Assume buffer is widened and point is on a headline."
  9966. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9967. (let ((p (point))
  9968. (heading (let ((case-fold-search nil))
  9969. (looking-at org-complex-heading-regexp)
  9970. (if (not (match-end 4)) ""
  9971. ;; Remove statistics cookies.
  9972. (org-trim
  9973. (org-link-display-format
  9974. (replace-regexp-in-string
  9975. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9976. (match-string-no-properties 4))))))))
  9977. (if (org-up-heading-safe)
  9978. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9979. (when use-cache
  9980. (push (cons p path) org-outline-path-cache))
  9981. path)
  9982. ;; This is a new root node. Since we assume we are moving
  9983. ;; forward, we can drop previous cache so as to limit number
  9984. ;; of associations there.
  9985. (let ((path (list heading)))
  9986. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9987. path)))))
  9988. (defun org-get-outline-path (&optional with-self use-cache)
  9989. "Return the outline path to the current entry.
  9990. An outline path is a list of ancestors for current headline, as
  9991. a list of strings. Statistics cookies are removed and links are
  9992. replaced with their description, if any, or their path otherwise.
  9993. When optional argument WITH-SELF is non-nil, the path also
  9994. includes the current headline.
  9995. When optional argument USE-CACHE is non-nil, cache outline paths
  9996. between calls to this function so as to avoid backtracking. This
  9997. argument is useful when planning to find more than one outline
  9998. path in the same document. In that case, there are two
  9999. conditions to satisfy:
  10000. - `org-outline-path-cache' is set to nil before starting the
  10001. process;
  10002. - outline paths are computed by increasing buffer positions."
  10003. (org-with-wide-buffer
  10004. (and (or (and with-self (org-back-to-heading t))
  10005. (org-up-heading-safe))
  10006. (reverse (org--get-outline-path-1 use-cache)))))
  10007. (defun org-format-outline-path (path &optional width prefix separator)
  10008. "Format the outline path PATH for display.
  10009. WIDTH is the maximum number of characters that is available.
  10010. PREFIX is a prefix to be included in the returned string,
  10011. such as the file name.
  10012. SEPARATOR is inserted between the different parts of the path,
  10013. the default is \"/\"."
  10014. (setq width (or width 79))
  10015. (setq path (delq nil path))
  10016. (unless (> width 0)
  10017. (user-error "Argument `width' must be positive"))
  10018. (setq separator (or separator "/"))
  10019. (let* ((org-odd-levels-only nil)
  10020. (fpath (concat
  10021. prefix (and prefix path separator)
  10022. (mapconcat
  10023. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10024. (cl-loop for head in path
  10025. for n from 0
  10026. collect (org-add-props
  10027. head nil 'face
  10028. (nth (% n org-n-level-faces) org-level-faces)))
  10029. separator))))
  10030. (when (> (length fpath) width)
  10031. (if (< width 7)
  10032. ;; It's unlikely that `width' will be this small, but don't
  10033. ;; waste characters by adding ".." if it is.
  10034. (setq fpath (substring fpath 0 width))
  10035. (setf (substring fpath (- width 2)) "..")))
  10036. fpath))
  10037. (defun org-display-outline-path (&optional file current separator just-return-string)
  10038. "Display the current outline path in the echo area.
  10039. If FILE is non-nil, prepend the output with the file name.
  10040. If CURRENT is non-nil, append the current heading to the output.
  10041. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10042. the different parts of the path and defaults to \"/\".
  10043. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10044. (interactive "P")
  10045. (let* (case-fold-search
  10046. (bfn (buffer-file-name (buffer-base-buffer)))
  10047. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10048. res)
  10049. (when current (setq path (append path
  10050. (save-excursion
  10051. (org-back-to-heading t)
  10052. (when (looking-at org-complex-heading-regexp)
  10053. (list (match-string 4)))))))
  10054. (setq res
  10055. (org-format-outline-path
  10056. path
  10057. (1- (frame-width))
  10058. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10059. separator))
  10060. (if just-return-string
  10061. (org-no-properties res)
  10062. (org-unlogged-message "%s" res))))
  10063. (defvar org-refile-history nil
  10064. "History for refiling operations.")
  10065. (defvar org-after-refile-insert-hook nil
  10066. "Hook run after `org-refile' has inserted its stuff at the new location.
  10067. Note that this is still *before* the stuff will be removed from
  10068. the *old* location.")
  10069. (defvar org-capture-last-stored-marker)
  10070. (defvar org-refile-keep nil
  10071. "Non-nil means `org-refile' will copy instead of refile.")
  10072. (defun org-copy ()
  10073. "Like `org-refile', but copy."
  10074. (interactive)
  10075. (let ((org-refile-keep t))
  10076. (org-refile nil nil nil "Copy")))
  10077. (defun org-refile (&optional arg default-buffer rfloc msg)
  10078. "Move the entry or entries at point to another heading.
  10079. The list of target headings is compiled using the information in
  10080. `org-refile-targets', which see.
  10081. At the target location, the entry is filed as a subitem of the
  10082. target heading. Depending on `org-reverse-note-order', the new
  10083. subitem will either be the first or the last subitem.
  10084. If there is an active region, all entries in that region will be
  10085. refiled. However, the region must fulfill the requirement that
  10086. the first heading sets the top-level of the moved text.
  10087. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10088. location
  10089. and not actually move anything.
  10090. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10091. location where the last
  10092. refiling operation has put the subtree.
  10093. With a numeric prefix argument of `2', refile to the running clock.
  10094. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10095. being set to t and copy to the target location, don't move it.
  10096. Beware that keeping refiled entries may result in duplicated ID
  10097. properties.
  10098. RFLOC can be a refile location obtained in a different way.
  10099. MSG is a string to replace \"Refile\" in the default prompt with
  10100. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10101. See also `org-refile-use-outline-path'.
  10102. If you are using target caching (see `org-refile-use-cache'), you
  10103. have to clear the target cache in order to find new targets.
  10104. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10105. prefix argument (`C-u C-u C-u C-c C-w')."
  10106. (interactive "P")
  10107. (if (member arg '(0 (64)))
  10108. (org-refile-cache-clear)
  10109. (let* ((actionmsg (cond (msg msg)
  10110. ((equal arg 3) "Refile (and keep)")
  10111. (t "Refile")))
  10112. (regionp (org-region-active-p))
  10113. (region-start (and regionp (region-beginning)))
  10114. (region-end (and regionp (region-end)))
  10115. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10116. pos it nbuf file level reversed)
  10117. (setq last-command nil)
  10118. (when regionp
  10119. (goto-char region-start)
  10120. (or (bolp) (goto-char (point-at-bol)))
  10121. (setq region-start (point))
  10122. (unless (or (org-kill-is-subtree-p
  10123. (buffer-substring region-start region-end))
  10124. (prog1 org-refile-active-region-within-subtree
  10125. (let ((s (point-at-eol)))
  10126. (org-toggle-heading)
  10127. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10128. (user-error "The region is not a (sequence of) subtree(s)")))
  10129. (if (equal arg '(16))
  10130. (org-refile-goto-last-stored)
  10131. (when (or
  10132. (and (equal arg 2)
  10133. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10134. (prog1
  10135. (setq it (list (or org-clock-heading "running clock")
  10136. (buffer-file-name
  10137. (marker-buffer org-clock-hd-marker))
  10138. ""
  10139. (marker-position org-clock-hd-marker)))
  10140. (setq arg nil)))
  10141. (setq it
  10142. (or rfloc
  10143. (let (heading-text)
  10144. (save-excursion
  10145. (unless (and arg (listp arg))
  10146. (org-back-to-heading t)
  10147. (setq heading-text
  10148. (replace-regexp-in-string
  10149. org-bracket-link-regexp
  10150. "\\3"
  10151. (or (nth 4 (org-heading-components))
  10152. ""))))
  10153. (org-refile-get-location
  10154. (cond ((and arg (listp arg)) "Goto")
  10155. (regionp (concat actionmsg " region to"))
  10156. (t (concat actionmsg " subtree \""
  10157. heading-text "\" to")))
  10158. default-buffer
  10159. (and (not (equal '(4) arg))
  10160. org-refile-allow-creating-parent-nodes)))))))
  10161. (setq file (nth 1 it)
  10162. pos (nth 3 it))
  10163. (when (and (not arg)
  10164. pos
  10165. (equal (buffer-file-name) file)
  10166. (if regionp
  10167. (and (>= pos region-start)
  10168. (<= pos region-end))
  10169. (and (>= pos (point))
  10170. (< pos (save-excursion
  10171. (org-end-of-subtree t t))))))
  10172. (error "Cannot refile to position inside the tree or region"))
  10173. (setq nbuf (or (find-buffer-visiting file)
  10174. (find-file-noselect file)))
  10175. (if (and arg (not (equal arg 3)))
  10176. (progn
  10177. (pop-to-buffer-same-window nbuf)
  10178. (goto-char (cond (pos)
  10179. ((org-notes-order-reversed-p) (point-min))
  10180. (t (point-max))))
  10181. (org-show-context 'org-goto))
  10182. (if regionp
  10183. (progn
  10184. (org-kill-new (buffer-substring region-start region-end))
  10185. (org-save-markers-in-region region-start region-end))
  10186. (org-copy-subtree 1 nil t))
  10187. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10188. (find-file-noselect file)))
  10189. (setq reversed (org-notes-order-reversed-p))
  10190. (org-with-wide-buffer
  10191. (if pos
  10192. (progn
  10193. (goto-char pos)
  10194. (setq level (org-get-valid-level (funcall outline-level) 1))
  10195. (goto-char
  10196. (if reversed
  10197. (or (outline-next-heading) (point-max))
  10198. (or (save-excursion (org-get-next-sibling))
  10199. (org-end-of-subtree t t)
  10200. (point-max)))))
  10201. (setq level 1)
  10202. (if (not reversed)
  10203. (goto-char (point-max))
  10204. (goto-char (point-min))
  10205. (or (outline-next-heading) (goto-char (point-max)))))
  10206. (unless (bolp) (newline))
  10207. (org-paste-subtree level nil nil t)
  10208. (when org-log-refile
  10209. (org-add-log-setup 'refile nil nil org-log-refile)
  10210. (unless (eq org-log-refile 'note)
  10211. (save-excursion (org-add-log-note))))
  10212. (and org-auto-align-tags
  10213. (let ((org-loop-over-headlines-in-active-region nil))
  10214. (org-align-tags)))
  10215. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10216. :last-refile)))
  10217. (when bookmark-name
  10218. (with-demoted-errors
  10219. (bookmark-set bookmark-name))))
  10220. ;; If we are refiling for capture, make sure that the
  10221. ;; last-capture pointers point here
  10222. (when (bound-and-true-p org-capture-is-refiling)
  10223. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10224. :last-capture-marker)))
  10225. (when bookmark-name
  10226. (with-demoted-errors
  10227. (bookmark-set bookmark-name))))
  10228. (move-marker org-capture-last-stored-marker (point)))
  10229. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10230. (run-hooks 'org-after-refile-insert-hook)))
  10231. (unless org-refile-keep
  10232. (if regionp
  10233. (delete-region (point) (+ (point) (- region-end region-start)))
  10234. (org-preserve-local-variables
  10235. (delete-region
  10236. (and (org-back-to-heading t) (point))
  10237. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10238. (when (featurep 'org-inlinetask)
  10239. (org-inlinetask-remove-END-maybe))
  10240. (setq org-markers-to-move nil)
  10241. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10242. (defun org-refile-goto-last-stored ()
  10243. "Go to the location where the last refile was stored."
  10244. (interactive)
  10245. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10246. (message "This is the location of the last refile"))
  10247. (defun org-refile--get-location (refloc tbl)
  10248. "When user refile to REFLOC, find the associated target in TBL.
  10249. Also check `org-refile-target-table'."
  10250. (car (delq
  10251. nil
  10252. (mapcar
  10253. (lambda (r) (or (assoc r tbl)
  10254. (assoc r org-refile-target-table)))
  10255. (list (replace-regexp-in-string "/$" "" refloc)
  10256. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10257. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10258. "Prompt the user for a refile location, using PROMPT.
  10259. PROMPT should not be suffixed with a colon and a space, because
  10260. this function appends the default value from
  10261. `org-refile-history' automatically, if that is not empty."
  10262. (let ((org-refile-targets org-refile-targets)
  10263. (org-refile-use-outline-path org-refile-use-outline-path))
  10264. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10265. (unless org-refile-target-table
  10266. (user-error "No refile targets"))
  10267. (let* ((cbuf (current-buffer))
  10268. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10269. (cfunc (if (and org-refile-use-outline-path
  10270. org-outline-path-complete-in-steps)
  10271. #'org-olpath-completing-read
  10272. #'completing-read))
  10273. (extra (if org-refile-use-outline-path "/" ""))
  10274. (cbnex (concat (buffer-name) extra))
  10275. (filename (and cfn (expand-file-name cfn)))
  10276. (tbl (mapcar
  10277. (lambda (x)
  10278. (if (and (not (member org-refile-use-outline-path
  10279. '(file full-file-path)))
  10280. (not (equal filename (nth 1 x))))
  10281. (cons (concat (car x) extra " ("
  10282. (file-name-nondirectory (nth 1 x)) ")")
  10283. (cdr x))
  10284. (cons (concat (car x) extra) (cdr x))))
  10285. org-refile-target-table))
  10286. (completion-ignore-case t)
  10287. cdef
  10288. (prompt (concat prompt
  10289. (or (and (car org-refile-history)
  10290. (concat " (default " (car org-refile-history) ")"))
  10291. (and (assoc cbnex tbl) (setq cdef cbnex)
  10292. (concat " (default " cbnex ")"))) ": "))
  10293. pa answ parent-target child parent old-hist)
  10294. (setq old-hist org-refile-history)
  10295. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10296. nil 'org-refile-history (or cdef (car org-refile-history))))
  10297. (if (setq pa (org-refile--get-location answ tbl))
  10298. (progn
  10299. (org-refile-check-position pa)
  10300. (when (or (not org-refile-history)
  10301. (not (eq old-hist org-refile-history))
  10302. (not (equal (car pa) (car org-refile-history))))
  10303. (setq org-refile-history
  10304. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10305. org-refile-history
  10306. (cdr org-refile-history))))
  10307. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10308. (pop org-refile-history)))
  10309. pa)
  10310. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10311. (progn
  10312. (setq parent (match-string 1 answ)
  10313. child (match-string 2 answ))
  10314. (setq parent-target (org-refile--get-location parent tbl))
  10315. (when (and parent-target
  10316. (or (eq new-nodes t)
  10317. (and (eq new-nodes 'confirm)
  10318. (y-or-n-p (format "Create new node \"%s\"? "
  10319. child)))))
  10320. (org-refile-new-child parent-target child)))
  10321. (user-error "Invalid target location")))))
  10322. (declare-function org-string-nw-p "org-macs" (s))
  10323. (defun org-refile-check-position (refile-pointer)
  10324. "Check if the refile pointer matches the headline to which it points."
  10325. (let* ((file (nth 1 refile-pointer))
  10326. (re (nth 2 refile-pointer))
  10327. (pos (nth 3 refile-pointer))
  10328. buffer)
  10329. (if (and (not (markerp pos)) (not file))
  10330. (user-error "Please indicate a target file in the refile path")
  10331. (when (org-string-nw-p re)
  10332. (setq buffer (if (markerp pos)
  10333. (marker-buffer pos)
  10334. (or (find-buffer-visiting file)
  10335. (find-file-noselect file))))
  10336. (with-current-buffer buffer
  10337. (org-with-wide-buffer
  10338. (goto-char pos)
  10339. (beginning-of-line 1)
  10340. (unless (looking-at-p re)
  10341. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10342. (defun org-refile-new-child (parent-target child)
  10343. "Use refile target PARENT-TARGET to add new CHILD below it."
  10344. (unless parent-target
  10345. (error "Cannot find parent for new node"))
  10346. (let ((file (nth 1 parent-target))
  10347. (pos (nth 3 parent-target))
  10348. level)
  10349. (with-current-buffer (or (find-buffer-visiting file)
  10350. (find-file-noselect file))
  10351. (org-with-wide-buffer
  10352. (if pos
  10353. (goto-char pos)
  10354. (goto-char (point-max))
  10355. (unless (bolp) (newline)))
  10356. (when (looking-at org-outline-regexp)
  10357. (setq level (funcall outline-level))
  10358. (org-end-of-subtree t t))
  10359. (org-back-over-empty-lines)
  10360. (insert "\n" (make-string
  10361. (if pos (org-get-valid-level level 1) 1) ?*)
  10362. " " child "\n")
  10363. (beginning-of-line 0)
  10364. (list (concat (car parent-target) "/" child) file "" (point))))))
  10365. (defun org-olpath-completing-read (prompt collection &rest args)
  10366. "Read an outline path like a file name."
  10367. (let ((thetable collection))
  10368. (apply #'completing-read
  10369. prompt
  10370. (lambda (string predicate &optional flag)
  10371. (cond
  10372. ((eq flag nil) (try-completion string thetable))
  10373. ((eq flag t)
  10374. (let ((l (length string)))
  10375. (mapcar (lambda (x)
  10376. (let ((r (substring x l))
  10377. (f (if (string-match " ([^)]*)$" x)
  10378. (match-string 0 x)
  10379. "")))
  10380. (if (string-match "/" r)
  10381. (concat string (substring r 0 (match-end 0)) f)
  10382. x)))
  10383. (all-completions string thetable predicate))))
  10384. ;; Exact match?
  10385. ((eq flag 'lambda) (assoc string thetable))))
  10386. args)))
  10387. ;;;; Dynamic blocks
  10388. (defun org-find-dblock (name)
  10389. "Find the first dynamic block with name NAME in the buffer.
  10390. If not found, stay at current position and return nil."
  10391. (let ((case-fold-search t) pos)
  10392. (save-excursion
  10393. (goto-char (point-min))
  10394. (setq pos (and (re-search-forward
  10395. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10396. (match-beginning 0))))
  10397. (when pos (goto-char pos))
  10398. pos))
  10399. (defun org-create-dblock (plist)
  10400. "Create a dynamic block section, with parameters taken from PLIST.
  10401. PLIST must contain a :name entry which is used as the name of the block."
  10402. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10403. (end-of-line 1)
  10404. (newline))
  10405. (let ((col (current-column))
  10406. (name (plist-get plist :name)))
  10407. (insert "#+BEGIN: " name)
  10408. (while plist
  10409. (if (eq (car plist) :name)
  10410. (setq plist (cddr plist))
  10411. (insert " " (prin1-to-string (pop plist)))))
  10412. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10413. (beginning-of-line -2)))
  10414. (defun org-prepare-dblock ()
  10415. "Prepare dynamic block for refresh.
  10416. This empties the block, puts the cursor at the insert position and returns
  10417. the property list including an extra property :name with the block name."
  10418. (unless (looking-at org-dblock-start-re)
  10419. (user-error "Not at a dynamic block"))
  10420. (let* ((begdel (1+ (match-end 0)))
  10421. (name (org-no-properties (match-string 1)))
  10422. (params (append (list :name name)
  10423. (read (concat "(" (match-string 3) ")")))))
  10424. (save-excursion
  10425. (beginning-of-line 1)
  10426. (skip-chars-forward " \t")
  10427. (setq params (plist-put params :indentation-column (current-column))))
  10428. (unless (re-search-forward org-dblock-end-re nil t)
  10429. (error "Dynamic block not terminated"))
  10430. (setq params
  10431. (append params
  10432. (list :content (buffer-substring
  10433. begdel (match-beginning 0)))))
  10434. (delete-region begdel (match-beginning 0))
  10435. (goto-char begdel)
  10436. (open-line 1)
  10437. params))
  10438. (defun org-map-dblocks (&optional command)
  10439. "Apply COMMAND to all dynamic blocks in the current buffer.
  10440. If COMMAND is not given, use `org-update-dblock'."
  10441. (let ((cmd (or command 'org-update-dblock)))
  10442. (save-excursion
  10443. (goto-char (point-min))
  10444. (while (re-search-forward org-dblock-start-re nil t)
  10445. (goto-char (match-beginning 0))
  10446. (save-excursion
  10447. (condition-case nil
  10448. (funcall cmd)
  10449. (error (message "Error during update of dynamic block"))))
  10450. (unless (re-search-forward org-dblock-end-re nil t)
  10451. (error "Dynamic block not terminated"))))))
  10452. (defun org-dblock-update (&optional arg)
  10453. "User command for updating dynamic blocks.
  10454. Update the dynamic block at point. With prefix ARG, update all dynamic
  10455. blocks in the buffer."
  10456. (interactive "P")
  10457. (if arg
  10458. (org-update-all-dblocks)
  10459. (or (looking-at org-dblock-start-re)
  10460. (org-beginning-of-dblock))
  10461. (org-update-dblock)))
  10462. (defun org-update-dblock ()
  10463. "Update the dynamic block at point.
  10464. This means to empty the block, parse for parameters and then call
  10465. the correct writing function."
  10466. (interactive)
  10467. (save-excursion
  10468. (let* ((win (selected-window))
  10469. (pos (point))
  10470. (line (org-current-line))
  10471. (params (org-prepare-dblock))
  10472. (name (plist-get params :name))
  10473. (indent (plist-get params :indentation-column))
  10474. (cmd (intern (concat "org-dblock-write:" name))))
  10475. (message "Updating dynamic block `%s' at line %d..." name line)
  10476. (funcall cmd params)
  10477. (message "Updating dynamic block `%s' at line %d...done" name line)
  10478. (goto-char pos)
  10479. (when (and indent (> indent 0))
  10480. (setq indent (make-string indent ?\ ))
  10481. (save-excursion
  10482. (select-window win)
  10483. (org-beginning-of-dblock)
  10484. (forward-line 1)
  10485. (while (not (looking-at org-dblock-end-re))
  10486. (insert indent)
  10487. (beginning-of-line 2))
  10488. (when (looking-at org-dblock-end-re)
  10489. (and (looking-at "[ \t]+")
  10490. (replace-match ""))
  10491. (insert indent)))))))
  10492. (defun org-beginning-of-dblock ()
  10493. "Find the beginning of the dynamic block at point.
  10494. Error if there is no such block at point."
  10495. (let ((pos (point))
  10496. beg)
  10497. (end-of-line 1)
  10498. (if (and (re-search-backward org-dblock-start-re nil t)
  10499. (setq beg (match-beginning 0))
  10500. (re-search-forward org-dblock-end-re nil t)
  10501. (> (match-end 0) pos))
  10502. (goto-char beg)
  10503. (goto-char pos)
  10504. (error "Not in a dynamic block"))))
  10505. (defun org-update-all-dblocks ()
  10506. "Update all dynamic blocks in the buffer.
  10507. This function can be used in a hook."
  10508. (interactive)
  10509. (when (derived-mode-p 'org-mode)
  10510. (org-map-dblocks 'org-update-dblock)))
  10511. ;;;; Completion
  10512. (declare-function org-export-backend-options "ox" (cl-x) t)
  10513. (defun org-get-export-keywords ()
  10514. "Return a list of all currently understood export keywords.
  10515. Export keywords include options, block names, attributes and
  10516. keywords relative to each registered export back-end."
  10517. (let (keywords)
  10518. (dolist (backend
  10519. (bound-and-true-p org-export-registered-backends)
  10520. (delq nil keywords))
  10521. ;; Back-end name (for keywords, like #+LATEX:)
  10522. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10523. (dolist (option-entry (org-export-backend-options backend))
  10524. ;; Back-end options.
  10525. (push (nth 1 option-entry) keywords)))))
  10526. (defconst org-options-keywords
  10527. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10528. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10529. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10530. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10531. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10532. (defcustom org-structure-template-alist
  10533. '(("a" . "export ascii")
  10534. ("c" . "center")
  10535. ("C" . "comment")
  10536. ("e" . "example")
  10537. ("E" . "export")
  10538. ("h" . "export html")
  10539. ("l" . "export latex")
  10540. ("q" . "quote")
  10541. ("s" . "src")
  10542. ("v" . "verse"))
  10543. "An alist of keys and block types.
  10544. `org-insert-structure-template' will display a menu with this
  10545. list of templates to choose from. The block type is inserted,
  10546. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  10547. The menu keys are defined by the car of each entry in this alist.
  10548. If two entries have the keys \"a\" and \"aa\" respectively, the
  10549. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10550. latter will be inserted by typing \"aa\". If an entry with the
  10551. key \"aab\" is later added, it can be inserted by typing \"ab\".
  10552. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10553. block can be inserted by pressing TAB after the string \"<KEY\"."
  10554. :group 'org-edit-structure
  10555. :type '(repeat
  10556. (cons (string :tag "Key")
  10557. (string :tag "Template")))
  10558. :package-version '(Org . "9.2"))
  10559. (defun org--check-org-structure-template-alist (&optional checklist)
  10560. "Check whether `org-structure-template-alist' is set up correctly.
  10561. In particular, check if the Org 9.2 format is used as opposed to
  10562. previous format.
  10563. "
  10564. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  10565. (or (eval checklist)
  10566. org-structure-template-alist))))
  10567. (when elm
  10568. (org-display-warning
  10569. (format "
  10570. Please update the entries of `%s'.
  10571. In Org 9.2 the format was changed from something like
  10572. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  10573. to something like
  10574. (\"s\" . \"src\")
  10575. Please refer to the documentation of `org-structure-template-alist'.
  10576. The following entries must be updated:
  10577. %s"
  10578. (or checklist 'org-structure-template-alist)
  10579. (pp-to-string elm))))))
  10580. (defun org--insert-structure-template-mks ()
  10581. "Present `org-structure-template-alist' with `org-mks'.
  10582. Menus are added if keys require more than one keystroke. Tabs
  10583. are added to single key entries when more than one stroke is
  10584. needed. Keys longer than two characters are reduced to two
  10585. characters."
  10586. (org--check-org-structure-template-alist)
  10587. (let* (case-fold-search
  10588. (templates (append org-structure-template-alist
  10589. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10590. (keys (mapcar #'car templates))
  10591. (start-letters
  10592. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10593. ;; Sort each element of `org-structure-template-alist' into
  10594. ;; sublists according to the first letter.
  10595. (superlist
  10596. (mapcar (lambda (letter)
  10597. (list letter
  10598. (cl-remove-if-not
  10599. (apply-partially #'string-match-p (concat "^" letter))
  10600. templates :key #'car)))
  10601. start-letters)))
  10602. (org-mks
  10603. (apply #'append
  10604. ;; Make an `org-mks' table. If only one element is
  10605. ;; present in a sublist, make it part of the top-menu,
  10606. ;; otherwise make a submenu according to the starting
  10607. ;; letter and populate it.
  10608. (mapcar (lambda (sublist)
  10609. (if (eq 1 (length (cadr sublist)))
  10610. (mapcar (lambda (elm)
  10611. (list (substring (car elm) 0 1)
  10612. (cdr elm) ""))
  10613. (cadr sublist))
  10614. ;; Create submenu.
  10615. (let* ((topkey (car sublist))
  10616. (elms (cadr sublist))
  10617. (keys (mapcar #'car elms))
  10618. (long (> (length elms) 3)))
  10619. (append
  10620. (list
  10621. ;; Make a description of the submenu.
  10622. (list topkey
  10623. (concat
  10624. (mapconcat #'cdr
  10625. (cl-subseq elms 0 (if long 3 (length elms)))
  10626. ", ")
  10627. (when long ", ..."))))
  10628. ;; List of entries in submenu.
  10629. (cl-mapcar #'list
  10630. (org--insert-structure-template-unique-keys keys)
  10631. (mapcar #'cdr elms)
  10632. (make-list (length elms) ""))))))
  10633. superlist))
  10634. "Select a key\n============"
  10635. "Key: ")))
  10636. (defun org--insert-structure-template-unique-keys (keys)
  10637. "Make a list of unique, two characters long elements from KEYS.
  10638. Elements of length one have a tab appended. Elements of length
  10639. two are kept as is. Longer elements are truncated to length two.
  10640. If an element cannot be made unique, an error is raised."
  10641. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10642. menu-keys)
  10643. (dolist (key orderd-keys)
  10644. (let ((potential-key
  10645. (cl-case (length key)
  10646. (1 (concat key "\t"))
  10647. (2 key)
  10648. (otherwise
  10649. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10650. (mapcar (apply-partially #'concat (substring key 0 1))
  10651. (split-string (substring key 1) "" t)))))))
  10652. (if (or (not potential-key) (assoc potential-key menu-keys))
  10653. (user-error "Could not make unique key for %s." key)
  10654. (push (cons potential-key key) menu-keys))))
  10655. (mapcar #'car
  10656. (cl-sort menu-keys #'<
  10657. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10658. (defun org-insert-structure-template (type)
  10659. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10660. Select a block from `org-structure-template-alist' then type
  10661. either RET, TAB or SPC to write the block type. With an active
  10662. region, wrap the region in the block. Otherwise, insert an empty
  10663. block."
  10664. (interactive
  10665. (list (pcase (org--insert-structure-template-mks)
  10666. (`("\t" . ,_) (read-string "Structure type: "))
  10667. (`(,_ ,choice . ,_) choice))))
  10668. (let* ((region? (use-region-p))
  10669. (region-start (and region? (region-beginning)))
  10670. (region-end (and region? (copy-marker (region-end))))
  10671. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  10672. (verbatim? (string-match-p
  10673. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10674. type)))
  10675. (when region? (goto-char region-start))
  10676. (let ((column (current-indentation)))
  10677. (if (save-excursion (skip-chars-backward " \t") (bolp))
  10678. (beginning-of-line)
  10679. (insert "\n"))
  10680. (save-excursion
  10681. (indent-to column)
  10682. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  10683. (when region?
  10684. (when verbatim? (org-escape-code-in-region (point) region-end))
  10685. (goto-char region-end)
  10686. ;; Ignore empty lines at the end of the region.
  10687. (skip-chars-backward " \r\t\n")
  10688. (end-of-line))
  10689. (unless (bolp) (insert "\n"))
  10690. (indent-to column)
  10691. (insert (format "#+end_%s" (car (split-string type))))
  10692. (if (looking-at "[ \t]*$") (replace-match "")
  10693. (insert "\n"))
  10694. (when (and (eobp) (not (bolp))) (insert "\n")))
  10695. (if extended? (end-of-line)
  10696. (forward-line)
  10697. (skip-chars-forward " \t")))))
  10698. ;;;; TODO, DEADLINE, Comments
  10699. (defun org-toggle-comment ()
  10700. "Change the COMMENT state of an entry."
  10701. (interactive)
  10702. (save-excursion
  10703. (org-back-to-heading)
  10704. (let ((case-fold-search nil))
  10705. (looking-at org-complex-heading-regexp))
  10706. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10707. (skip-chars-forward " \t")
  10708. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10709. (if (org-in-commented-heading-p t)
  10710. (delete-region (point)
  10711. (progn (search-forward " " (line-end-position) 'move)
  10712. (skip-chars-forward " \t")
  10713. (point)))
  10714. (insert org-comment-string)
  10715. (unless (eolp) (insert " ")))))
  10716. (defvar org-last-todo-state-is-todo nil
  10717. "This is non-nil when the last TODO state change led to a TODO state.
  10718. If the last change removed the TODO tag or switched to DONE, then
  10719. this is nil.")
  10720. (defvar org-todo-setup-filter-hook nil
  10721. "Hook for functions that pre-filter todo specs.
  10722. Each function takes a todo spec and returns either nil or the spec
  10723. transformed into canonical form." )
  10724. (defvar org-todo-get-default-hook nil
  10725. "Hook for functions that get a default item for todo.
  10726. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10727. nil or a string to be used for the todo mark." )
  10728. (defvar org-agenda-headline-snapshot-before-repeat)
  10729. (defun org-current-effective-time ()
  10730. "Return current time adjusted for `org-extend-today-until' variable."
  10731. (let* ((ct (org-current-time))
  10732. (dct (decode-time ct))
  10733. (ct1
  10734. (cond
  10735. (org-use-last-clock-out-time-as-effective-time
  10736. (or (org-clock-get-last-clock-out-time) ct))
  10737. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10738. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10739. (t ct))))
  10740. ct1))
  10741. (defun org-todo-yesterday (&optional arg)
  10742. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10743. (interactive "P")
  10744. (if (eq major-mode 'org-agenda-mode)
  10745. (apply 'org-agenda-todo-yesterday arg)
  10746. (let* ((org-use-effective-time t)
  10747. (hour (nth 2 (decode-time (org-current-time))))
  10748. (org-extend-today-until (1+ hour)))
  10749. (org-todo arg))))
  10750. (defvar org-block-entry-blocking ""
  10751. "First entry preventing the TODO state change.")
  10752. (defun org-cancel-repeater ()
  10753. "Cancel a repeater by setting its numeric value to zero."
  10754. (interactive)
  10755. (save-excursion
  10756. (org-back-to-heading t)
  10757. (let ((bound1 (point))
  10758. (bound0 (save-excursion (outline-next-heading) (point))))
  10759. (when (and (re-search-forward
  10760. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10761. org-deadline-time-regexp "\\)\\|\\("
  10762. org-ts-regexp "\\)")
  10763. bound0 t)
  10764. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10765. bound1 t))
  10766. (replace-match "0" t nil nil 1)))))
  10767. (defvar org-state)
  10768. (defvar org-blocked-by-checkboxes)
  10769. (defun org-todo (&optional arg)
  10770. "Change the TODO state of an item.
  10771. The state of an item is given by a keyword at the start of the heading,
  10772. like
  10773. *** TODO Write paper
  10774. *** DONE Call mom
  10775. The different keywords are specified in the variable `org-todo-keywords'.
  10776. By default the available states are \"TODO\" and \"DONE\". So, for this
  10777. example: when the item starts with TODO, it is changed to DONE.
  10778. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10779. DONE are present, add TODO at the beginning of the heading.
  10780. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10781. state.
  10782. With numeric prefix ARG, switch to that state.
  10783. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10784. next set of TODO \
  10785. keywords (nextset).
  10786. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10787. prefix, circumvent any state blocking.
  10788. With a numeric prefix arg of 0, inhibit note taking for the change.
  10789. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10790. When called through ELisp, arg is also interpreted in the following way:
  10791. `none' -> empty state
  10792. \"\" -> switch to empty state
  10793. `done' -> switch to DONE
  10794. `nextset' -> switch to the next set of keywords
  10795. `previousset' -> switch to the previous set of keywords
  10796. \"WAITING\" -> switch to the specified keyword, but only if it
  10797. really is a member of `org-todo-keywords'."
  10798. (interactive "P")
  10799. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10800. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10801. 'region-start-level 'region))
  10802. org-loop-over-headlines-in-active-region)
  10803. (org-map-entries
  10804. `(org-todo ,arg)
  10805. org-loop-over-headlines-in-active-region
  10806. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10807. (when (equal arg '(16)) (setq arg 'nextset))
  10808. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10809. (let ((org-blocker-hook org-blocker-hook)
  10810. commentp
  10811. case-fold-search)
  10812. (when (equal arg '(64))
  10813. (setq arg nil org-blocker-hook nil))
  10814. (when (and org-blocker-hook
  10815. (or org-inhibit-blocking
  10816. (org-entry-get nil "NOBLOCKING")))
  10817. (setq org-blocker-hook nil))
  10818. (save-excursion
  10819. (catch 'exit
  10820. (org-back-to-heading t)
  10821. (when (org-in-commented-heading-p t)
  10822. (org-toggle-comment)
  10823. (setq commentp t))
  10824. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10825. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10826. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10827. (let* ((match-data (match-data))
  10828. (startpos (copy-marker (line-beginning-position)))
  10829. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10830. (org-log-done org-log-done)
  10831. (org-log-repeat org-log-repeat)
  10832. (org-todo-log-states org-todo-log-states)
  10833. (org-inhibit-logging
  10834. (if (equal arg 0)
  10835. (progn (setq arg nil) 'note) org-inhibit-logging))
  10836. (this (match-string 1))
  10837. (hl-pos (match-beginning 0))
  10838. (head (org-get-todo-sequence-head this))
  10839. (ass (assoc head org-todo-kwd-alist))
  10840. (interpret (nth 1 ass))
  10841. (done-word (nth 3 ass))
  10842. (final-done-word (nth 4 ass))
  10843. (org-last-state (or this ""))
  10844. (completion-ignore-case t)
  10845. (member (member this org-todo-keywords-1))
  10846. (tail (cdr member))
  10847. (org-state (cond
  10848. ((and org-todo-key-trigger
  10849. (or (and (equal arg '(4))
  10850. (eq org-use-fast-todo-selection 'prefix))
  10851. (and (not arg) org-use-fast-todo-selection
  10852. (not (eq org-use-fast-todo-selection
  10853. 'prefix)))))
  10854. ;; Use fast selection.
  10855. (org-fast-todo-selection))
  10856. ((and (equal arg '(4))
  10857. (or (not org-use-fast-todo-selection)
  10858. (not org-todo-key-trigger)))
  10859. ;; Read a state with completion.
  10860. (completing-read
  10861. "State: " (mapcar #'list org-todo-keywords-1)
  10862. nil t))
  10863. ((eq arg 'right)
  10864. (if this
  10865. (if tail (car tail) nil)
  10866. (car org-todo-keywords-1)))
  10867. ((eq arg 'left)
  10868. (unless (equal member org-todo-keywords-1)
  10869. (if this
  10870. (nth (- (length org-todo-keywords-1)
  10871. (length tail) 2)
  10872. org-todo-keywords-1)
  10873. (org-last org-todo-keywords-1))))
  10874. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10875. (setq arg nil))) ;hack to fall back to cycling
  10876. (arg
  10877. ;; User or caller requests a specific state.
  10878. (cond
  10879. ((equal arg "") nil)
  10880. ((eq arg 'none) nil)
  10881. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10882. ((eq arg 'nextset)
  10883. (or (car (cdr (member head org-todo-heads)))
  10884. (car org-todo-heads)))
  10885. ((eq arg 'previousset)
  10886. (let ((org-todo-heads (reverse org-todo-heads)))
  10887. (or (car (cdr (member head org-todo-heads)))
  10888. (car org-todo-heads))))
  10889. ((car (member arg org-todo-keywords-1)))
  10890. ((stringp arg)
  10891. (user-error "State `%s' not valid in this file" arg))
  10892. ((nth (1- (prefix-numeric-value arg))
  10893. org-todo-keywords-1))))
  10894. ((null member) (or head (car org-todo-keywords-1)))
  10895. ((equal this final-done-word) nil) ;-> make empty
  10896. ((null tail) nil) ;-> first entry
  10897. ((memq interpret '(type priority))
  10898. (if (eq this-command last-command)
  10899. (car tail)
  10900. (if (> (length tail) 0)
  10901. (or done-word (car org-done-keywords))
  10902. nil)))
  10903. (t
  10904. (car tail))))
  10905. (org-state (or
  10906. (run-hook-with-args-until-success
  10907. 'org-todo-get-default-hook org-state org-last-state)
  10908. org-state))
  10909. (next (if org-state (concat " " org-state " ") " "))
  10910. (change-plist (list :type 'todo-state-change :from this :to org-state
  10911. :position startpos))
  10912. dolog now-done-p)
  10913. (when org-blocker-hook
  10914. (let (org-blocked-by-checkboxes block-reason)
  10915. (setq org-last-todo-state-is-todo
  10916. (not (member this org-done-keywords)))
  10917. (unless (save-excursion
  10918. (save-match-data
  10919. (org-with-wide-buffer
  10920. (run-hook-with-args-until-failure
  10921. 'org-blocker-hook change-plist))))
  10922. (setq block-reason (if org-blocked-by-checkboxes
  10923. "contained checkboxes"
  10924. (format "\"%s\"" org-block-entry-blocking)))
  10925. (if (called-interactively-p 'interactive)
  10926. (user-error "TODO state change from %s to %s blocked (by %s)"
  10927. this org-state block-reason)
  10928. ;; Fail silently.
  10929. (message "TODO state change from %s to %s blocked (by %s)"
  10930. this org-state block-reason)
  10931. (throw 'exit nil)))))
  10932. (store-match-data match-data)
  10933. (replace-match next t t)
  10934. (cond ((equal this org-state)
  10935. (message "TODO state was already %s" (org-trim next)))
  10936. ((not (pos-visible-in-window-p hl-pos))
  10937. (message "TODO state changed to %s" (org-trim next))))
  10938. (unless head
  10939. (setq head (org-get-todo-sequence-head org-state)
  10940. ass (assoc head org-todo-kwd-alist)
  10941. interpret (nth 1 ass)
  10942. done-word (nth 3 ass)
  10943. final-done-word (nth 4 ass)))
  10944. (when (memq arg '(nextset previousset))
  10945. (message "Keyword-Set %d/%d: %s"
  10946. (- (length org-todo-sets) -1
  10947. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10948. (length org-todo-sets)
  10949. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10950. (setq org-last-todo-state-is-todo
  10951. (not (member org-state org-done-keywords)))
  10952. (setq now-done-p (and (member org-state org-done-keywords)
  10953. (not (member this org-done-keywords))))
  10954. (and logging (org-local-logging logging))
  10955. (when (and (or org-todo-log-states org-log-done)
  10956. (not (eq org-inhibit-logging t))
  10957. (not (memq arg '(nextset previousset))))
  10958. ;; We need to look at recording a time and note.
  10959. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10960. (nth 2 (assoc this org-todo-log-states))))
  10961. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10962. (setq dolog 'time))
  10963. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10964. (and org-state
  10965. (member org-state org-not-done-keywords)
  10966. (not (member this org-not-done-keywords))))
  10967. ;; This is now a todo state and was not one before
  10968. ;; If there was a CLOSED time stamp, get rid of it.
  10969. (org-add-planning-info nil nil 'closed))
  10970. (when (and now-done-p org-log-done)
  10971. ;; It is now done, and it was not done before.
  10972. (org-add-planning-info 'closed (org-current-effective-time))
  10973. (when (and (not dolog) (eq 'note org-log-done))
  10974. (org-add-log-setup 'done org-state this 'note)))
  10975. (when (and org-state dolog)
  10976. ;; This is a non-nil state, and we need to log it.
  10977. (org-add-log-setup 'state org-state this dolog)))
  10978. ;; Fixup tag positioning.
  10979. (org-todo-trigger-tag-changes org-state)
  10980. (when org-auto-align-tags (org-align-tags))
  10981. (when org-provide-todo-statistics
  10982. (org-update-parent-todo-statistics))
  10983. (run-hooks 'org-after-todo-state-change-hook)
  10984. (when (and arg (not (member org-state org-done-keywords)))
  10985. (setq head (org-get-todo-sequence-head org-state)))
  10986. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10987. ;; Do we need to trigger a repeat?
  10988. (when now-done-p
  10989. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10990. ;; This is for the agenda, take a snapshot of the headline.
  10991. (save-match-data
  10992. (setq org-agenda-headline-snapshot-before-repeat
  10993. (org-get-heading))))
  10994. (org-auto-repeat-maybe org-state))
  10995. ;; Fixup cursor location if close to the keyword.
  10996. (when (and (outline-on-heading-p)
  10997. (not (bolp))
  10998. (save-excursion (beginning-of-line 1)
  10999. (looking-at org-todo-line-regexp))
  11000. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11001. (goto-char (or (match-end 2) (match-end 1)))
  11002. (and (looking-at " ") (just-one-space)))
  11003. (when org-trigger-hook
  11004. (save-excursion
  11005. (run-hook-with-args 'org-trigger-hook change-plist)))
  11006. (when commentp (org-toggle-comment))))))))
  11007. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11008. "Block turning an entry into a TODO, using the hierarchy.
  11009. This checks whether the current task should be blocked from state
  11010. changes. Such blocking occurs when:
  11011. 1. The task has children which are not all in a completed state.
  11012. 2. A task has a parent with the property :ORDERED:, and there
  11013. are siblings prior to the current task with incomplete
  11014. status.
  11015. 3. The parent of the task is blocked because it has siblings that should
  11016. be done first, or is child of a block grandparent TODO entry."
  11017. (if (not org-enforce-todo-dependencies)
  11018. t ; if locally turned off don't block
  11019. (catch 'dont-block
  11020. ;; If this is not a todo state change, or if this entry is already DONE,
  11021. ;; do not block
  11022. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11023. (member (plist-get change-plist :from)
  11024. (cons 'done org-done-keywords))
  11025. (member (plist-get change-plist :to)
  11026. (cons 'todo org-not-done-keywords))
  11027. (not (plist-get change-plist :to)))
  11028. (throw 'dont-block t))
  11029. ;; If this task has children, and any are undone, it's blocked
  11030. (save-excursion
  11031. (org-back-to-heading t)
  11032. (let ((this-level (funcall outline-level)))
  11033. (outline-next-heading)
  11034. (let ((child-level (funcall outline-level)))
  11035. (while (and (not (eobp))
  11036. (> child-level this-level))
  11037. ;; this todo has children, check whether they are all
  11038. ;; completed
  11039. (when (and (not (org-entry-is-done-p))
  11040. (org-entry-is-todo-p))
  11041. (setq org-block-entry-blocking (org-get-heading))
  11042. (throw 'dont-block nil))
  11043. (outline-next-heading)
  11044. (setq child-level (funcall outline-level))))))
  11045. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11046. ;; any previous siblings are undone, it's blocked
  11047. (save-excursion
  11048. (org-back-to-heading t)
  11049. (let* ((pos (point))
  11050. (parent-pos (and (org-up-heading-safe) (point)))
  11051. (case-fold-search nil))
  11052. (unless parent-pos (throw 'dont-block t)) ; no parent
  11053. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11054. (forward-line 1)
  11055. (re-search-forward org-not-done-heading-regexp pos t))
  11056. (setq org-block-entry-blocking (match-string 0))
  11057. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11058. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11059. (while t
  11060. (goto-char parent-pos)
  11061. (unless (looking-at org-not-done-heading-regexp)
  11062. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11063. (setq pos (point))
  11064. (setq parent-pos (and (org-up-heading-safe) (point)))
  11065. (unless parent-pos (throw 'dont-block t)) ; no parent
  11066. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11067. (forward-line 1)
  11068. (re-search-forward org-not-done-heading-regexp pos t)
  11069. (setq org-block-entry-blocking (org-get-heading)))
  11070. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11071. (defcustom org-track-ordered-property-with-tag nil
  11072. "Should the ORDERED property also be shown as a tag?
  11073. The ORDERED property decides if an entry should require subtasks to be
  11074. completed in sequence. Since a property is not very visible, setting
  11075. this option means that toggling the ORDERED property with the command
  11076. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11077. not relevant for the behavior, but it makes things more visible.
  11078. Note that toggling the tag with tags commands will not change the property
  11079. and therefore not influence behavior!
  11080. This can be t, meaning the tag ORDERED should be used, It can also be a
  11081. string to select a different tag for this task."
  11082. :group 'org-todo
  11083. :type '(choice
  11084. (const :tag "No tracking" nil)
  11085. (const :tag "Track with ORDERED tag" t)
  11086. (string :tag "Use other tag")))
  11087. (defun org-toggle-ordered-property ()
  11088. "Toggle the ORDERED property of the current entry.
  11089. For better visibility, you can track the value of this property with a tag.
  11090. See variable `org-track-ordered-property-with-tag'."
  11091. (interactive)
  11092. (let* ((t1 org-track-ordered-property-with-tag)
  11093. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11094. (save-excursion
  11095. (org-back-to-heading)
  11096. (if (org-entry-get nil "ORDERED")
  11097. (progn
  11098. (org-delete-property "ORDERED")
  11099. (and tag (org-toggle-tag tag 'off))
  11100. (message "Subtasks can be completed in arbitrary order"))
  11101. (org-entry-put nil "ORDERED" "t")
  11102. (and tag (org-toggle-tag tag 'on))
  11103. (message "Subtasks must be completed in sequence")))))
  11104. (defun org-block-todo-from-checkboxes (change-plist)
  11105. "Block turning an entry into a TODO, using checkboxes.
  11106. This checks whether the current task should be blocked from state
  11107. changes because there are unchecked boxes in this entry."
  11108. (if (not org-enforce-todo-checkbox-dependencies)
  11109. t ; if locally turned off don't block
  11110. (catch 'dont-block
  11111. ;; If this is not a todo state change, or if this entry is already DONE,
  11112. ;; do not block
  11113. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11114. (member (plist-get change-plist :from)
  11115. (cons 'done org-done-keywords))
  11116. (member (plist-get change-plist :to)
  11117. (cons 'todo org-not-done-keywords))
  11118. (not (plist-get change-plist :to)))
  11119. (throw 'dont-block t))
  11120. ;; If this task has checkboxes that are not checked, it's blocked
  11121. (save-excursion
  11122. (org-back-to-heading t)
  11123. (let ((beg (point)) end)
  11124. (outline-next-heading)
  11125. (setq end (point))
  11126. (goto-char beg)
  11127. (when (org-list-search-forward
  11128. (concat (org-item-beginning-re)
  11129. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11130. "\\[[- ]\\]")
  11131. end t)
  11132. (when (boundp 'org-blocked-by-checkboxes)
  11133. (setq org-blocked-by-checkboxes t))
  11134. (throw 'dont-block nil))))
  11135. t))) ; do not block
  11136. (defun org-entry-blocked-p ()
  11137. "Non-nil if entry at point is blocked."
  11138. (and (not (org-entry-get nil "NOBLOCKING"))
  11139. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11140. (not (run-hook-with-args-until-failure
  11141. 'org-blocker-hook
  11142. (list :type 'todo-state-change
  11143. :position (point)
  11144. :from 'todo
  11145. :to 'done)))))
  11146. (defun org-update-statistics-cookies (all)
  11147. "Update the statistics cookie, either from TODO or from checkboxes.
  11148. This should be called with the cursor in a line with a statistics
  11149. cookie. When called with a \\[universal-argument] prefix, update
  11150. all statistics cookies in the buffer."
  11151. (interactive "P")
  11152. (if all
  11153. (progn
  11154. (org-update-checkbox-count 'all)
  11155. (org-map-entries 'org-update-parent-todo-statistics))
  11156. (if (not (org-at-heading-p))
  11157. (org-update-checkbox-count)
  11158. (let ((pos (point-marker))
  11159. end l1 l2)
  11160. (ignore-errors (org-back-to-heading t))
  11161. (if (not (org-at-heading-p))
  11162. (org-update-checkbox-count)
  11163. (setq l1 (org-outline-level))
  11164. (setq end (save-excursion
  11165. (outline-next-heading)
  11166. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11167. (point)))
  11168. (if (and (save-excursion
  11169. (re-search-forward
  11170. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11171. (not (save-excursion (re-search-forward
  11172. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11173. (org-update-checkbox-count)
  11174. (if (and l2 (> l2 l1))
  11175. (progn
  11176. (goto-char end)
  11177. (org-update-parent-todo-statistics))
  11178. (goto-char pos)
  11179. (beginning-of-line 1)
  11180. (while (re-search-forward
  11181. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11182. (point-at-eol) t)
  11183. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11184. (goto-char pos)
  11185. (move-marker pos nil)))))
  11186. (defvar org-entry-property-inherited-from) ;; defined below
  11187. (defun org-update-parent-todo-statistics ()
  11188. "Update any statistics cookie in the parent of the current headline.
  11189. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11190. the entire subtree and this will travel up the hierarchy and update
  11191. statistics everywhere."
  11192. (let* ((prop (save-excursion (org-up-heading-safe)
  11193. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11194. (recursive (or (not org-hierarchical-todo-statistics)
  11195. (and prop (string-match "\\<recursive\\>" prop))))
  11196. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11197. 0))
  11198. (first t)
  11199. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11200. level ltoggle l1 new ndel
  11201. (cnt-all 0) (cnt-done 0) is-percent kwd
  11202. checkbox-beg cookie-present)
  11203. (catch 'exit
  11204. (save-excursion
  11205. (beginning-of-line 1)
  11206. (setq ltoggle (funcall outline-level))
  11207. ;; Three situations are to consider:
  11208. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11209. ;; to the top-level ancestor on the headline;
  11210. ;; 2. If parent has "recursive" property, repeat up to the
  11211. ;; headline setting that property, taking inheritance into
  11212. ;; account;
  11213. ;; 3. Else, move up to direct parent and proceed only once.
  11214. (while (and (setq level (org-up-heading-safe))
  11215. (or recursive first)
  11216. (>= (point) lim))
  11217. (setq first nil cookie-present nil)
  11218. (unless (and level
  11219. (not (string-match
  11220. "\\<checkbox\\>"
  11221. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11222. "")))))
  11223. (throw 'exit nil))
  11224. (while (re-search-forward box-re (point-at-eol) t)
  11225. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11226. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11227. (save-match-data
  11228. (unless (outline-next-heading) (throw 'exit nil))
  11229. (while (and (looking-at org-complex-heading-regexp)
  11230. (> (setq l1 (length (match-string 1))) level))
  11231. (setq kwd (and (or recursive (= l1 ltoggle))
  11232. (match-string 2)))
  11233. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11234. (and (eq org-provide-todo-statistics t)
  11235. (or (member kwd org-done-keywords)))
  11236. (and (listp org-provide-todo-statistics)
  11237. (stringp (car org-provide-todo-statistics))
  11238. (or (member kwd org-provide-todo-statistics)
  11239. (member kwd org-done-keywords)))
  11240. (and (listp org-provide-todo-statistics)
  11241. (listp (car org-provide-todo-statistics))
  11242. (or (member kwd (car org-provide-todo-statistics))
  11243. (and (member kwd org-done-keywords)
  11244. (member kwd (cadr org-provide-todo-statistics))))))
  11245. (setq cnt-all (1+ cnt-all))
  11246. (and (eq org-provide-todo-statistics t)
  11247. kwd
  11248. (setq cnt-all (1+ cnt-all))))
  11249. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11250. (member kwd org-done-keywords))
  11251. (and (listp org-provide-todo-statistics)
  11252. (listp (car org-provide-todo-statistics))
  11253. (member kwd org-done-keywords)
  11254. (member kwd (cadr org-provide-todo-statistics)))
  11255. (and (listp org-provide-todo-statistics)
  11256. (stringp (car org-provide-todo-statistics))
  11257. (member kwd org-done-keywords)))
  11258. (setq cnt-done (1+ cnt-done)))
  11259. (outline-next-heading)))
  11260. (setq new
  11261. (if is-percent
  11262. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11263. (max 1 cnt-all)))
  11264. (format "[%d/%d]" cnt-done cnt-all))
  11265. ndel (- (match-end 0) checkbox-beg))
  11266. (goto-char checkbox-beg)
  11267. (insert new)
  11268. (delete-region (point) (+ (point) ndel))
  11269. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11270. (when cookie-present
  11271. (run-hook-with-args 'org-after-todo-statistics-hook
  11272. cnt-done (- cnt-all cnt-done))))))
  11273. (run-hooks 'org-todo-statistics-hook)))
  11274. (defvar org-after-todo-statistics-hook nil
  11275. "Hook that is called after a TODO statistics cookie has been updated.
  11276. Each function is called with two arguments: the number of not-done entries
  11277. and the number of done entries.
  11278. For example, the following function, when added to this hook, will switch
  11279. an entry to DONE when all children are done, and back to TODO when new
  11280. entries are set to a TODO status. Note that this hook is only called
  11281. when there is a statistics cookie in the headline!
  11282. (defun org-summary-todo (n-done n-not-done)
  11283. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11284. (let (org-log-done org-log-states) ; turn off logging
  11285. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11286. ")
  11287. (defvar org-todo-statistics-hook nil
  11288. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11289. This hook runs even if there is no statistics cookie present, in which case
  11290. `org-after-todo-statistics-hook' would not run.")
  11291. (defun org-todo-trigger-tag-changes (state)
  11292. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11293. (let ((l org-todo-state-tags-triggers)
  11294. changes)
  11295. (when (or (not state) (equal state ""))
  11296. (setq changes (append changes (cdr (assoc "" l)))))
  11297. (when (and (stringp state) (> (length state) 0))
  11298. (setq changes (append changes (cdr (assoc state l)))))
  11299. (when (member state org-not-done-keywords)
  11300. (setq changes (append changes (cdr (assq 'todo l)))))
  11301. (when (member state org-done-keywords)
  11302. (setq changes (append changes (cdr (assq 'done l)))))
  11303. (dolist (c changes)
  11304. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11305. (defun org-local-logging (value)
  11306. "Get logging settings from a property VALUE."
  11307. ;; Directly set the variables, they are already local.
  11308. (setq org-log-done nil
  11309. org-log-repeat nil
  11310. org-todo-log-states nil)
  11311. (dolist (w (split-string value))
  11312. (let (a)
  11313. (cond
  11314. ((setq a (assoc w org-startup-options))
  11315. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11316. (set (nth 1 a) (nth 2 a))))
  11317. ((setq a (org-extract-log-state-settings w))
  11318. (and (member (car a) org-todo-keywords-1)
  11319. (push a org-todo-log-states)))))))
  11320. (defun org-get-todo-sequence-head (kwd)
  11321. "Return the head of the TODO sequence to which KWD belongs.
  11322. If KWD is not set, check if there is a text property remembering the
  11323. right sequence."
  11324. (let (p)
  11325. (cond
  11326. ((not kwd)
  11327. (or (get-text-property (point-at-bol) 'org-todo-head)
  11328. (progn
  11329. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11330. nil (point-at-eol)))
  11331. (get-text-property p 'org-todo-head))))
  11332. ((not (member kwd org-todo-keywords-1))
  11333. (car org-todo-keywords-1))
  11334. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11335. (defun org-fast-todo-selection ()
  11336. "Fast TODO keyword selection with single keys.
  11337. Returns the new TODO keyword, or nil if no state change should occur."
  11338. (let* ((fulltable org-todo-key-alist)
  11339. (done-keywords org-done-keywords) ;; needed for the faces.
  11340. (maxlen (apply 'max (mapcar
  11341. (lambda (x)
  11342. (if (stringp (car x)) (string-width (car x)) 0))
  11343. fulltable)))
  11344. (expert nil)
  11345. (fwidth (+ maxlen 3 1 3))
  11346. (ncol (/ (- (window-width) 4) fwidth))
  11347. tg cnt e c tbl
  11348. groups ingroup)
  11349. (save-excursion
  11350. (save-window-excursion
  11351. (if expert
  11352. (set-buffer (get-buffer-create " *Org todo*"))
  11353. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11354. (erase-buffer)
  11355. (setq-local org-done-keywords done-keywords)
  11356. (setq tbl fulltable cnt 0)
  11357. (while (setq e (pop tbl))
  11358. (cond
  11359. ((equal e '(:startgroup))
  11360. (push '() groups) (setq ingroup t)
  11361. (unless (= cnt 0)
  11362. (setq cnt 0)
  11363. (insert "\n"))
  11364. (insert "{ "))
  11365. ((equal e '(:endgroup))
  11366. (setq ingroup nil cnt 0)
  11367. (insert "}\n"))
  11368. ((equal e '(:newline))
  11369. (unless (= cnt 0)
  11370. (setq cnt 0)
  11371. (insert "\n")
  11372. (setq e (car tbl))
  11373. (while (equal (car tbl) '(:newline))
  11374. (insert "\n")
  11375. (setq tbl (cdr tbl)))))
  11376. (t
  11377. (setq tg (car e) c (cdr e))
  11378. (when ingroup (push tg (car groups)))
  11379. (setq tg (org-add-props tg nil 'face
  11380. (org-get-todo-face tg)))
  11381. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11382. (insert "[" c "] " tg (make-string
  11383. (- fwidth 4 (length tg)) ?\ ))
  11384. (when (= (setq cnt (1+ cnt)) ncol)
  11385. (insert "\n")
  11386. (when ingroup (insert " "))
  11387. (setq cnt 0)))))
  11388. (insert "\n")
  11389. (goto-char (point-min))
  11390. (unless expert (org-fit-window-to-buffer))
  11391. (message "[a-z..]:Set [SPC]:clear")
  11392. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11393. (cond
  11394. ((or (= c ?\C-g)
  11395. (and (= c ?q) (not (rassoc c fulltable))))
  11396. (setq quit-flag t))
  11397. ((= c ?\ ) nil)
  11398. ((setq e (rassoc c fulltable) tg (car e))
  11399. tg)
  11400. (t (setq quit-flag t)))))))
  11401. (defun org-entry-is-todo-p ()
  11402. (member (org-get-todo-state) org-not-done-keywords))
  11403. (defun org-entry-is-done-p ()
  11404. (member (org-get-todo-state) org-done-keywords))
  11405. (defun org-get-todo-state ()
  11406. "Return the TODO keyword of the current subtree."
  11407. (save-excursion
  11408. (org-back-to-heading t)
  11409. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11410. (match-end 2)
  11411. (match-string 2))))
  11412. (defun org-at-date-range-p (&optional inactive-ok)
  11413. "Non-nil if point is inside a date range.
  11414. When optional argument INACTIVE-OK is non-nil, also consider
  11415. inactive time ranges.
  11416. When this function returns a non-nil value, match data is set
  11417. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11418. on INACTIVE-OK."
  11419. (interactive)
  11420. (save-excursion
  11421. (catch 'exit
  11422. (let ((pos (point)))
  11423. (skip-chars-backward "^[<\r\n")
  11424. (skip-chars-backward "<[")
  11425. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11426. (>= (match-end 0) pos)
  11427. (throw 'exit t))
  11428. (skip-chars-backward "^<[\r\n")
  11429. (skip-chars-backward "<[")
  11430. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11431. (>= (match-end 0) pos)
  11432. (throw 'exit t)))
  11433. nil)))
  11434. (defun org-get-repeat (&optional timestamp)
  11435. "Check if there is a time-stamp with repeater in this entry.
  11436. Return the repeater, as a string, or nil. Also return nil when
  11437. this function is called before first heading.
  11438. When optional argument TIMESTAMP is a string, extract the
  11439. repeater from there instead."
  11440. (save-match-data
  11441. (cond (timestamp
  11442. (and (string-match org-repeat-re timestamp)
  11443. (match-string-no-properties 1 timestamp)))
  11444. ((org-before-first-heading-p) nil)
  11445. (t
  11446. (save-excursion
  11447. (org-back-to-heading t)
  11448. (let ((end (org-entry-end-position)))
  11449. (catch :repeat
  11450. (while (re-search-forward org-repeat-re end t)
  11451. (when (save-match-data (org-at-timestamp-p 'agenda))
  11452. (throw :repeat (match-string-no-properties 1)))))))))))
  11453. (defvar org-last-changed-timestamp)
  11454. (defvar org-last-inserted-timestamp)
  11455. (defvar org-log-post-message)
  11456. (defvar org-log-note-purpose)
  11457. (defvar org-log-note-how nil)
  11458. (defvar org-log-note-extra)
  11459. (defun org-auto-repeat-maybe (done-word)
  11460. "Check if the current headline contains a repeated time-stamp.
  11461. If yes, set TODO state back to what it was and change the base date
  11462. of repeating deadline/scheduled time stamps to new date.
  11463. This function is run automatically after each state change to a DONE state."
  11464. (let* ((repeat (org-get-repeat))
  11465. (aa (assoc org-last-state org-todo-kwd-alist))
  11466. (interpret (nth 1 aa))
  11467. (head (nth 2 aa))
  11468. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11469. (msg "Entry repeats: ")
  11470. (org-log-done nil)
  11471. (org-todo-log-states nil)
  11472. (end (copy-marker (org-entry-end-position))))
  11473. (unwind-protect
  11474. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11475. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11476. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11477. (and (stringp org-todo-repeat-to-state)
  11478. org-todo-repeat-to-state)
  11479. (and org-todo-repeat-to-state org-last-state))))
  11480. (org-todo (cond
  11481. ((and to-state (member to-state org-todo-keywords-1))
  11482. to-state)
  11483. ((eq interpret 'type) org-last-state)
  11484. (head)
  11485. (t 'none))))
  11486. (org-back-to-heading t)
  11487. (org-add-planning-info nil nil 'closed)
  11488. ;; When `org-log-repeat' is non-nil or entry contains
  11489. ;; a clock, set LAST_REPEAT property.
  11490. (when (or org-log-repeat
  11491. (catch :clock
  11492. (save-excursion
  11493. (while (re-search-forward org-clock-line-re end t)
  11494. (when (org-at-clock-log-p) (throw :clock t))))))
  11495. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11496. (org-time-stamp-format t t)
  11497. (current-time))))
  11498. (when org-log-repeat
  11499. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11500. (memq 'org-add-log-note post-command-hook))
  11501. ;; We are already setup for some record.
  11502. (when (eq org-log-repeat 'note)
  11503. ;; Make sure we take a note, not only a time stamp.
  11504. (setq org-log-note-how 'note))
  11505. ;; Set up for taking a record.
  11506. (org-add-log-setup 'state
  11507. (or done-word (car org-done-keywords))
  11508. org-last-state
  11509. org-log-repeat)))
  11510. (let ((planning-re (regexp-opt
  11511. (list org-scheduled-string org-deadline-string))))
  11512. (while (re-search-forward org-ts-regexp end t)
  11513. (let* ((ts (match-string 0))
  11514. (planning? (org-at-planning-p))
  11515. (type (if (not planning?) "Plain:"
  11516. (save-excursion
  11517. (re-search-backward
  11518. planning-re (line-beginning-position) t)
  11519. (match-string 0)))))
  11520. (cond
  11521. ;; Ignore fake time-stamps (e.g., within comments).
  11522. ((not (org-at-timestamp-p 'agenda)))
  11523. ;; Time-stamps without a repeater are usually
  11524. ;; skipped. However, a SCHEDULED time-stamp without
  11525. ;; one is removed, as they are no longer relevant.
  11526. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11527. ts))
  11528. (when (equal type org-scheduled-string)
  11529. (org-remove-timestamp-with-keyword type)))
  11530. (t
  11531. (let ((n (string-to-number (match-string 2 ts)))
  11532. (what (match-string 3 ts)))
  11533. (when (equal what "w") (setq n (* n 7) what "d"))
  11534. (when (and (equal what "h")
  11535. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11536. ts)))
  11537. (user-error
  11538. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11539. has been set"
  11540. n))
  11541. ;; Preparation, see if we need to modify the start
  11542. ;; date for the change.
  11543. (when (match-end 1)
  11544. (let ((time (save-match-data
  11545. (org-time-string-to-time ts))))
  11546. (cond
  11547. ((equal (match-string 1 ts) ".")
  11548. ;; Shift starting date to today
  11549. (org-timestamp-change
  11550. (- (org-today) (time-to-days time))
  11551. 'day))
  11552. ((equal (match-string 1 ts) "+")
  11553. (let ((nshiftmax 10)
  11554. (nshift 0))
  11555. (while (or (= nshift 0)
  11556. (not (time-less-p (current-time) time)))
  11557. (when (= (cl-incf nshift) nshiftmax)
  11558. (or (y-or-n-p
  11559. (format "%d repeater intervals were not \
  11560. enough to shift date past today. Continue? "
  11561. nshift))
  11562. (user-error "Abort")))
  11563. (org-timestamp-change n (cdr (assoc what whata)))
  11564. (org-in-regexp org-ts-regexp3)
  11565. (setq ts (match-string 1))
  11566. (setq time
  11567. (save-match-data
  11568. (org-time-string-to-time ts)))))
  11569. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11570. ;; Rematch, so that we have everything in place
  11571. ;; for the real shift.
  11572. (org-in-regexp org-ts-regexp3)
  11573. (setq ts (match-string 1))
  11574. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11575. ts)))))
  11576. (save-excursion
  11577. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11578. (setq msg
  11579. (concat
  11580. msg type " " org-last-changed-timestamp " "))))))))
  11581. (setq org-log-post-message msg)
  11582. (message "%s" msg))
  11583. (set-marker end nil))))
  11584. (defun org-show-todo-tree (arg)
  11585. "Make a compact tree which shows all headlines marked with TODO.
  11586. The tree will show the lines where the regexp matches, and all higher
  11587. headlines above the match.
  11588. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11589. With a numeric prefix N, construct a sparse tree for the Nth element
  11590. of `org-todo-keywords-1'."
  11591. (interactive "P")
  11592. (let ((case-fold-search nil)
  11593. (kwd-re
  11594. (cond ((null arg) org-not-done-regexp)
  11595. ((equal arg '(4))
  11596. (let ((kwd
  11597. (completing-read "Keyword (or KWD1|KWD2|...): "
  11598. (mapcar #'list org-todo-keywords-1))))
  11599. (concat "\\("
  11600. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11601. "\\)\\>")))
  11602. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11603. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11604. org-todo-keywords-1)))
  11605. (t (user-error "Invalid prefix argument: %s" arg)))))
  11606. (message "%d TODO entries found"
  11607. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11608. (defun org--deadline-or-schedule (arg type time)
  11609. "Insert DEADLINE or SCHEDULE information in current entry.
  11610. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11611. `org-schedule' for information about ARG and TIME arguments."
  11612. (let* ((deadline? (eq type 'deadline))
  11613. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11614. (log (if deadline? org-log-redeadline org-log-reschedule))
  11615. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11616. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11617. ;; Save repeater cookie from either TIME or current scheduled
  11618. ;; time stamp. We are going to insert it back at the end of
  11619. ;; the process.
  11620. (repeater (or (and (org-string-nw-p time)
  11621. ;; We use `org-repeat-re' because we need
  11622. ;; to tell the difference between a real
  11623. ;; repeater and a time delta, e.g. "+2d".
  11624. (string-match org-repeat-re time)
  11625. (match-string 1 time))
  11626. (and (org-string-nw-p old-date)
  11627. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11628. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11629. old-date)
  11630. (match-string 1 old-date)))))
  11631. (pcase arg
  11632. (`(4)
  11633. (if (not old-date)
  11634. (message (if deadline? "Entry had no deadline to remove"
  11635. "Entry was not scheduled"))
  11636. (when (and old-date log)
  11637. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11638. nil old-date log))
  11639. (org-remove-timestamp-with-keyword keyword)
  11640. (message (if deadline? "Entry no longer has a deadline."
  11641. "Entry is no longer scheduled."))))
  11642. (`(16)
  11643. (save-excursion
  11644. (org-back-to-heading t)
  11645. (let ((regexp (if deadline? org-deadline-time-regexp
  11646. org-scheduled-time-regexp)))
  11647. (if (not (re-search-forward regexp (line-end-position 2) t))
  11648. (user-error (if deadline? "No deadline information to update"
  11649. "No scheduled information to update"))
  11650. (let* ((rpl0 (match-string 1))
  11651. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11652. (msg (if deadline? "Warn starting from" "Delay until")))
  11653. (replace-match
  11654. (concat keyword
  11655. " <" rpl
  11656. (format " -%dd"
  11657. (abs (- (time-to-days
  11658. (save-match-data
  11659. (org-read-date
  11660. nil t nil msg old-date-time)))
  11661. (time-to-days old-date-time))))
  11662. ">") t t))))))
  11663. (_
  11664. (org-add-planning-info type time 'closed)
  11665. (when (and old-date
  11666. log
  11667. (not (equal old-date org-last-inserted-timestamp)))
  11668. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11669. org-last-inserted-timestamp
  11670. old-date
  11671. log))
  11672. (when repeater
  11673. (save-excursion
  11674. (org-back-to-heading t)
  11675. (when (re-search-forward
  11676. (concat keyword " " org-last-inserted-timestamp)
  11677. (line-end-position 2)
  11678. t)
  11679. (goto-char (1- (match-end 0)))
  11680. (insert " " repeater)
  11681. (setq org-last-inserted-timestamp
  11682. (concat (substring org-last-inserted-timestamp 0 -1)
  11683. " " repeater
  11684. (substring org-last-inserted-timestamp -1))))))
  11685. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11686. org-last-inserted-timestamp)))))
  11687. (defun org-deadline (arg &optional time)
  11688. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11689. With one universal prefix argument, remove any deadline from the item.
  11690. With two universal prefix arguments, prompt for a warning delay.
  11691. With argument TIME, set the deadline at the corresponding date. TIME
  11692. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11693. (interactive "P")
  11694. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11695. (org-map-entries
  11696. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11697. nil
  11698. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11699. 'region-start-level
  11700. 'region)
  11701. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11702. (org--deadline-or-schedule arg 'deadline time)))
  11703. (defun org-schedule (arg &optional time)
  11704. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11705. With one universal prefix argument, remove any scheduling date from the item.
  11706. With two universal prefix arguments, prompt for a delay cookie.
  11707. With argument TIME, scheduled at the corresponding date. TIME can
  11708. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11709. (interactive "P")
  11710. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11711. (org-map-entries
  11712. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11713. nil
  11714. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11715. 'region-start-level
  11716. 'region)
  11717. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11718. (org--deadline-or-schedule arg 'scheduled time)))
  11719. (defun org-get-scheduled-time (pom &optional inherit)
  11720. "Get the scheduled time as a time tuple, of a format suitable
  11721. for calling org-schedule with, or if there is no scheduling,
  11722. returns nil."
  11723. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11724. (when time
  11725. (apply 'encode-time (org-parse-time-string time)))))
  11726. (defun org-get-deadline-time (pom &optional inherit)
  11727. "Get the deadline as a time tuple, of a format suitable for
  11728. calling org-deadline with, or if there is no scheduling, returns
  11729. nil."
  11730. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11731. (when time
  11732. (apply 'encode-time (org-parse-time-string time)))))
  11733. (defun org-remove-timestamp-with-keyword (keyword)
  11734. "Remove all time stamps with KEYWORD in the current entry."
  11735. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11736. beg)
  11737. (save-excursion
  11738. (org-back-to-heading t)
  11739. (setq beg (point))
  11740. (outline-next-heading)
  11741. (while (re-search-backward re beg t)
  11742. (replace-match "")
  11743. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11744. (equal (char-before) ?\ ))
  11745. (backward-delete-char 1)
  11746. (when (string-match "^[ \t]*$" (buffer-substring
  11747. (point-at-bol) (point-at-eol)))
  11748. (delete-region (point-at-bol)
  11749. (min (point-max) (1+ (point-at-eol))))))))))
  11750. (defvar org-time-was-given) ; dynamically scoped parameter
  11751. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11752. (defun org-at-planning-p ()
  11753. "Non-nil when point is on a planning info line."
  11754. ;; This is as accurate and faster than `org-element-at-point' since
  11755. ;; planning info location is fixed in the section.
  11756. (org-with-wide-buffer
  11757. (beginning-of-line)
  11758. (and (looking-at-p org-planning-line-re)
  11759. (eq (point)
  11760. (ignore-errors
  11761. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11762. (org-back-to-heading t)
  11763. (org-with-limited-levels (org-back-to-heading t)))
  11764. (line-beginning-position 2))))))
  11765. (defun org-add-planning-info (what &optional time &rest remove)
  11766. "Insert new timestamp with keyword in the planning line.
  11767. WHAT indicates what kind of time stamp to add. It is a symbol
  11768. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11769. the time to use. If none is given, the user is prompted for
  11770. a date. REMOVE indicates what kind of entries to remove. An old
  11771. WHAT entry will also be removed."
  11772. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11773. (catch 'exit
  11774. (when (and (memq what '(scheduled deadline))
  11775. (or (not time)
  11776. (and (stringp time)
  11777. (string-match "^[-+]+[0-9]" time))))
  11778. ;; Try to get a default date/time from existing timestamp
  11779. (save-excursion
  11780. (org-back-to-heading t)
  11781. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11782. (when (re-search-forward (if (eq what 'scheduled)
  11783. org-scheduled-time-regexp
  11784. org-deadline-time-regexp)
  11785. end t)
  11786. (setq ts (match-string 1)
  11787. default-time (apply 'encode-time (org-parse-time-string ts))
  11788. default-input (and ts (org-get-compact-tod ts)))))))
  11789. (when what
  11790. (setq time
  11791. (if (stringp time)
  11792. ;; This is a string (relative or absolute), set
  11793. ;; proper date.
  11794. (apply #'encode-time
  11795. (org-read-date-analyze
  11796. time default-time (decode-time default-time)))
  11797. ;; If necessary, get the time from the user
  11798. (or time (org-read-date nil 'to-time nil
  11799. (cl-case what
  11800. (deadline "DEADLINE")
  11801. (scheduled "SCHEDULED")
  11802. (otherwise nil))
  11803. default-time default-input)))))
  11804. (org-with-wide-buffer
  11805. (org-back-to-heading t)
  11806. (forward-line)
  11807. (unless (bolp) (insert "\n"))
  11808. (cond ((looking-at-p org-planning-line-re)
  11809. ;; Move to current indentation.
  11810. (skip-chars-forward " \t")
  11811. ;; Check if we have to remove something.
  11812. (dolist (type (if what (cons what remove) remove))
  11813. (save-excursion
  11814. (when (re-search-forward
  11815. (cl-case type
  11816. (closed org-closed-time-regexp)
  11817. (deadline org-deadline-time-regexp)
  11818. (scheduled org-scheduled-time-regexp)
  11819. (otherwise
  11820. (error "Invalid planning type: %s" type)))
  11821. (line-end-position) t)
  11822. ;; Delete until next keyword or end of line.
  11823. (delete-region
  11824. (match-beginning 0)
  11825. (if (re-search-forward org-keyword-time-not-clock-regexp
  11826. (line-end-position)
  11827. t)
  11828. (match-beginning 0)
  11829. (line-end-position))))))
  11830. ;; If there is nothing more to add and no more keyword
  11831. ;; is left, remove the line completely.
  11832. (if (and (looking-at-p "[ \t]*$") (not what))
  11833. (delete-region (line-beginning-position)
  11834. (line-beginning-position 2))
  11835. ;; If we removed last keyword, do not leave trailing
  11836. ;; white space at the end of line.
  11837. (let ((p (point)))
  11838. (save-excursion
  11839. (end-of-line)
  11840. (unless (= (skip-chars-backward " \t" p) 0)
  11841. (delete-region (point) (line-end-position)))))))
  11842. ((not what) (throw 'exit nil)) ; Nothing to do.
  11843. (t (insert-before-markers "\n")
  11844. (backward-char 1)
  11845. (when org-adapt-indentation
  11846. (indent-to-column (1+ (org-outline-level))))))
  11847. (when what
  11848. ;; Insert planning keyword.
  11849. (insert (cl-case what
  11850. (closed org-closed-string)
  11851. (deadline org-deadline-string)
  11852. (scheduled org-scheduled-string)
  11853. (otherwise (error "Invalid planning type: %s" what)))
  11854. " ")
  11855. ;; Insert associated timestamp.
  11856. (let ((ts (org-insert-time-stamp
  11857. time
  11858. (or org-time-was-given
  11859. (and (eq what 'closed) org-log-done-with-time))
  11860. (eq what 'closed)
  11861. nil nil (list org-end-time-was-given))))
  11862. (unless (eolp) (insert " "))
  11863. ts))))))
  11864. (defvar org-log-note-marker (make-marker)
  11865. "Marker pointing at the entry where the note is to be inserted.")
  11866. (defvar org-log-note-purpose nil)
  11867. (defvar org-log-note-state nil)
  11868. (defvar org-log-note-previous-state nil)
  11869. (defvar org-log-note-extra nil)
  11870. (defvar org-log-note-window-configuration nil)
  11871. (defvar org-log-note-return-to (make-marker))
  11872. (defvar org-log-note-effective-time nil
  11873. "Remembered current time so that dynamically scoped
  11874. `org-extend-today-until' affects timestamps in state change log")
  11875. (defvar org-log-post-message nil
  11876. "Message to be displayed after a log note has been stored.
  11877. The auto-repeater uses this.")
  11878. (defun org-add-note ()
  11879. "Add a note to the current entry.
  11880. This is done in the same way as adding a state change note."
  11881. (interactive)
  11882. (org-add-log-setup 'note))
  11883. (defun org-log-beginning (&optional create)
  11884. "Return expected start of log notes in current entry.
  11885. When optional argument CREATE is non-nil, the function creates
  11886. a drawer to store notes, if necessary. Returned position ignores
  11887. narrowing."
  11888. (org-with-wide-buffer
  11889. (let ((drawer (org-log-into-drawer)))
  11890. (cond
  11891. (drawer
  11892. (org-end-of-meta-data)
  11893. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11894. (end (if (org-at-heading-p) (point)
  11895. (save-excursion (outline-next-heading) (point))))
  11896. (case-fold-search t))
  11897. (catch 'exit
  11898. ;; Try to find existing drawer.
  11899. (while (re-search-forward regexp end t)
  11900. (let ((element (org-element-at-point)))
  11901. (when (eq (org-element-type element) 'drawer)
  11902. (let ((cend (org-element-property :contents-end element)))
  11903. (when (and (not org-log-states-order-reversed) cend)
  11904. (goto-char cend)))
  11905. (throw 'exit nil))))
  11906. ;; No drawer found. Create one, if permitted.
  11907. (when create
  11908. (unless (bolp) (insert "\n"))
  11909. (let ((beg (point)))
  11910. (insert ":" drawer ":\n:END:\n")
  11911. (org-indent-region beg (point))
  11912. (org-flag-region
  11913. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11914. (end-of-line -1)))))
  11915. (t
  11916. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11917. (skip-chars-forward " \t\n")
  11918. (beginning-of-line)
  11919. (unless org-log-states-order-reversed
  11920. (org-skip-over-state-notes)
  11921. (skip-chars-backward " \t\n")
  11922. (forward-line)))))
  11923. (if (bolp) (point) (line-beginning-position 2))))
  11924. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11925. "Set up the post command hook to take a note.
  11926. If this is about to TODO state change, the new state is expected in STATE.
  11927. HOW is an indicator what kind of note should be created.
  11928. EXTRA is additional text that will be inserted into the notes buffer."
  11929. (move-marker org-log-note-marker (point))
  11930. (setq org-log-note-purpose purpose
  11931. org-log-note-state state
  11932. org-log-note-previous-state prev-state
  11933. org-log-note-how how
  11934. org-log-note-extra extra
  11935. org-log-note-effective-time (org-current-effective-time))
  11936. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11937. (defun org-skip-over-state-notes ()
  11938. "Skip past the list of State notes in an entry."
  11939. (when (ignore-errors (goto-char (org-in-item-p)))
  11940. (let* ((struct (org-list-struct))
  11941. (prevs (org-list-prevs-alist struct))
  11942. (regexp
  11943. (concat "[ \t]*- +"
  11944. (replace-regexp-in-string
  11945. " +" " +"
  11946. (org-replace-escapes
  11947. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11948. `(("%d" . ,org-ts-regexp-inactive)
  11949. ("%D" . ,org-ts-regexp)
  11950. ("%s" . "\\(?:\"\\S-+\"\\)?")
  11951. ("%S" . "\\(?:\"\\S-+\"\\)?")
  11952. ("%t" . ,org-ts-regexp-inactive)
  11953. ("%T" . ,org-ts-regexp)
  11954. ("%u" . ".*?")
  11955. ("%U" . ".*?")))))))
  11956. (while (looking-at-p regexp)
  11957. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11958. (org-list-get-item-end (point) struct)))))))
  11959. (defun org-add-log-note (&optional _purpose)
  11960. "Pop up a window for taking a note, and add this note later."
  11961. (remove-hook 'post-command-hook 'org-add-log-note)
  11962. (setq org-log-note-window-configuration (current-window-configuration))
  11963. (delete-other-windows)
  11964. (move-marker org-log-note-return-to (point))
  11965. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11966. (goto-char org-log-note-marker)
  11967. (org-switch-to-buffer-other-window "*Org Note*")
  11968. (erase-buffer)
  11969. (if (memq org-log-note-how '(time state))
  11970. (org-store-log-note)
  11971. (let ((org-inhibit-startup t)) (org-mode))
  11972. (insert (format "# Insert note for %s.
  11973. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11974. (cl-case org-log-note-purpose
  11975. (clock-out "stopped clock")
  11976. (done "closed todo item")
  11977. (reschedule "rescheduling")
  11978. (delschedule "no longer scheduled")
  11979. (redeadline "changing deadline")
  11980. (deldeadline "removing deadline")
  11981. (refile "refiling")
  11982. (note "this entry")
  11983. (state
  11984. (format "state change from \"%s\" to \"%s\""
  11985. (or org-log-note-previous-state "")
  11986. (or org-log-note-state "")))
  11987. (t (error "This should not happen")))))
  11988. (when org-log-note-extra (insert org-log-note-extra))
  11989. (setq-local org-finish-function 'org-store-log-note)
  11990. (run-hooks 'org-log-buffer-setup-hook)))
  11991. (defvar org-note-abort nil) ; dynamically scoped
  11992. (defun org-store-log-note ()
  11993. "Finish taking a log note, and insert it to where it belongs."
  11994. (let ((txt (prog1 (buffer-string)
  11995. (kill-buffer)))
  11996. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11997. lines)
  11998. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11999. (setq txt (replace-match "" t t txt)))
  12000. (when (string-match "\\s-+\\'" txt)
  12001. (setq txt (replace-match "" t t txt)))
  12002. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12003. (when (org-string-nw-p note)
  12004. (setq note
  12005. (org-replace-escapes
  12006. note
  12007. (list (cons "%u" (user-login-name))
  12008. (cons "%U" user-full-name)
  12009. (cons "%t" (format-time-string
  12010. (org-time-stamp-format 'long 'inactive)
  12011. org-log-note-effective-time))
  12012. (cons "%T" (format-time-string
  12013. (org-time-stamp-format 'long nil)
  12014. org-log-note-effective-time))
  12015. (cons "%d" (format-time-string
  12016. (org-time-stamp-format nil 'inactive)
  12017. org-log-note-effective-time))
  12018. (cons "%D" (format-time-string
  12019. (org-time-stamp-format nil nil)
  12020. org-log-note-effective-time))
  12021. (cons "%s" (cond
  12022. ((not org-log-note-state) "")
  12023. ((string-match-p org-ts-regexp
  12024. org-log-note-state)
  12025. (format "\"[%s]\""
  12026. (substring org-log-note-state 1 -1)))
  12027. (t (format "\"%s\"" org-log-note-state))))
  12028. (cons "%S"
  12029. (cond
  12030. ((not org-log-note-previous-state) "")
  12031. ((string-match-p org-ts-regexp
  12032. org-log-note-previous-state)
  12033. (format "\"[%s]\""
  12034. (substring
  12035. org-log-note-previous-state 1 -1)))
  12036. (t (format "\"%s\""
  12037. org-log-note-previous-state)))))))
  12038. (when lines (setq note (concat note " \\\\")))
  12039. (push note lines))
  12040. (when (and lines (not org-note-abort))
  12041. (with-current-buffer (marker-buffer org-log-note-marker)
  12042. (org-with-wide-buffer
  12043. ;; Find location for the new note.
  12044. (goto-char org-log-note-marker)
  12045. (set-marker org-log-note-marker nil)
  12046. ;; Note associated to a clock is to be located right after
  12047. ;; the clock. Do not move point.
  12048. (unless (eq org-log-note-purpose 'clock-out)
  12049. (goto-char (org-log-beginning t)))
  12050. ;; Make sure point is at the beginning of an empty line.
  12051. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12052. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12053. ;; In an existing list, add a new item at the top level.
  12054. ;; Otherwise, indent line like a regular one.
  12055. (let ((itemp (org-in-item-p)))
  12056. (if itemp
  12057. (indent-line-to
  12058. (let ((struct (save-excursion
  12059. (goto-char itemp) (org-list-struct))))
  12060. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12061. (org-indent-line)))
  12062. (insert (org-list-bullet-string "-") (pop lines))
  12063. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12064. (dolist (line lines)
  12065. (insert "\n")
  12066. (indent-line-to ind)
  12067. (insert line)))
  12068. (message "Note stored")
  12069. (org-back-to-heading t))
  12070. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12071. ;; from within `org-add-log-note' because `buffer-undo-list'
  12072. ;; is then modified outside of `org-with-remote-undo'.
  12073. (when (eq this-command 'org-agenda-todo)
  12074. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12075. ;; Don't add undo information when called from `org-agenda-todo'.
  12076. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12077. (set-window-configuration org-log-note-window-configuration)
  12078. (with-current-buffer (marker-buffer org-log-note-return-to)
  12079. (goto-char org-log-note-return-to))
  12080. (move-marker org-log-note-return-to nil)
  12081. (when org-log-post-message (message "%s" org-log-post-message))))
  12082. (defun org-remove-empty-drawer-at (pos)
  12083. "Remove an empty drawer at position POS.
  12084. POS may also be a marker."
  12085. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12086. (org-with-wide-buffer
  12087. (goto-char pos)
  12088. (let ((drawer (org-element-at-point)))
  12089. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12090. (not (org-element-property :contents-begin drawer)))
  12091. (delete-region (org-element-property :begin drawer)
  12092. (progn (goto-char (org-element-property :end drawer))
  12093. (skip-chars-backward " \r\t\n")
  12094. (forward-line)
  12095. (point))))))))
  12096. (defvar org-ts-type nil)
  12097. (defun org-sparse-tree (&optional arg type)
  12098. "Create a sparse tree, prompt for the details.
  12099. This command can create sparse trees. You first need to select the type
  12100. of match used to create the tree:
  12101. t Show all TODO entries.
  12102. T Show entries with a specific TODO keyword.
  12103. m Show entries selected by a tags/property match.
  12104. p Enter a property name and its value (both with completion on existing
  12105. names/values) and show entries with that property.
  12106. r Show entries matching a regular expression (`/' can be used as well).
  12107. b Show deadlines and scheduled items before a date.
  12108. a Show deadlines and scheduled items after a date.
  12109. d Show deadlines due within `org-deadline-warning-days'.
  12110. D Show deadlines and scheduled items between a date range."
  12111. (interactive "P")
  12112. (setq type (or type org-sparse-tree-default-date-type))
  12113. (setq org-ts-type type)
  12114. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12115. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12116. \[c]ycle through date types: %s"
  12117. (cl-case type
  12118. (all "all timestamps")
  12119. (scheduled "only scheduled")
  12120. (deadline "only deadline")
  12121. (active "only active timestamps")
  12122. (inactive "only inactive timestamps")
  12123. (closed "with a closed time-stamp")
  12124. (otherwise "scheduled/deadline")))
  12125. (let ((answer (read-char-exclusive)))
  12126. (cl-case answer
  12127. (?c
  12128. (org-sparse-tree
  12129. arg
  12130. (cadr
  12131. (memq type '(nil all scheduled deadline active inactive closed)))))
  12132. (?d (call-interactively 'org-check-deadlines))
  12133. (?b (call-interactively 'org-check-before-date))
  12134. (?a (call-interactively 'org-check-after-date))
  12135. (?D (call-interactively 'org-check-dates-range))
  12136. (?t (call-interactively 'org-show-todo-tree))
  12137. (?T (org-show-todo-tree '(4)))
  12138. (?m (call-interactively 'org-match-sparse-tree))
  12139. ((?p ?P)
  12140. (let* ((kwd (completing-read
  12141. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12142. (value (completing-read
  12143. "Value: " (mapcar #'list (org-property-values kwd)))))
  12144. (unless (string-match "\\`{.*}\\'" value)
  12145. (setq value (concat "\"" value "\"")))
  12146. (org-match-sparse-tree arg (concat kwd "=" value))))
  12147. ((?r ?R ?/) (call-interactively 'org-occur))
  12148. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12149. (defvar-local org-occur-highlights nil
  12150. "List of overlays used for occur matches.")
  12151. (defvar-local org-occur-parameters nil
  12152. "Parameters of the active org-occur calls.
  12153. This is a list, each call to org-occur pushes as cons cell,
  12154. containing the regular expression and the callback, onto the list.
  12155. The list can contain several entries if `org-occur' has been called
  12156. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12157. will only contain one set of parameters. When the highlights are
  12158. removed (for example with `C-c C-c', or with the next edit (depending
  12159. on `org-remove-highlights-with-change'), this variable is emptied
  12160. as well.")
  12161. (defun org-occur (regexp &optional keep-previous callback)
  12162. "Make a compact tree which shows all matches of REGEXP.
  12163. The tree will show the lines where the regexp matches, and any other context
  12164. defined in `org-show-context-detail', which see.
  12165. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12166. done by a previous call to `org-occur' will be kept, to allow stacking of
  12167. calls to this command.
  12168. Optional argument CALLBACK can be a function of no argument. In this case,
  12169. it is called with point at the end of the match, match data being set
  12170. accordingly. Current match is shown only if the return value is non-nil.
  12171. The function must neither move point nor alter narrowing."
  12172. (interactive "sRegexp: \nP")
  12173. (when (equal regexp "")
  12174. (user-error "Regexp cannot be empty"))
  12175. (unless keep-previous
  12176. (org-remove-occur-highlights nil nil t))
  12177. (push (cons regexp callback) org-occur-parameters)
  12178. (let ((cnt 0))
  12179. (save-excursion
  12180. (goto-char (point-min))
  12181. (when (or (not keep-previous) ; do not want to keep
  12182. (not org-occur-highlights)) ; no previous matches
  12183. ;; hide everything
  12184. (org-overview))
  12185. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12186. (isearch-no-upper-case-p regexp t)
  12187. org-occur-case-fold-search)))
  12188. (while (re-search-forward regexp nil t)
  12189. (when (or (not callback)
  12190. (save-match-data (funcall callback)))
  12191. (setq cnt (1+ cnt))
  12192. (when org-highlight-sparse-tree-matches
  12193. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12194. (org-show-context 'occur-tree)))))
  12195. (when org-remove-highlights-with-change
  12196. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12197. nil 'local))
  12198. (unless org-sparse-tree-open-archived-trees
  12199. (org-hide-archived-subtrees (point-min) (point-max)))
  12200. (run-hooks 'org-occur-hook)
  12201. (when (called-interactively-p 'interactive)
  12202. (message "%d match(es) for regexp %s" cnt regexp))
  12203. cnt))
  12204. (defun org-occur-next-match (&optional n _reset)
  12205. "Function for `next-error-function' to find sparse tree matches.
  12206. N is the number of matches to move, when negative move backwards.
  12207. This function always goes back to the starting point when no
  12208. match is found."
  12209. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12210. (search-func (if (< n 0)
  12211. 'previous-single-char-property-change
  12212. 'next-single-char-property-change))
  12213. (n (abs n))
  12214. (pos (point))
  12215. p1)
  12216. (catch 'exit
  12217. (while (setq p1 (funcall search-func (point) 'org-type))
  12218. (when (equal p1 limit)
  12219. (goto-char pos)
  12220. (user-error "No more matches"))
  12221. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12222. (setq n (1- n))
  12223. (when (= n 0)
  12224. (goto-char p1)
  12225. (throw 'exit (point))))
  12226. (goto-char p1))
  12227. (goto-char p1)
  12228. (user-error "No more matches"))))
  12229. (defun org-highlight-new-match (beg end)
  12230. "Highlight from BEG to END and mark the highlight is an occur headline."
  12231. (let ((ov (make-overlay beg end)))
  12232. (overlay-put ov 'face 'secondary-selection)
  12233. (overlay-put ov 'org-type 'org-occur)
  12234. (push ov org-occur-highlights)))
  12235. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12236. "Remove the occur highlights from the buffer.
  12237. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12238. from the `before-change-functions' in the current buffer."
  12239. (interactive)
  12240. (unless org-inhibit-highlight-removal
  12241. (mapc #'delete-overlay org-occur-highlights)
  12242. (setq org-occur-highlights nil)
  12243. (setq org-occur-parameters nil)
  12244. (unless noremove
  12245. (remove-hook 'before-change-functions
  12246. 'org-remove-occur-highlights 'local))))
  12247. ;;;; Priorities
  12248. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12249. "Regular expression matching the priority indicator.")
  12250. (defvar org-remove-priority-next-time nil)
  12251. (defun org-priority-up ()
  12252. "Increase the priority of the current item."
  12253. (interactive)
  12254. (org-priority 'up))
  12255. (defun org-priority-down ()
  12256. "Decrease the priority of the current item."
  12257. (interactive)
  12258. (org-priority 'down))
  12259. (defun org-priority (&optional action show)
  12260. "Change the priority of an item.
  12261. When called interactively with a `\\[universal-argument]' prefix,
  12262. show the priority in the minibuffer instead of changing it.
  12263. When called programatically, ACTION can be `set', `up', `down',
  12264. or a character."
  12265. (interactive "P")
  12266. (when show
  12267. ;; Deprecation warning inserted for Org 9.2; once enough time has
  12268. ;; passed the SHOW argument should be removed.
  12269. (warn "`org-priority' called with deprecated SHOW argument"))
  12270. (if (equal action '(4))
  12271. (org-show-priority)
  12272. (unless org-enable-priority-commands
  12273. (user-error "Priority commands are disabled"))
  12274. (setq action (or action 'set))
  12275. (let (current new news have remove)
  12276. (save-excursion
  12277. (org-back-to-heading t)
  12278. (when (looking-at org-priority-regexp)
  12279. (setq current (string-to-char (match-string 2))
  12280. have t))
  12281. (cond
  12282. ((eq action 'remove)
  12283. (setq remove t new ?\ ))
  12284. ((or (eq action 'set)
  12285. (integerp action))
  12286. (if (not (eq action 'set))
  12287. (setq new action)
  12288. (message "Priority %c-%c, SPC to remove: "
  12289. org-highest-priority org-lowest-priority)
  12290. (save-match-data
  12291. (setq new (read-char-exclusive))))
  12292. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12293. (= (upcase org-lowest-priority) org-lowest-priority))
  12294. (setq new (upcase new)))
  12295. (cond ((equal new ?\s) (setq remove t))
  12296. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12297. (user-error "Priority must be between `%c' and `%c'"
  12298. org-highest-priority org-lowest-priority))))
  12299. ((eq action 'up)
  12300. (setq new (if have
  12301. (1- current) ; normal cycling
  12302. ;; last priority was empty
  12303. (if (eq last-command this-command)
  12304. org-lowest-priority ; wrap around empty to lowest
  12305. ;; default
  12306. (if org-priority-start-cycle-with-default
  12307. org-default-priority
  12308. (1- org-default-priority))))))
  12309. ((eq action 'down)
  12310. (setq new (if have
  12311. (1+ current) ; normal cycling
  12312. ;; last priority was empty
  12313. (if (eq last-command this-command)
  12314. org-highest-priority ; wrap around empty to highest
  12315. ;; default
  12316. (if org-priority-start-cycle-with-default
  12317. org-default-priority
  12318. (1+ org-default-priority))))))
  12319. (t (user-error "Invalid action")))
  12320. (when (or (< (upcase new) org-highest-priority)
  12321. (> (upcase new) org-lowest-priority))
  12322. (if (and (memq action '(up down))
  12323. (not have) (not (eq last-command this-command)))
  12324. ;; `new' is from default priority
  12325. (error
  12326. "The default can not be set, see `org-default-priority' why")
  12327. ;; normal cycling: `new' is beyond highest/lowest priority
  12328. ;; and is wrapped around to the empty priority
  12329. (setq remove t)))
  12330. (setq news (format "%c" new))
  12331. (if have
  12332. (if remove
  12333. (replace-match "" t t nil 1)
  12334. (replace-match news t t nil 2))
  12335. (if remove
  12336. (user-error "No priority cookie found in line")
  12337. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12338. (if (match-end 2)
  12339. (progn
  12340. (goto-char (match-end 2))
  12341. (insert " [#" news "]"))
  12342. (goto-char (match-beginning 3))
  12343. (insert "[#" news "] "))))
  12344. (org-align-tags))
  12345. (if remove
  12346. (message "Priority removed")
  12347. (message "Priority of current item set to %s" news)))))
  12348. (defun org-show-priority ()
  12349. "Show the priority of the current item.
  12350. This priority is composed of the main priority given with the [#A] cookies,
  12351. and by additional input from the age of a schedules or deadline entry."
  12352. (interactive)
  12353. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12354. (org-get-at-bol 'priority)
  12355. (save-excursion
  12356. (save-match-data
  12357. (beginning-of-line)
  12358. (and (looking-at org-heading-regexp)
  12359. (org-get-priority (match-string 0))))))))
  12360. (message "Priority is %d" (if pri pri -1000))))
  12361. (defun org-get-priority (s)
  12362. "Find priority cookie and return priority."
  12363. (save-match-data
  12364. (if (functionp org-get-priority-function)
  12365. (funcall org-get-priority-function)
  12366. (if (not (string-match org-priority-regexp s))
  12367. (* 1000 (- org-lowest-priority org-default-priority))
  12368. (* 1000 (- org-lowest-priority
  12369. (string-to-char (match-string 2 s))))))))
  12370. ;;;; Tags
  12371. (defvar org-agenda-archives-mode)
  12372. (defvar org-map-continue-from nil
  12373. "Position from where mapping should continue.
  12374. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12375. (defvar org-scanner-tags nil
  12376. "The current tag list while the tags scanner is running.")
  12377. (defvar org-trust-scanner-tags nil
  12378. "Should `org-get-tags' use the tags for the scanner.
  12379. This is for internal dynamical scoping only.
  12380. When this is non-nil, the function `org-get-tags' will return the value
  12381. of `org-scanner-tags' instead of building the list by itself. This
  12382. can lead to large speed-ups when the tags scanner is used in a file with
  12383. many entries, and when the list of tags is retrieved, for example to
  12384. obtain a list of properties. Building the tags list for each entry in such
  12385. a file becomes an N^2 operation - but with this variable set, it scales
  12386. as N.")
  12387. (defvar org--matcher-tags-todo-only nil)
  12388. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12389. "Scan headline tags with inheritance and produce output ACTION.
  12390. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12391. or `agenda' to produce an entry list for an agenda view. It can also be
  12392. a Lisp form or a function that should be called at each matched headline, in
  12393. this case the return value is a list of all return values from these calls.
  12394. MATCHER is a function accepting three arguments, returning
  12395. a non-nil value whenever a given set of tags qualifies a headline
  12396. for inclusion. See `org-make-tags-matcher' for more information.
  12397. As a special case, it can also be set to t (respectively nil) in
  12398. order to match all (respectively none) headline.
  12399. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12400. included in the output.
  12401. START-LEVEL can be a string with asterisks, reducing the scope to
  12402. headlines matching this string."
  12403. (require 'org-agenda)
  12404. (let* ((re (concat "^"
  12405. (if start-level
  12406. ;; Get the correct level to match
  12407. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12408. org-outline-regexp)
  12409. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12410. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12411. (props (list 'face 'default
  12412. 'done-face 'org-agenda-done
  12413. 'undone-face 'default
  12414. 'mouse-face 'highlight
  12415. 'org-not-done-regexp org-not-done-regexp
  12416. 'org-todo-regexp org-todo-regexp
  12417. 'org-complex-heading-regexp org-complex-heading-regexp
  12418. 'help-echo
  12419. (format "mouse-2 or RET jump to Org file %S"
  12420. (abbreviate-file-name
  12421. (or (buffer-file-name (buffer-base-buffer))
  12422. (buffer-name (buffer-base-buffer)))))))
  12423. (org-map-continue-from nil)
  12424. lspos tags tags-list
  12425. (tags-alist (list (cons 0 org-file-tags)))
  12426. (llast 0) rtn rtn1 level category i txt
  12427. todo marker entry priority
  12428. ts-date ts-date-type ts-date-pair)
  12429. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12430. (setq action (list 'lambda nil action)))
  12431. (save-excursion
  12432. (goto-char (point-min))
  12433. (when (eq action 'sparse-tree)
  12434. (org-overview)
  12435. (org-remove-occur-highlights))
  12436. (while (let (case-fold-search)
  12437. (re-search-forward re nil t))
  12438. (setq org-map-continue-from nil)
  12439. (catch :skip
  12440. ;; Ignore closing parts of inline tasks.
  12441. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12442. (throw :skip t))
  12443. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  12444. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  12445. (goto-char (setq lspos (match-beginning 0)))
  12446. (setq level (org-reduced-level (org-outline-level))
  12447. category (org-get-category))
  12448. (when (eq action 'agenda)
  12449. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12450. ts-date (car ts-date-pair)
  12451. ts-date-type (cdr ts-date-pair)))
  12452. (setq i llast llast level)
  12453. ;; remove tag lists from same and sublevels
  12454. (while (>= i level)
  12455. (when (setq entry (assoc i tags-alist))
  12456. (setq tags-alist (delete entry tags-alist)))
  12457. (setq i (1- i)))
  12458. ;; add the next tags
  12459. (when tags
  12460. (setq tags (org-split-string tags ":")
  12461. tags-alist
  12462. (cons (cons level tags) tags-alist)))
  12463. ;; compile tags for current headline
  12464. (setq tags-list
  12465. (if org-use-tag-inheritance
  12466. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12467. tags)
  12468. org-scanner-tags tags-list)
  12469. (when org-use-tag-inheritance
  12470. (setcdr (car tags-alist)
  12471. (mapcar (lambda (x)
  12472. (setq x (copy-sequence x))
  12473. (org-add-prop-inherited x))
  12474. (cdar tags-alist))))
  12475. (when (and tags org-use-tag-inheritance
  12476. (or (not (eq t org-use-tag-inheritance))
  12477. org-tags-exclude-from-inheritance))
  12478. ;; Selective inheritance, remove uninherited ones.
  12479. (setcdr (car tags-alist)
  12480. (org-remove-uninherited-tags (cdar tags-alist))))
  12481. (when (and
  12482. ;; eval matcher only when the todo condition is OK
  12483. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12484. (if (functionp matcher)
  12485. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12486. (funcall matcher todo tags-list level))
  12487. matcher))
  12488. ;; Call the skipper, but return t if it does not
  12489. ;; skip, so that the `and' form continues evaluating.
  12490. (progn
  12491. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12492. t)
  12493. ;; Check if timestamps are deselecting this entry
  12494. (or (not todo-only)
  12495. (and (member todo org-todo-keywords-1)
  12496. (or (not org-agenda-tags-todo-honor-ignore-options)
  12497. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12498. ;; select this headline
  12499. (cond
  12500. ((eq action 'sparse-tree)
  12501. (and org-highlight-sparse-tree-matches
  12502. (org-get-heading) (match-end 0)
  12503. (org-highlight-new-match
  12504. (match-beginning 1) (match-end 1)))
  12505. (org-show-context 'tags-tree))
  12506. ((eq action 'agenda)
  12507. (setq txt (org-agenda-format-item
  12508. ""
  12509. (concat
  12510. (if (eq org-tags-match-list-sublevels 'indented)
  12511. (make-string (1- level) ?.) "")
  12512. (org-get-heading))
  12513. (make-string level ?\s)
  12514. category
  12515. tags-list)
  12516. priority (org-get-priority txt))
  12517. (goto-char lspos)
  12518. (setq marker (org-agenda-new-marker))
  12519. (org-add-props txt props
  12520. 'org-marker marker 'org-hd-marker marker 'org-category category
  12521. 'todo-state todo
  12522. 'ts-date ts-date
  12523. 'priority priority
  12524. 'type (concat "tagsmatch" ts-date-type))
  12525. (push txt rtn))
  12526. ((functionp action)
  12527. (setq org-map-continue-from nil)
  12528. (save-excursion
  12529. (setq rtn1 (funcall action))
  12530. (push rtn1 rtn)))
  12531. (t (user-error "Invalid action")))
  12532. ;; if we are to skip sublevels, jump to end of subtree
  12533. (unless org-tags-match-list-sublevels
  12534. (org-end-of-subtree t)
  12535. (backward-char 1))))
  12536. ;; Get the correct position from where to continue
  12537. (if org-map-continue-from
  12538. (goto-char org-map-continue-from)
  12539. (and (= (point) lspos) (end-of-line 1)))))
  12540. (when (and (eq action 'sparse-tree)
  12541. (not org-sparse-tree-open-archived-trees))
  12542. (org-hide-archived-subtrees (point-min) (point-max)))
  12543. (nreverse rtn)))
  12544. (defun org-remove-uninherited-tags (tags)
  12545. "Remove all tags that are not inherited from the list TAGS."
  12546. (cond
  12547. ((eq org-use-tag-inheritance t)
  12548. (if org-tags-exclude-from-inheritance
  12549. (org-delete-all org-tags-exclude-from-inheritance tags)
  12550. tags))
  12551. ((not org-use-tag-inheritance) nil)
  12552. ((stringp org-use-tag-inheritance)
  12553. (delq nil (mapcar
  12554. (lambda (x)
  12555. (if (and (string-match org-use-tag-inheritance x)
  12556. (not (member x org-tags-exclude-from-inheritance)))
  12557. x nil))
  12558. tags)))
  12559. ((listp org-use-tag-inheritance)
  12560. (delq nil (mapcar
  12561. (lambda (x)
  12562. (if (member x org-use-tag-inheritance) x nil))
  12563. tags)))))
  12564. (defun org-match-sparse-tree (&optional todo-only match)
  12565. "Create a sparse tree according to tags string MATCH.
  12566. MATCH is a string with match syntax. It can contain a selection
  12567. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12568. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12569. those. See the manual for details.
  12570. If optional argument TODO-ONLY is non-nil, only select lines that
  12571. are also TODO tasks."
  12572. (interactive "P")
  12573. (org-agenda-prepare-buffers (list (current-buffer)))
  12574. (let ((org--matcher-tags-todo-only todo-only))
  12575. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12576. org--matcher-tags-todo-only)))
  12577. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12578. (defvar org-cached-props nil)
  12579. (defun org-cached-entry-get (pom property)
  12580. (if (or (eq t org-use-property-inheritance)
  12581. (and (stringp org-use-property-inheritance)
  12582. (let ((case-fold-search t))
  12583. (string-match-p org-use-property-inheritance property)))
  12584. (and (listp org-use-property-inheritance)
  12585. (member-ignore-case property org-use-property-inheritance)))
  12586. ;; Caching is not possible, check it directly.
  12587. (org-entry-get pom property 'inherit)
  12588. ;; Get all properties, so we can do complicated checks easily.
  12589. (cdr (assoc-string property
  12590. (or org-cached-props
  12591. (setq org-cached-props (org-entry-properties pom)))
  12592. t))))
  12593. (defun org-global-tags-completion-table (&optional files)
  12594. "Return the list of all tags in all agenda buffer/files.
  12595. Optional FILES argument is a list of files which can be used
  12596. instead of the agenda files."
  12597. (save-excursion
  12598. (org-uniquify
  12599. (delq nil
  12600. (apply #'append
  12601. (mapcar
  12602. (lambda (file)
  12603. (set-buffer (find-file-noselect file))
  12604. (org--tag-add-to-alist
  12605. (org-get-buffer-tags)
  12606. (mapcar (lambda (x)
  12607. (and (stringp (car-safe x))
  12608. (list (car-safe x))))
  12609. org-current-tag-alist)))
  12610. (if (car-safe files) files
  12611. (org-agenda-files))))))))
  12612. (defun org-make-tags-matcher (match)
  12613. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12614. Returns a cons of the selection string MATCH and a function
  12615. implementing the matcher.
  12616. The matcher is to be called at an Org entry, with point on the
  12617. headline, and returns non-nil if the entry matches the selection
  12618. string MATCH. It must be called with three arguments: the TODO
  12619. keyword at the entry (or nil if none), the list of all tags at
  12620. the entry including inherited ones and the reduced level of the
  12621. headline. Additionally, the category of the entry, if any, must
  12622. be specified as the text property `org-category' on the headline.
  12623. This function sets the variable `org--matcher-tags-todo-only' to
  12624. a non-nil value if the matcher restricts matching to TODO
  12625. entries, otherwise it is not touched.
  12626. See also `org-scan-tags'."
  12627. (unless match
  12628. ;; Get a new match request, with completion against the global
  12629. ;; tags table and the local tags in current buffer.
  12630. (let ((org-last-tags-completion-table
  12631. (org--tag-add-to-alist
  12632. (org-get-buffer-tags)
  12633. (org-global-tags-completion-table))))
  12634. (setq match
  12635. (completing-read
  12636. "Match: "
  12637. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12638. (let ((match0 match)
  12639. (re (concat
  12640. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12641. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12642. "\\([<>=]\\{1,2\\}\\)"
  12643. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12644. "\\|" org-tag-re "\\)"))
  12645. (start 0)
  12646. tagsmatch todomatch tagsmatcher todomatcher)
  12647. ;; Expand group tags.
  12648. (setq match (org-tags-expand match))
  12649. ;; Check if there is a TODO part of this match, which would be the
  12650. ;; part after a "/". To make sure that this slash is not part of
  12651. ;; a property value to be matched against, we also check that
  12652. ;; there is no / after that slash. First, find the last slash.
  12653. (let ((s 0))
  12654. (while (string-match "/+" match s)
  12655. (setq start (match-beginning 0))
  12656. (setq s (match-end 0))))
  12657. (if (and (string-match "/+" match start)
  12658. (not (string-match-p "\"" match start)))
  12659. ;; Match contains also a TODO-matching request.
  12660. (progn
  12661. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12662. (setq todomatch (substring match (match-end 0)))
  12663. (when (string-prefix-p "!" todomatch)
  12664. (setq org--matcher-tags-todo-only t)
  12665. (setq todomatch (substring todomatch 1)))
  12666. (when (string-match "\\`\\s-*\\'" todomatch)
  12667. (setq todomatch nil)))
  12668. ;; Only matching tags.
  12669. (setq tagsmatch match)
  12670. (setq todomatch nil))
  12671. ;; Make the tags matcher.
  12672. (when (org-string-nw-p tagsmatch)
  12673. (let ((orlist nil)
  12674. (orterms (org-split-string tagsmatch "|"))
  12675. term)
  12676. (while (setq term (pop orterms))
  12677. (while (and (equal (substring term -1) "\\") orterms)
  12678. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12679. (while (string-match re term)
  12680. (let* ((rest (substring term (match-end 0)))
  12681. (minus (and (match-end 1)
  12682. (equal (match-string 1 term) "-")))
  12683. (tag (save-match-data
  12684. (replace-regexp-in-string
  12685. "\\\\-" "-" (match-string 2 term))))
  12686. (regexp (eq (string-to-char tag) ?{))
  12687. (levelp (match-end 4))
  12688. (propp (match-end 5))
  12689. (mm
  12690. (cond
  12691. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12692. (levelp
  12693. `(,(org-op-to-function (match-string 3 term))
  12694. level
  12695. ,(string-to-number (match-string 4 term))))
  12696. (propp
  12697. (let* ((gv (pcase (upcase (match-string 5 term))
  12698. ("CATEGORY"
  12699. '(get-text-property (point) 'org-category))
  12700. ("TODO" 'todo)
  12701. (p `(org-cached-entry-get nil ,p))))
  12702. (pv (match-string 7 term))
  12703. (regexp (eq (string-to-char pv) ?{))
  12704. (strp (eq (string-to-char pv) ?\"))
  12705. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12706. (po (org-op-to-function (match-string 6 term)
  12707. (if timep 'time strp))))
  12708. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12709. (when timep (setq pv (org-matcher-time pv)))
  12710. (cond ((and regexp (eq po '/=))
  12711. `(not (string-match ,pv (or ,gv ""))))
  12712. (regexp `(string-match ,pv (or ,gv "")))
  12713. (strp `(,po (or ,gv "") ,pv))
  12714. (t
  12715. `(,po
  12716. (string-to-number (or ,gv ""))
  12717. ,(string-to-number pv))))))
  12718. (t `(member ,tag tags-list)))))
  12719. (push (if minus `(not ,mm) mm) tagsmatcher)
  12720. (setq term rest)))
  12721. (push `(and ,@tagsmatcher) orlist)
  12722. (setq tagsmatcher nil))
  12723. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12724. ;; Make the TODO matcher.
  12725. (when (org-string-nw-p todomatch)
  12726. (let ((orlist nil))
  12727. (dolist (term (org-split-string todomatch "|"))
  12728. (while (string-match re term)
  12729. (let* ((minus (and (match-end 1)
  12730. (equal (match-string 1 term) "-")))
  12731. (kwd (match-string 2 term))
  12732. (regexp (eq (string-to-char kwd) ?{))
  12733. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12734. `(equal todo ,kwd))))
  12735. (push (if minus `(not ,mm) mm) todomatcher))
  12736. (setq term (substring term (match-end 0))))
  12737. (push (if (> (length todomatcher) 1)
  12738. (cons 'and todomatcher)
  12739. (car todomatcher))
  12740. orlist)
  12741. (setq todomatcher nil))
  12742. (setq todomatcher (cons 'or orlist))))
  12743. ;; Return the string and function of the matcher. If no
  12744. ;; tags-specific or todo-specific matcher exists, match
  12745. ;; everything.
  12746. (let ((matcher (if (and tagsmatcher todomatcher)
  12747. `(and ,tagsmatcher ,todomatcher)
  12748. (or tagsmatcher todomatcher t))))
  12749. (when org--matcher-tags-todo-only
  12750. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12751. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12752. (defun org--tags-expand-group (group tag-groups expanded)
  12753. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  12754. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  12755. an accumulator used in recursive calls."
  12756. (dolist (tag group)
  12757. (unless (member tag expanded)
  12758. (let ((group (assoc tag tag-groups)))
  12759. (push tag expanded)
  12760. (when group
  12761. (setq expanded
  12762. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  12763. expanded)
  12764. (defun org-tags-expand (match &optional single-as-list downcased)
  12765. "Expand group tags in MATCH.
  12766. This replaces every group tag in MATCH with a regexp tag search.
  12767. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12768. will be replaced like this:
  12769. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12770. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12771. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12772. Replacing by a regexp preserves the structure of the match.
  12773. E.g., this expansion
  12774. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12775. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12776. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  12777. A group tag in MATCH can contain regular expressions of its own.
  12778. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12779. will be replaced like this:
  12780. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12781. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12782. assumed to be a single group tag, and the function will return
  12783. the list of tags in this group.
  12784. When DOWNCASED is non-nil, expand downcased TAGS."
  12785. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  12786. (let ((tag-groups
  12787. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  12788. (if (not downcased) g
  12789. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  12790. (cond
  12791. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  12792. (org-group-tags
  12793. (let* ((case-fold-search t)
  12794. (tag-syntax org-mode-syntax-table)
  12795. (group-keys (mapcar #'car tag-groups))
  12796. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  12797. (return-match (if downcased (downcase match) match)))
  12798. ;; Mark regexp-expressions in the match-expression so that we
  12799. ;; do not replace them later on.
  12800. (let ((s 0))
  12801. (while (string-match "{.+?}" return-match s)
  12802. (setq s (match-end 0))
  12803. (add-text-properties
  12804. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  12805. ;; @ and _ are allowed as word-components in tags.
  12806. (modify-syntax-entry ?@ "w" tag-syntax)
  12807. (modify-syntax-entry ?_ "w" tag-syntax)
  12808. ;; For each tag token found in MATCH, compute a regexp and it
  12809. (with-syntax-table tag-syntax
  12810. (replace-regexp-in-string
  12811. key-regexp
  12812. (lambda (m)
  12813. (if (get-text-property (match-beginning 2) 'regexp m)
  12814. m ;regexp tag: ignore
  12815. (let* ((operator (match-string 1 m))
  12816. (tag-token (let ((tag (match-string 2 m)))
  12817. (list (if downcased (downcase tag) tag))))
  12818. regexp-tags regular-tags)
  12819. ;; Partition tags between regexp and regular tags.
  12820. ;; Remove curly bracket syntax from regexp tags.
  12821. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  12822. (save-match-data
  12823. (if (string-match "{\\(.+?\\)}" tag)
  12824. (push (match-string 1 tag) regexp-tags)
  12825. (push tag regular-tags))))
  12826. ;; Replace tag token by the appropriate regexp.
  12827. ;; Regular tags need to be regexp-quoted, whereas
  12828. ;; regexp-tags are inserted as-is.
  12829. (let ((regular (regexp-opt regular-tags))
  12830. (regexp (mapconcat #'identity regexp-tags "\\|")))
  12831. (concat operator
  12832. (cond
  12833. ((null regular-tags) (format "{%s}" regexp))
  12834. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  12835. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  12836. return-match
  12837. t t))))
  12838. (t match))))
  12839. (defun org-op-to-function (op &optional stringp)
  12840. "Turn an operator into the appropriate function."
  12841. (setq op
  12842. (cond
  12843. ((equal op "<" ) '(< org-string< org-time<))
  12844. ((equal op ">" ) '(> org-string> org-time>))
  12845. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12846. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12847. ((member op '("=" "==")) '(= string= org-time=))
  12848. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12849. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12850. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12851. (defvar org-tags-overlay (make-overlay 1 1))
  12852. (delete-overlay org-tags-overlay)
  12853. (defun org-add-prop-inherited (s)
  12854. (add-text-properties 0 (length s) '(inherited t) s)
  12855. s)
  12856. (defun org-toggle-tag (tag &optional onoff)
  12857. "Toggle the tag TAG for the current line.
  12858. If ONOFF is `on' or `off', don't toggle but set to this state."
  12859. (save-excursion
  12860. (org-back-to-heading t)
  12861. (let ((current
  12862. ;; Reverse the tags list so any new tag is appended to the
  12863. ;; current list of tags.
  12864. (nreverse (org-get-tags nil t)))
  12865. res)
  12866. (pcase onoff
  12867. (`off (setq current (delete tag current)))
  12868. ((or `on (guard (not (member tag current))))
  12869. (setq res t)
  12870. (cl-pushnew tag current :test #'equal))
  12871. (_ (setq current (delete tag current))))
  12872. (org-set-tags (nreverse current))
  12873. res)))
  12874. (defun org--align-tags-here (to-col)
  12875. "Align tags on the current headline to TO-COL.
  12876. Assume point is on a headline. Preserve point when aligning
  12877. tags."
  12878. (when (org-match-line org-tag-line-re)
  12879. (let* ((tags-start (match-beginning 1))
  12880. (blank-start (save-excursion
  12881. (goto-char tags-start)
  12882. (skip-chars-backward " \t")
  12883. (point)))
  12884. (new (max (if (>= to-col 0) to-col
  12885. (- (abs to-col) (string-width (match-string 1))))
  12886. ;; Introduce at least one space after the heading
  12887. ;; or the stars.
  12888. (save-excursion
  12889. (goto-char blank-start)
  12890. (1+ (current-column)))))
  12891. (current
  12892. (save-excursion (goto-char tags-start) (current-column)))
  12893. (origin (point-marker))
  12894. (column (current-column))
  12895. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  12896. (when (/= new current)
  12897. (delete-region blank-start tags-start)
  12898. (goto-char blank-start)
  12899. (let ((indent-tabs-mode nil)) (indent-to new))
  12900. ;; Try to move back to original position. If point was in the
  12901. ;; blanks before the tags, ORIGIN marker is of no use because
  12902. ;; it now points to BLANK-START. Use COLUMN instead.
  12903. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  12904. (defun org-set-tags-command (&optional arg)
  12905. "Set the tags for the current visible entry.
  12906. When called with `\\[universal-argument]' prefix argument ARG, \
  12907. realign all tags
  12908. in the current buffer. If a region is active, set tags for
  12909. all headlines in the region.
  12910. This function is for interactive use only;
  12911. in Lisp code use `org-set-tags' instead."
  12912. (interactive "P")
  12913. (cond
  12914. (arg (org-align-tags t))
  12915. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12916. ;; Disable `org-loop-over-headlines-in-active-region' for
  12917. ;; successive calls.
  12918. (let (org-loop-over-headlines-in-active-region)
  12919. (org-map-entries
  12920. #'org-set-tags-command
  12921. nil
  12922. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12923. 'region-start-level
  12924. 'region)
  12925. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  12926. (t
  12927. (save-excursion
  12928. (org-back-to-heading)
  12929. (let* ((all-tags (org-get-tags))
  12930. (table (setq org-last-tags-completion-table
  12931. (org--tag-add-to-alist
  12932. (and org-complete-tags-always-offer-all-agenda-tags
  12933. (org-global-tags-completion-table
  12934. (org-agenda-files)))
  12935. (or org-current-tag-alist (org-get-buffer-tags)))))
  12936. (current-tags
  12937. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  12938. all-tags))
  12939. (inherited-tags
  12940. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  12941. all-tags))
  12942. (tags
  12943. (replace-regexp-in-string
  12944. ;; Ignore all forbidden characters in tags.
  12945. "[^[:alnum:]_@#%]+" ":"
  12946. (if (or (eq t org-use-fast-tag-selection)
  12947. (and org-use-fast-tag-selection
  12948. (delq nil (mapcar #'cdr table))))
  12949. (org-fast-tag-selection
  12950. current-tags
  12951. inherited-tags
  12952. table
  12953. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  12954. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  12955. (org-trim (completing-read
  12956. "Tags: "
  12957. #'org-tags-completion-function
  12958. nil nil (org-make-tag-string current-tags)
  12959. 'org-tags-history)))))))
  12960. (org-set-tags tags))))))
  12961. (defun org-align-tags (&optional all)
  12962. "Align tags in current entry.
  12963. When optional argument ALL is non-nil, align all tags in the
  12964. visible part of the buffer."
  12965. (let ((get-indent-column
  12966. (lambda ()
  12967. (let ((offset (if (bound-and-true-p org-indent-mode)
  12968. (* (1- org-indent-indentation-per-level)
  12969. (1- (org-current-level)))
  12970. 0)))
  12971. (+ org-tags-column
  12972. (if (> org-tags-column 0) (- offset) offset))))))
  12973. (if (and (not all) (org-at-heading-p))
  12974. (org--align-tags-here (funcall get-indent-column))
  12975. (save-excursion
  12976. (if all
  12977. (while (re-search-forward org-tag-line-re nil t)
  12978. (org--align-tags-here (funcall get-indent-column)))
  12979. (org-back-to-heading t)
  12980. (org--align-tags-here (funcall get-indent-column)))))))
  12981. (defun org-set-tags (tags)
  12982. "Set the tags of the current entry to TAGS, replacing current tags.
  12983. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  12984. If TAGS is nil or the empty string, all tags are removed.
  12985. This function assumes point is on a headline."
  12986. (org-with-wide-buffer
  12987. (let ((tags (pcase tags
  12988. ((pred listp) tags)
  12989. ((pred stringp) (split-string (org-trim tags) ":" t))
  12990. (_ (error "Invalid tag specification: %S" tags))))
  12991. (old-tags (org-get-tags nil t))
  12992. (tags-change? nil))
  12993. (when (functionp org-tags-sort-function)
  12994. (setq tags (sort tags org-tags-sort-function)))
  12995. (setq tags-change? (not (equal tags old-tags)))
  12996. (when tags-change?
  12997. ;; Delete previous tags and any trailing white space.
  12998. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  12999. (line-end-position)))
  13000. (skip-chars-backward " \t")
  13001. (delete-region (point) (line-end-position))
  13002. ;; Deleting white spaces may break an otherwise empty headline.
  13003. ;; Re-introduce one space in this case.
  13004. (unless (org-at-heading-p) (insert " "))
  13005. (when tags
  13006. (save-excursion (insert " " (org-make-tag-string tags)))
  13007. ;; When text is being inserted on an invisible region
  13008. ;; boundary, it can be inadvertently sucked into
  13009. ;; invisibility.
  13010. (unless (org-invisible-p (line-beginning-position))
  13011. (org-flag-region (point) (line-end-position) nil 'outline))))
  13012. ;; Align tags, if any.
  13013. (when tags (org-align-tags))
  13014. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  13015. (defun org-change-tag-in-region (beg end tag off)
  13016. "Add or remove TAG for each entry in the region.
  13017. This works in the agenda, and also in an Org buffer."
  13018. (interactive
  13019. (list (region-beginning) (region-end)
  13020. (let ((org-last-tags-completion-table
  13021. (if (derived-mode-p 'org-mode)
  13022. (org--tag-add-to-alist
  13023. (org-get-buffer-tags)
  13024. (org-global-tags-completion-table))
  13025. (org-global-tags-completion-table))))
  13026. (completing-read
  13027. "Tag: " 'org-tags-completion-function nil nil nil
  13028. 'org-tags-history))
  13029. (progn
  13030. (message "[s]et or [r]emove? ")
  13031. (equal (read-char-exclusive) ?r))))
  13032. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13033. (let ((agendap (equal major-mode 'org-agenda-mode))
  13034. l1 l2 m buf pos newhead (cnt 0))
  13035. (goto-char end)
  13036. (setq l2 (1- (org-current-line)))
  13037. (goto-char beg)
  13038. (setq l1 (org-current-line))
  13039. (cl-loop for l from l1 to l2 do
  13040. (org-goto-line l)
  13041. (setq m (get-text-property (point) 'org-hd-marker))
  13042. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13043. (and agendap m))
  13044. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13045. pos (if agendap m (point)))
  13046. (with-current-buffer buf
  13047. (save-excursion
  13048. (save-restriction
  13049. (goto-char pos)
  13050. (setq cnt (1+ cnt))
  13051. (org-toggle-tag tag (if off 'off 'on))
  13052. (setq newhead (org-get-heading)))))
  13053. (and agendap (org-agenda-change-all-lines newhead m))))
  13054. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13055. (defun org-tags-completion-function (string _predicate &optional flag)
  13056. "Complete tag STRING.
  13057. FLAG specifies the type of completion operation to perform. This
  13058. function is passed as a collection function to `completing-read',
  13059. which see."
  13060. (let ((completion-ignore-case nil) ;tags are case-sensitive
  13061. (confirm (lambda (x) (stringp (car x))))
  13062. (prefix ""))
  13063. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13064. (setq prefix (match-string 1 string))
  13065. (setq string (match-string 2 string)))
  13066. (pcase flag
  13067. (`t (all-completions string org-last-tags-completion-table confirm))
  13068. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  13069. (`nil
  13070. (pcase (try-completion string org-last-tags-completion-table confirm)
  13071. ((and completion (pred stringp))
  13072. (concat prefix
  13073. completion
  13074. (if (and org-add-colon-after-tag-completion
  13075. (assoc completion org-last-tags-completion-table))
  13076. ":"
  13077. "")))
  13078. (completion completion)))
  13079. (_ nil))))
  13080. (defun org-fast-tag-insert (kwd tags face &optional end)
  13081. "Insert KWD, and the TAGS, the latter with face FACE.
  13082. Also insert END."
  13083. (insert (format "%-12s" (concat kwd ":"))
  13084. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13085. (or end "")))
  13086. (defun org-fast-tag-show-exit (flag)
  13087. (save-excursion
  13088. (org-goto-line 3)
  13089. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13090. (replace-match ""))
  13091. (when flag
  13092. (end-of-line 1)
  13093. (org-move-to-column (- (window-width) 19) t)
  13094. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13095. (defun org-set-current-tags-overlay (current prefix)
  13096. "Add an overlay to CURRENT tag with PREFIX."
  13097. (let ((s (org-make-tag-string current)))
  13098. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13099. (org-overlay-display org-tags-overlay (concat prefix s))))
  13100. (defvar org-last-tag-selection-key nil)
  13101. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13102. "Fast tag selection with single keys.
  13103. CURRENT is the current list of tags in the headline, INHERITED is the
  13104. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13105. possibly with grouping information. TODO-TABLE is a similar table with
  13106. TODO keywords, should these have keys assigned to them.
  13107. If the keys are nil, a-z are automatically assigned.
  13108. Returns the new tags string, or nil to not change the current settings."
  13109. (let* ((fulltable (append table todo-table))
  13110. (maxlen (if (null fulltable) 0
  13111. (apply #'max
  13112. (mapcar (lambda (x)
  13113. (if (stringp (car x)) (string-width (car x))
  13114. 0))
  13115. fulltable))))
  13116. (buf (current-buffer))
  13117. (expert (eq org-fast-tag-selection-single-key 'expert))
  13118. (buffer-tags nil)
  13119. (fwidth (+ maxlen 3 1 3))
  13120. (ncol (/ (- (window-width) 4) fwidth))
  13121. (i-face 'org-done)
  13122. (c-face 'org-todo)
  13123. tg cnt e c char c1 c2 ntable tbl rtn
  13124. ov-start ov-end ov-prefix
  13125. (exit-after-next org-fast-tag-selection-single-key)
  13126. (done-keywords org-done-keywords)
  13127. groups ingroup intaggroup)
  13128. (save-excursion
  13129. (beginning-of-line)
  13130. (if (looking-at org-tag-line-re)
  13131. (setq ov-start (match-beginning 1)
  13132. ov-end (match-end 1)
  13133. ov-prefix "")
  13134. (setq ov-start (1- (point-at-eol))
  13135. ov-end (1+ ov-start))
  13136. (skip-chars-forward "^\n\r")
  13137. (setq ov-prefix
  13138. (concat
  13139. (buffer-substring (1- (point)) (point))
  13140. (if (> (current-column) org-tags-column)
  13141. " "
  13142. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13143. (move-overlay org-tags-overlay ov-start ov-end)
  13144. (save-window-excursion
  13145. (if expert
  13146. (set-buffer (get-buffer-create " *Org tags*"))
  13147. (delete-other-windows)
  13148. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13149. (org-switch-to-buffer-other-window " *Org tags*"))
  13150. (erase-buffer)
  13151. (setq-local org-done-keywords done-keywords)
  13152. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13153. (org-fast-tag-insert "Current" current c-face "\n\n")
  13154. (org-fast-tag-show-exit exit-after-next)
  13155. (org-set-current-tags-overlay current ov-prefix)
  13156. (setq tbl fulltable char ?a cnt 0)
  13157. (while (setq e (pop tbl))
  13158. (cond
  13159. ((eq (car e) :startgroup)
  13160. (push '() groups) (setq ingroup t)
  13161. (unless (zerop cnt)
  13162. (setq cnt 0)
  13163. (insert "\n"))
  13164. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13165. ((eq (car e) :endgroup)
  13166. (setq ingroup nil cnt 0)
  13167. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13168. ((eq (car e) :startgrouptag)
  13169. (setq intaggroup t)
  13170. (unless (zerop cnt)
  13171. (setq cnt 0)
  13172. (insert "\n"))
  13173. (insert "[ "))
  13174. ((eq (car e) :endgrouptag)
  13175. (setq intaggroup nil cnt 0)
  13176. (insert "]\n"))
  13177. ((equal e '(:newline))
  13178. (unless (zerop cnt)
  13179. (setq cnt 0)
  13180. (insert "\n")
  13181. (setq e (car tbl))
  13182. (while (equal (car tbl) '(:newline))
  13183. (insert "\n")
  13184. (setq tbl (cdr tbl)))))
  13185. ((equal e '(:grouptags)) (insert " : "))
  13186. (t
  13187. (setq tg (copy-sequence (car e)) c2 nil)
  13188. (if (cdr e)
  13189. (setq c (cdr e))
  13190. ;; automatically assign a character.
  13191. (setq c1 (string-to-char
  13192. (downcase (substring
  13193. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13194. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13195. (while (or (rassoc char ntable) (rassoc char table))
  13196. (setq char (1+ char)))
  13197. (setq c2 c1))
  13198. (setq c (or c2 char)))
  13199. (when ingroup (push tg (car groups)))
  13200. (setq tg (org-add-props tg nil 'face
  13201. (cond
  13202. ((not (assoc tg table))
  13203. (org-get-todo-face tg))
  13204. ((member tg current) c-face)
  13205. ((member tg inherited) i-face))))
  13206. (when (equal (caar tbl) :grouptags)
  13207. (org-add-props tg nil 'face 'org-tag-group))
  13208. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13209. (insert "[" c "] " tg (make-string
  13210. (- fwidth 4 (length tg)) ?\ ))
  13211. (push (cons tg c) ntable)
  13212. (when (= (cl-incf cnt) ncol)
  13213. (insert "\n")
  13214. (when (or ingroup intaggroup) (insert " "))
  13215. (setq cnt 0)))))
  13216. (setq ntable (nreverse ntable))
  13217. (insert "\n")
  13218. (goto-char (point-min))
  13219. (unless expert (org-fit-window-to-buffer))
  13220. (setq rtn
  13221. (catch 'exit
  13222. (while t
  13223. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13224. (if (not groups) "no " "")
  13225. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13226. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13227. (setq org-last-tag-selection-key c)
  13228. (cond
  13229. ((= c ?\r) (throw 'exit t))
  13230. ((= c ?!)
  13231. (setq groups (not groups))
  13232. (goto-char (point-min))
  13233. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13234. ((= c ?\C-c)
  13235. (if (not expert)
  13236. (org-fast-tag-show-exit
  13237. (setq exit-after-next (not exit-after-next)))
  13238. (setq expert nil)
  13239. (delete-other-windows)
  13240. (set-window-buffer (split-window-vertically) " *Org tags*")
  13241. (org-switch-to-buffer-other-window " *Org tags*")
  13242. (org-fit-window-to-buffer)))
  13243. ((or (= c ?\C-g)
  13244. (and (= c ?q) (not (rassoc c ntable))))
  13245. (delete-overlay org-tags-overlay)
  13246. (setq quit-flag t))
  13247. ((= c ?\ )
  13248. (setq current nil)
  13249. (when exit-after-next (setq exit-after-next 'now)))
  13250. ((= c ?\t)
  13251. (condition-case nil
  13252. (setq tg (completing-read
  13253. "Tag: "
  13254. (or buffer-tags
  13255. (with-current-buffer buf
  13256. (setq buffer-tags
  13257. (org-get-buffer-tags))))))
  13258. (quit (setq tg "")))
  13259. (when (string-match "\\S-" tg)
  13260. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13261. (if (member tg current)
  13262. (setq current (delete tg current))
  13263. (push tg current)))
  13264. (when exit-after-next (setq exit-after-next 'now)))
  13265. ((setq e (rassoc c todo-table) tg (car e))
  13266. (with-current-buffer buf
  13267. (save-excursion (org-todo tg)))
  13268. (when exit-after-next (setq exit-after-next 'now)))
  13269. ((setq e (rassoc c ntable) tg (car e))
  13270. (if (member tg current)
  13271. (setq current (delete tg current))
  13272. (cl-loop for g in groups do
  13273. (when (member tg g)
  13274. (dolist (x g) (setq current (delete x current)))))
  13275. (push tg current))
  13276. (when exit-after-next (setq exit-after-next 'now))))
  13277. ;; Create a sorted list
  13278. (setq current
  13279. (sort current
  13280. (lambda (a b)
  13281. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13282. (when (eq exit-after-next 'now) (throw 'exit t))
  13283. (goto-char (point-min))
  13284. (beginning-of-line 2)
  13285. (delete-region (point) (point-at-eol))
  13286. (org-fast-tag-insert "Current" current c-face)
  13287. (org-set-current-tags-overlay current ov-prefix)
  13288. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13289. (while (re-search-forward tag-re nil t)
  13290. (let ((tag (match-string 1)))
  13291. (add-text-properties
  13292. (match-beginning 1) (match-end 1)
  13293. (list 'face
  13294. (cond
  13295. ((member tag current) c-face)
  13296. ((member tag inherited) i-face)
  13297. (t (get-text-property (match-beginning 1) '
  13298. face))))))))
  13299. (goto-char (point-min)))))
  13300. (delete-overlay org-tags-overlay)
  13301. (if rtn
  13302. (mapconcat 'identity current ":")
  13303. nil))))
  13304. (defun org-make-tag-string (tags)
  13305. "Return string associated to TAGS.
  13306. TAGS is a list of strings."
  13307. (if (null tags) ""
  13308. (format ":%s:" (mapconcat #'identity tags ":"))))
  13309. (defun org--get-local-tags ()
  13310. "Return list of tags for the current headline.
  13311. Assume point is at the beginning of the headline."
  13312. (and (looking-at org-tag-line-re)
  13313. (split-string (match-string-no-properties 2) ":" t)))
  13314. (defun org-get-tags (&optional pos local)
  13315. "Get the list of tags specified in the current headline.
  13316. When argument POS is non-nil, retrieve tags for headline at POS.
  13317. Accoring to `org-use-tags-inheritance', tags may be inherited
  13318. from parent headlines, and from the whole document, through
  13319. `org-file-tags'. However, when optional argument LOCAL is
  13320. non-nil, only return tags really specified in the considered
  13321. headline.
  13322. Inherited tags have the `inherited' text property."
  13323. (if (and org-trust-scanner-tags
  13324. (or (not pos) (eq pos (point)))
  13325. (not local))
  13326. org-scanner-tags
  13327. (org-with-point-at (or pos (point))
  13328. (unless (org-before-first-heading-p)
  13329. (org-back-to-heading t)
  13330. (let ((ltags (org--get-local-tags)) itags)
  13331. (if (or local (not org-use-tag-inheritance)) ltags
  13332. (setq itags org-file-tags)
  13333. (while (org-up-heading-safe)
  13334. (setq itags (append (mapcar #'org-add-prop-inherited
  13335. (org--get-local-tags))
  13336. itags)))
  13337. (delete-dups
  13338. (append (org-remove-uninherited-tags itags) ltags))))))))
  13339. (defun org-get-buffer-tags ()
  13340. "Get a table of all tags used in the buffer, for completion."
  13341. (org-with-point-at 1
  13342. (let (tags)
  13343. (while (re-search-forward org-tag-line-re nil t)
  13344. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13345. tags)))
  13346. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13347. ;;;; The mapping API
  13348. (defvar org-agenda-skip-comment-trees)
  13349. (defvar org-agenda-skip-function)
  13350. (defun org-map-entries (func &optional match scope &rest skip)
  13351. "Call FUNC at each headline selected by MATCH in SCOPE.
  13352. FUNC is a function or a lisp form. The function will be called without
  13353. arguments, with the cursor positioned at the beginning of the headline.
  13354. The return values of all calls to the function will be collected and
  13355. returned as a list.
  13356. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13357. does not need to preserve point. After evaluation, the cursor will be
  13358. moved to the end of the line (presumably of the headline of the
  13359. processed entry) and search continues from there. Under some
  13360. circumstances, this may not produce the wanted results. For example,
  13361. if you have removed (e.g. archived) the current (sub)tree it could
  13362. mean that the next entry will be skipped entirely. In such cases, you
  13363. can specify the position from where search should continue by making
  13364. FUNC set the variable `org-map-continue-from' to the desired buffer
  13365. position.
  13366. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13367. Only headlines that are matched by this query will be considered during
  13368. the iteration. When MATCH is nil or t, all headlines will be
  13369. visited by the iteration.
  13370. SCOPE determines the scope of this command. It can be any of:
  13371. nil The current buffer, respecting the restriction if any
  13372. tree The subtree started with the entry at point
  13373. region The entries within the active region, if any
  13374. region-start-level
  13375. The entries within the active region, but only those at
  13376. the same level than the first one.
  13377. file The current buffer, without restriction
  13378. file-with-archives
  13379. The current buffer, and any archives associated with it
  13380. agenda All agenda files
  13381. agenda-with-archives
  13382. All agenda files with any archive files associated with them
  13383. \(file1 file2 ...)
  13384. If this is a list, all files in the list will be scanned
  13385. The remaining args are treated as settings for the skipping facilities of
  13386. the scanner. The following items can be given here:
  13387. archive skip trees with the archive tag
  13388. comment skip trees with the COMMENT keyword
  13389. function or Emacs Lisp form:
  13390. will be used as value for `org-agenda-skip-function', so
  13391. whenever the function returns a position, FUNC will not be
  13392. called for that entry and search will continue from the
  13393. position returned
  13394. If your function needs to retrieve the tags including inherited tags
  13395. at the *current* entry, you can use the value of the variable
  13396. `org-scanner-tags' which will be much faster than getting the value
  13397. with `org-get-tags'. If your function gets properties with
  13398. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13399. to t around the call to `org-entry-properties' to get the same speedup.
  13400. Note that if your function moves around to retrieve tags and properties at
  13401. a *different* entry, you cannot use these techniques."
  13402. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13403. (not (org-region-active-p)))
  13404. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13405. (org-agenda-skip-archived-trees (memq 'archive skip))
  13406. (org-agenda-skip-comment-trees (memq 'comment skip))
  13407. (org-agenda-skip-function
  13408. (car (org-delete-all '(comment archive) skip)))
  13409. (org-tags-match-list-sublevels t)
  13410. (start-level (eq scope 'region-start-level))
  13411. matcher res
  13412. org-todo-keywords-for-agenda
  13413. org-done-keywords-for-agenda
  13414. org-todo-keyword-alist-for-agenda
  13415. org-tag-alist-for-agenda
  13416. org--matcher-tags-todo-only)
  13417. (cond
  13418. ((eq match t) (setq matcher t))
  13419. ((eq match nil) (setq matcher t))
  13420. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13421. (save-excursion
  13422. (save-restriction
  13423. (cond ((eq scope 'tree)
  13424. (org-back-to-heading t)
  13425. (org-narrow-to-subtree)
  13426. (setq scope nil))
  13427. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13428. (org-region-active-p))
  13429. ;; If needed, set start-level to a string like "2"
  13430. (when start-level
  13431. (save-excursion
  13432. (goto-char (region-beginning))
  13433. (unless (org-at-heading-p) (outline-next-heading))
  13434. (setq start-level (org-current-level))))
  13435. (narrow-to-region (region-beginning)
  13436. (save-excursion
  13437. (goto-char (region-end))
  13438. (unless (and (bolp) (org-at-heading-p))
  13439. (outline-next-heading))
  13440. (point)))
  13441. (setq scope nil)))
  13442. (if (not scope)
  13443. (progn
  13444. (org-agenda-prepare-buffers
  13445. (and buffer-file-name (list buffer-file-name)))
  13446. (setq res
  13447. (org-scan-tags
  13448. func matcher org--matcher-tags-todo-only start-level)))
  13449. ;; Get the right scope
  13450. (cond
  13451. ((and scope (listp scope) (symbolp (car scope)))
  13452. (setq scope (eval scope)))
  13453. ((eq scope 'agenda)
  13454. (setq scope (org-agenda-files t)))
  13455. ((eq scope 'agenda-with-archives)
  13456. (setq scope (org-agenda-files t))
  13457. (setq scope (org-add-archive-files scope)))
  13458. ((eq scope 'file)
  13459. (setq scope (and buffer-file-name (list buffer-file-name))))
  13460. ((eq scope 'file-with-archives)
  13461. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13462. (org-agenda-prepare-buffers scope)
  13463. (dolist (file scope)
  13464. (with-current-buffer (org-find-base-buffer-visiting file)
  13465. (org-with-wide-buffer
  13466. (goto-char (point-min))
  13467. (setq res
  13468. (append
  13469. res
  13470. (org-scan-tags
  13471. func matcher org--matcher-tags-todo-only)))))))))
  13472. res)))
  13473. ;;; Properties API
  13474. (defconst org-special-properties
  13475. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13476. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13477. "The special properties valid in Org mode.
  13478. These are properties that are not defined in the property drawer,
  13479. but in some other way.")
  13480. (defconst org-default-properties
  13481. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13482. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13483. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13484. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13485. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13486. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13487. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13488. "Some properties that are used by Org mode for various purposes.
  13489. Being in this list makes sure that they are offered for completion.")
  13490. (defun org--valid-property-p (property)
  13491. "Non nil when string PROPERTY is a valid property name."
  13492. (not
  13493. (or (equal property "")
  13494. (string-match-p "\\s-" property))))
  13495. (defun org--update-property-plist (key val props)
  13496. "Associate KEY to VAL in alist PROPS.
  13497. Modifications are made by side-effect. Return new alist."
  13498. (let* ((appending (string= (substring key -1) "+"))
  13499. (key (if appending (substring key 0 -1) key))
  13500. (old (assoc-string key props t)))
  13501. (if (not old) (cons (cons key val) props)
  13502. (setcdr old (if appending (concat (cdr old) " " val) val))
  13503. props)))
  13504. (defun org-get-property-block (&optional beg force)
  13505. "Return the (beg . end) range of the body of the property drawer.
  13506. BEG is the beginning of the current subtree, or of the part
  13507. before the first headline. If it is not given, it will be found.
  13508. If the drawer does not exist, create it if FORCE is non-nil, or
  13509. return nil."
  13510. (org-with-wide-buffer
  13511. (when beg (goto-char beg))
  13512. (unless (org-before-first-heading-p)
  13513. (let ((beg (cond (beg)
  13514. ((or (not (featurep 'org-inlinetask))
  13515. (org-inlinetask-in-task-p))
  13516. (org-back-to-heading t))
  13517. (t (org-with-limited-levels (org-back-to-heading t))))))
  13518. (forward-line)
  13519. (when (looking-at-p org-planning-line-re) (forward-line))
  13520. (cond ((looking-at org-property-drawer-re)
  13521. (forward-line)
  13522. (cons (point) (progn (goto-char (match-end 0))
  13523. (line-beginning-position))))
  13524. (force
  13525. (goto-char beg)
  13526. (org-insert-property-drawer)
  13527. (let ((pos (save-excursion (search-forward ":END:")
  13528. (line-beginning-position))))
  13529. (cons pos pos))))))))
  13530. (defun org-at-property-p ()
  13531. "Non-nil when point is inside a property drawer.
  13532. See `org-property-re' for match data, if applicable."
  13533. (save-excursion
  13534. (beginning-of-line)
  13535. (and (looking-at org-property-re)
  13536. (let ((property-drawer (save-match-data (org-get-property-block))))
  13537. (and property-drawer
  13538. (>= (point) (car property-drawer))
  13539. (< (point) (cdr property-drawer)))))))
  13540. (defun org-property-action ()
  13541. "Do an action on properties."
  13542. (interactive)
  13543. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13544. (let ((c (read-char-exclusive)))
  13545. (cl-case c
  13546. (?s (call-interactively #'org-set-property))
  13547. (?d (call-interactively #'org-delete-property))
  13548. (?D (call-interactively #'org-delete-property-globally))
  13549. (?c (call-interactively #'org-compute-property-at-point))
  13550. (otherwise (user-error "No such property action %c" c)))))
  13551. (defun org-inc-effort ()
  13552. "Increment the value of the effort property in the current entry."
  13553. (interactive)
  13554. (org-set-effort t))
  13555. (defvar org-clock-effort) ; Defined in org-clock.el.
  13556. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13557. (defun org-set-effort (&optional increment value)
  13558. "Set the effort property of the current entry.
  13559. If INCREMENT is non-nil, set the property to the next allowed
  13560. value. Otherwise, if optional argument VALUE is provided, use
  13561. it. Eventually, prompt for the new value if none of the previous
  13562. variables is set."
  13563. (interactive "P")
  13564. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13565. (current (org-entry-get nil org-effort-property))
  13566. (value
  13567. (cond
  13568. (increment
  13569. (unless allowed (user-error "Allowed effort values are not set"))
  13570. (or (cl-caadr (member (list current) allowed))
  13571. (user-error "Unknown value %S among allowed values" current)))
  13572. (value
  13573. (if (stringp value) value
  13574. (error "Invalid effort value: %S" value)))
  13575. (t
  13576. (let ((must-match
  13577. (and allowed
  13578. (not (get-text-property 0 'org-unrestricted
  13579. (caar allowed))))))
  13580. (completing-read "Effort: " allowed nil must-match))))))
  13581. (unless (equal current value)
  13582. (org-entry-put nil org-effort-property value))
  13583. (org-refresh-property '((effort . identity)
  13584. (effort-minutes . org-duration-to-minutes))
  13585. value)
  13586. (when (equal (org-get-heading t t t t)
  13587. (bound-and-true-p org-clock-current-task))
  13588. (setq org-clock-effort (org-get-at-bol 'effort))
  13589. (org-clock-update-mode-line))
  13590. (message "%s is now %s" org-effort-property value)))
  13591. (defun org-entry-properties (&optional pom which)
  13592. "Get all properties of the current entry.
  13593. When POM is a buffer position, get all properties from the entry
  13594. there instead.
  13595. This includes the TODO keyword, the tags, time strings for
  13596. deadline, scheduled, and clocking, and any additional properties
  13597. defined in the entry.
  13598. If WHICH is nil or `all', get all properties. If WHICH is
  13599. `special' or `standard', only get that subclass. If WHICH is
  13600. a string, only get that property.
  13601. Return value is an alist. Keys are properties, as upcased
  13602. strings."
  13603. (org-with-point-at pom
  13604. (when (and (derived-mode-p 'org-mode)
  13605. (ignore-errors (org-back-to-heading t)))
  13606. (catch 'exit
  13607. (let* ((beg (point))
  13608. (specific (and (stringp which) (upcase which)))
  13609. (which (cond ((not specific) which)
  13610. ((member specific org-special-properties) 'special)
  13611. (t 'standard)))
  13612. props)
  13613. ;; Get the special properties, like TODO and TAGS.
  13614. (when (memq which '(nil all special))
  13615. (when (or (not specific) (string= specific "CLOCKSUM"))
  13616. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13617. (when clocksum
  13618. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13619. props)))
  13620. (when specific (throw 'exit props)))
  13621. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13622. (let ((clocksumt (get-text-property (point)
  13623. :org-clock-minutes-today)))
  13624. (when clocksumt
  13625. (push (cons "CLOCKSUM_T"
  13626. (org-duration-from-minutes clocksumt))
  13627. props)))
  13628. (when specific (throw 'exit props)))
  13629. (when (or (not specific) (string= specific "ITEM"))
  13630. (let ((case-fold-search nil))
  13631. (when (looking-at org-complex-heading-regexp)
  13632. (push (cons "ITEM"
  13633. (let ((title (match-string-no-properties 4)))
  13634. (if (org-string-nw-p title)
  13635. (org-remove-tabs title)
  13636. "")))
  13637. props)))
  13638. (when specific (throw 'exit props)))
  13639. (when (or (not specific) (string= specific "TODO"))
  13640. (let ((case-fold-search nil))
  13641. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13642. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13643. (when specific (throw 'exit props)))
  13644. (when (or (not specific) (string= specific "PRIORITY"))
  13645. (push (cons "PRIORITY"
  13646. (if (looking-at org-priority-regexp)
  13647. (match-string-no-properties 2)
  13648. (char-to-string org-default-priority)))
  13649. props)
  13650. (when specific (throw 'exit props)))
  13651. (when (or (not specific) (string= specific "FILE"))
  13652. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13653. props)
  13654. (when specific (throw 'exit props)))
  13655. (when (or (not specific) (string= specific "TAGS"))
  13656. (let ((tags (org-get-tags nil t)))
  13657. (when tags
  13658. (push (cons "TAGS" (org-make-tag-string tags))
  13659. props)))
  13660. (when specific (throw 'exit props)))
  13661. (when (or (not specific) (string= specific "ALLTAGS"))
  13662. (let ((tags (org-get-tags)))
  13663. (when tags
  13664. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13665. props)))
  13666. (when specific (throw 'exit props)))
  13667. (when (or (not specific) (string= specific "BLOCKED"))
  13668. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13669. (when specific (throw 'exit props)))
  13670. (when (or (not specific)
  13671. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13672. (forward-line)
  13673. (when (looking-at-p org-planning-line-re)
  13674. (end-of-line)
  13675. (let ((bol (line-beginning-position))
  13676. ;; Backward compatibility: time keywords used to
  13677. ;; be configurable (before 8.3). Make sure we
  13678. ;; get the correct keyword.
  13679. (key-assoc `(("CLOSED" . ,org-closed-string)
  13680. ("DEADLINE" . ,org-deadline-string)
  13681. ("SCHEDULED" . ,org-scheduled-string))))
  13682. (dolist (pair (if specific (list (assoc specific key-assoc))
  13683. key-assoc))
  13684. (save-excursion
  13685. (when (search-backward (cdr pair) bol t)
  13686. (goto-char (match-end 0))
  13687. (skip-chars-forward " \t")
  13688. (and (looking-at org-ts-regexp-both)
  13689. (push (cons (car pair)
  13690. (match-string-no-properties 0))
  13691. props)))))))
  13692. (when specific (throw 'exit props)))
  13693. (when (or (not specific)
  13694. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13695. (let ((find-ts
  13696. (lambda (end ts)
  13697. ;; Fix next time-stamp before END. TS is the
  13698. ;; list of time-stamps found so far.
  13699. (let ((ts ts)
  13700. (regexp (cond
  13701. ((string= specific "TIMESTAMP")
  13702. org-ts-regexp)
  13703. ((string= specific "TIMESTAMP_IA")
  13704. org-ts-regexp-inactive)
  13705. ((assoc "TIMESTAMP_IA" ts)
  13706. org-ts-regexp)
  13707. ((assoc "TIMESTAMP" ts)
  13708. org-ts-regexp-inactive)
  13709. (t org-ts-regexp-both))))
  13710. (catch 'next
  13711. (while (re-search-forward regexp end t)
  13712. (backward-char)
  13713. (let ((object (org-element-context)))
  13714. ;; Accept to match timestamps in node
  13715. ;; properties, too.
  13716. (when (memq (org-element-type object)
  13717. '(node-property timestamp))
  13718. (let ((type
  13719. (org-element-property :type object)))
  13720. (cond
  13721. ((and (memq type '(active active-range))
  13722. (not (equal specific "TIMESTAMP_IA")))
  13723. (unless (assoc "TIMESTAMP" ts)
  13724. (push (cons "TIMESTAMP"
  13725. (org-element-property
  13726. :raw-value object))
  13727. ts)
  13728. (when specific (throw 'exit ts))))
  13729. ((and (memq type '(inactive inactive-range))
  13730. (not (string= specific "TIMESTAMP")))
  13731. (unless (assoc "TIMESTAMP_IA" ts)
  13732. (push (cons "TIMESTAMP_IA"
  13733. (org-element-property
  13734. :raw-value object))
  13735. ts)
  13736. (when specific (throw 'exit ts))))))
  13737. ;; Both timestamp types are found,
  13738. ;; move to next part.
  13739. (when (= (length ts) 2) (throw 'next ts)))))
  13740. ts)))))
  13741. (goto-char beg)
  13742. ;; First look for timestamps within headline.
  13743. (let ((ts (funcall find-ts (line-end-position) nil)))
  13744. (if (= (length ts) 2) (setq props (nconc ts props))
  13745. ;; Then find timestamps in the section, skipping
  13746. ;; planning line.
  13747. (let ((end (save-excursion (outline-next-heading))))
  13748. (forward-line)
  13749. (when (looking-at-p org-planning-line-re) (forward-line))
  13750. (setq props (nconc (funcall find-ts end ts) props))))))))
  13751. ;; Get the standard properties, like :PROP:.
  13752. (when (memq which '(nil all standard))
  13753. ;; If we are looking after a specific property, delegate
  13754. ;; to `org-entry-get', which is faster. However, make an
  13755. ;; exception for "CATEGORY", since it can be also set
  13756. ;; through keywords (i.e. #+CATEGORY).
  13757. (if (and specific (not (equal specific "CATEGORY")))
  13758. (let ((value (org-entry-get beg specific nil t)))
  13759. (throw 'exit (and value (list (cons specific value)))))
  13760. (let ((range (org-get-property-block beg)))
  13761. (when range
  13762. (let ((end (cdr range)) seen-base)
  13763. (goto-char (car range))
  13764. ;; Unlike to `org--update-property-plist', we
  13765. ;; handle the case where base values is found
  13766. ;; after its extension. We also forbid standard
  13767. ;; properties to be named as special properties.
  13768. (while (re-search-forward org-property-re end t)
  13769. (let* ((key (upcase (match-string-no-properties 2)))
  13770. (extendp (string-match-p "\\+\\'" key))
  13771. (key-base (if extendp (substring key 0 -1) key))
  13772. (value (match-string-no-properties 3)))
  13773. (cond
  13774. ((member-ignore-case key-base org-special-properties))
  13775. (extendp
  13776. (setq props
  13777. (org--update-property-plist key value props)))
  13778. ((member key seen-base))
  13779. (t (push key seen-base)
  13780. (let ((p (assoc-string key props t)))
  13781. (if p (setcdr p (concat value " " (cdr p)))
  13782. (push (cons key value) props))))))))))))
  13783. (unless (assoc "CATEGORY" props)
  13784. (push (cons "CATEGORY" (org-get-category beg)) props)
  13785. (when (string= specific "CATEGORY") (throw 'exit props)))
  13786. ;; Return value.
  13787. props)))))
  13788. (defun org--property-local-values (property literal-nil)
  13789. "Return value for PROPERTY in current entry.
  13790. Value is a list whose car is the base value for PROPERTY and cdr
  13791. a list of accumulated values. Return nil if neither is found in
  13792. the entry. Also return nil when PROPERTY is set to \"nil\",
  13793. unless LITERAL-NIL is non-nil."
  13794. (let ((range (org-get-property-block)))
  13795. (when range
  13796. (goto-char (car range))
  13797. (let* ((case-fold-search t)
  13798. (end (cdr range))
  13799. (value
  13800. ;; Base value.
  13801. (save-excursion
  13802. (let ((v (and (re-search-forward
  13803. (org-re-property property nil t) end t)
  13804. (match-string-no-properties 3))))
  13805. (list (if literal-nil v (org-not-nil v)))))))
  13806. ;; Find additional values.
  13807. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13808. (while (re-search-forward property+ end t)
  13809. (push (match-string-no-properties 3) value)))
  13810. ;; Return final values.
  13811. (and (not (equal value '(nil))) (nreverse value))))))
  13812. (defun org--property-global-value (property literal-nil)
  13813. "Return value for PROPERTY in current buffer.
  13814. Return value is a string. Return nil if property is not set
  13815. globally. Also return nil when PROPERTY is set to \"nil\",
  13816. unless LITERAL-NIL is non-nil."
  13817. (let ((global
  13818. (cdr (or (assoc-string property org-file-properties t)
  13819. (assoc-string property org-global-properties t)
  13820. (assoc-string property org-global-properties-fixed t)))))
  13821. (if literal-nil global (org-not-nil global))))
  13822. (defun org-entry-get (pom property &optional inherit literal-nil)
  13823. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13824. If INHERIT is non-nil and the entry does not have the property,
  13825. then also check higher levels of the hierarchy. If INHERIT is
  13826. the symbol `selective', use inheritance only if the setting in
  13827. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13828. If the property is present but empty, the return value is the
  13829. empty string. If the property is not present at all, nil is
  13830. returned. In any other case, return the value as a string.
  13831. Search is case-insensitive.
  13832. If LITERAL-NIL is set, return the string value \"nil\" as
  13833. a string, do not interpret it as the list atom nil. This is used
  13834. for inheritance when a \"nil\" value can supersede a non-nil
  13835. value higher up the hierarchy."
  13836. (org-with-point-at pom
  13837. (cond
  13838. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13839. ;; We need a special property. Use `org-entry-properties' to
  13840. ;; retrieve it, but specify the wanted property.
  13841. (cdr (assoc-string property (org-entry-properties nil property))))
  13842. ((and inherit
  13843. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13844. (org-entry-get-with-inheritance property literal-nil))
  13845. (t
  13846. (let* ((local (org--property-local-values property literal-nil))
  13847. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13848. (if literal-nil value (org-not-nil value)))))))
  13849. (defun org-property-or-variable-value (var &optional inherit)
  13850. "Check if there is a property fixing the value of VAR.
  13851. If yes, return this value. If not, return the current value of the variable."
  13852. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13853. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13854. (read prop)
  13855. (symbol-value var))))
  13856. (defun org-entry-delete (pom property)
  13857. "Delete PROPERTY from entry at point-or-marker POM.
  13858. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13859. non-nil when a property was removed."
  13860. (org-with-point-at pom
  13861. (pcase (org-get-property-block)
  13862. (`(,begin . ,origin)
  13863. (let* ((end (copy-marker origin))
  13864. (re (org-re-property
  13865. (concat (regexp-quote property) "\\+?") t t)))
  13866. (goto-char begin)
  13867. (while (re-search-forward re end t)
  13868. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13869. ;; If drawer is empty, remove it altogether.
  13870. (when (= begin end)
  13871. (delete-region (line-beginning-position 0)
  13872. (line-beginning-position 2)))
  13873. ;; Return non-nil if some property was removed.
  13874. (prog1 (/= end origin) (set-marker end nil))))
  13875. (_ nil))))
  13876. ;; Multi-values properties are properties that contain multiple values
  13877. ;; These values are assumed to be single words, separated by whitespace.
  13878. (defun org-entry-add-to-multivalued-property (pom property value)
  13879. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13880. (let* ((old (org-entry-get pom property))
  13881. (values (and old (split-string old))))
  13882. (setq value (org-entry-protect-space value))
  13883. (unless (member value values)
  13884. (setq values (append values (list value)))
  13885. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13886. (defun org-entry-remove-from-multivalued-property (pom property value)
  13887. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13888. (let* ((old (org-entry-get pom property))
  13889. (values (and old (split-string old))))
  13890. (setq value (org-entry-protect-space value))
  13891. (when (member value values)
  13892. (setq values (delete value values))
  13893. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13894. (defun org-entry-member-in-multivalued-property (pom property value)
  13895. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13896. (let* ((old (org-entry-get pom property))
  13897. (values (and old (split-string old))))
  13898. (setq value (org-entry-protect-space value))
  13899. (member value values)))
  13900. (defun org-entry-get-multivalued-property (pom property)
  13901. "Return a list of values in a multivalued property."
  13902. (let* ((value (org-entry-get pom property))
  13903. (values (and value (split-string value))))
  13904. (mapcar #'org-entry-restore-space values)))
  13905. (defun org-entry-put-multivalued-property (pom property &rest values)
  13906. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13907. VALUES should be a list of strings. Spaces will be protected."
  13908. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13909. (let* ((value (org-entry-get pom property))
  13910. (values (and value (split-string value))))
  13911. (mapcar #'org-entry-restore-space values)))
  13912. (defun org-entry-protect-space (s)
  13913. "Protect spaces and newline in string S."
  13914. (while (string-match " " s)
  13915. (setq s (replace-match "%20" t t s)))
  13916. (while (string-match "\n" s)
  13917. (setq s (replace-match "%0A" t t s)))
  13918. s)
  13919. (defun org-entry-restore-space (s)
  13920. "Restore spaces and newline in string S."
  13921. (while (string-match "%20" s)
  13922. (setq s (replace-match " " t t s)))
  13923. (while (string-match "%0A" s)
  13924. (setq s (replace-match "\n" t t s)))
  13925. s)
  13926. (defvar org-entry-property-inherited-from (make-marker)
  13927. "Marker pointing to the entry from where a property was inherited.
  13928. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13929. location of the entry where the inheritance search matched. If there was
  13930. no match, the marker will point nowhere.
  13931. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13932. is set.")
  13933. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13934. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13935. The search will stop at the first ancestor which has the property defined.
  13936. If the value found is \"nil\", return nil to show that the property
  13937. should be considered as undefined (this is the meaning of nil here).
  13938. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13939. (move-marker org-entry-property-inherited-from nil)
  13940. (org-with-wide-buffer
  13941. (let (value)
  13942. (catch 'exit
  13943. (while t
  13944. (let ((v (org--property-local-values property literal-nil)))
  13945. (when v
  13946. (setq value
  13947. (concat (mapconcat #'identity (delq nil v) " ")
  13948. (and value " ")
  13949. value)))
  13950. (cond
  13951. ((car v)
  13952. (org-back-to-heading t)
  13953. (move-marker org-entry-property-inherited-from (point))
  13954. (throw 'exit nil))
  13955. ((org-up-heading-safe))
  13956. (t
  13957. (let ((global (org--property-global-value property literal-nil)))
  13958. (cond ((not global))
  13959. (value (setq value (concat global " " value)))
  13960. (t (setq value global))))
  13961. (throw 'exit nil))))))
  13962. (if literal-nil value (org-not-nil value)))))
  13963. (defvar org-property-changed-functions nil
  13964. "Hook called when the value of a property has changed.
  13965. Each hook function should accept two arguments, the name of the property
  13966. and the new value.")
  13967. (defun org-entry-put (pom property value)
  13968. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13969. If the value is nil, it is converted to the empty string. If it
  13970. is not a string, an error is raised. Also raise an error on
  13971. invalid property names.
  13972. PROPERTY can be any regular property (see
  13973. `org-special-properties'). It can also be \"TODO\",
  13974. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13975. For the last two properties, VALUE may have any of the special
  13976. values \"earlier\" and \"later\". The function then increases or
  13977. decreases scheduled or deadline date by one day."
  13978. (cond ((null value) (setq value ""))
  13979. ((not (stringp value)) (error "Properties values should be strings"))
  13980. ((not (org--valid-property-p property))
  13981. (user-error "Invalid property name: \"%s\"" property)))
  13982. (org-with-point-at pom
  13983. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13984. (org-back-to-heading t)
  13985. (org-with-limited-levels (org-back-to-heading t)))
  13986. (let ((beg (point)))
  13987. (cond
  13988. ((equal property "TODO")
  13989. (cond ((not (org-string-nw-p value)) (setq value 'none))
  13990. ((not (member value org-todo-keywords-1))
  13991. (user-error "\"%s\" is not a valid TODO state" value)))
  13992. (org-todo value)
  13993. (org-align-tags))
  13994. ((equal property "PRIORITY")
  13995. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  13996. (org-align-tags))
  13997. ((equal property "SCHEDULED")
  13998. (forward-line)
  13999. (if (and (looking-at-p org-planning-line-re)
  14000. (re-search-forward
  14001. org-scheduled-time-regexp (line-end-position) t))
  14002. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14003. ((string= value "later") (org-timestamp-change 1 'day))
  14004. ((string= value "") (org-schedule '(4)))
  14005. (t (org-schedule nil value)))
  14006. (if (member value '("earlier" "later" ""))
  14007. (call-interactively #'org-schedule)
  14008. (org-schedule nil value))))
  14009. ((equal property "DEADLINE")
  14010. (forward-line)
  14011. (if (and (looking-at-p org-planning-line-re)
  14012. (re-search-forward
  14013. org-deadline-time-regexp (line-end-position) t))
  14014. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14015. ((string= value "later") (org-timestamp-change 1 'day))
  14016. ((string= value "") (org-deadline '(4)))
  14017. (t (org-deadline nil value)))
  14018. (if (member value '("earlier" "later" ""))
  14019. (call-interactively #'org-deadline)
  14020. (org-deadline nil value))))
  14021. ((member property org-special-properties)
  14022. (error "The %s property cannot be set with `org-entry-put'" property))
  14023. (t
  14024. (let* ((range (org-get-property-block beg 'force))
  14025. (end (cdr range))
  14026. (case-fold-search t))
  14027. (goto-char (car range))
  14028. (if (re-search-forward (org-re-property property nil t) end t)
  14029. (progn (delete-region (match-beginning 0) (match-end 0))
  14030. (goto-char (match-beginning 0)))
  14031. (goto-char end)
  14032. (insert "\n")
  14033. (backward-char))
  14034. (insert ":" property ":")
  14035. (when value (insert " " value))
  14036. (org-indent-line)))))
  14037. (run-hook-with-args 'org-property-changed-functions property value)))
  14038. (defun org-buffer-property-keys (&optional specials defaults columns)
  14039. "Get all property keys in the current buffer.
  14040. When SPECIALS is non-nil, also list the special properties that
  14041. reflect things like tags and TODO state.
  14042. When DEFAULTS is non-nil, also include properties that has
  14043. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14044. DESCRIPTION, LOCATION, and LOGGING and others.
  14045. When COLUMNS in non-nil, also include property names given in
  14046. COLUMN formats in the current buffer."
  14047. (let ((case-fold-search t)
  14048. (props (append
  14049. (and specials org-special-properties)
  14050. (and defaults (cons org-effort-property org-default-properties))
  14051. nil)))
  14052. (org-with-wide-buffer
  14053. (goto-char (point-min))
  14054. (while (re-search-forward org-property-start-re nil t)
  14055. (catch :skip
  14056. (let ((range (org-get-property-block)))
  14057. (unless range (throw :skip nil))
  14058. (goto-char (car range))
  14059. (let ((begin (car range))
  14060. (end (cdr range)))
  14061. ;; Make sure that found property block is not located
  14062. ;; before current point, as it would generate an infloop.
  14063. ;; It can happen, for example, in the following
  14064. ;; situation:
  14065. ;;
  14066. ;; * Headline
  14067. ;; :PROPERTIES:
  14068. ;; ...
  14069. ;; :END:
  14070. ;; *************** Inlinetask
  14071. ;; #+BEGIN_EXAMPLE
  14072. ;; :PROPERTIES:
  14073. ;; #+END_EXAMPLE
  14074. ;;
  14075. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14076. (while (< (point) end)
  14077. (let ((p (progn (looking-at org-property-re)
  14078. (match-string-no-properties 2))))
  14079. ;; Only add true property name, not extension symbol.
  14080. (push (if (not (string-match-p "\\+\\'" p)) p
  14081. (substring p 0 -1))
  14082. props))
  14083. (forward-line))))
  14084. (outline-next-heading)))
  14085. (when columns
  14086. (goto-char (point-min))
  14087. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14088. (let ((element (org-element-at-point)))
  14089. (when (memq (org-element-type element) '(keyword node-property))
  14090. (let ((value (org-element-property :value element))
  14091. (start 0))
  14092. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14093. \\(?:{[^}]+}\\)?"
  14094. value start)
  14095. (setq start (match-end 0))
  14096. (let ((p (match-string-no-properties 1 value)))
  14097. (unless (member-ignore-case p org-special-properties)
  14098. (push p props))))))))))
  14099. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14100. (defun org-property-values (key)
  14101. "List all non-nil values of property KEY in current buffer."
  14102. (org-with-wide-buffer
  14103. (goto-char (point-min))
  14104. (let ((case-fold-search t)
  14105. (re (org-re-property key))
  14106. values)
  14107. (while (re-search-forward re nil t)
  14108. (push (org-entry-get (point) key) values))
  14109. (delete-dups values))))
  14110. (defun org-insert-property-drawer ()
  14111. "Insert a property drawer into the current entry."
  14112. (org-with-wide-buffer
  14113. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14114. (org-back-to-heading t)
  14115. (org-with-limited-levels (org-back-to-heading t)))
  14116. (forward-line)
  14117. (when (looking-at-p org-planning-line-re) (forward-line))
  14118. (unless (looking-at-p org-property-drawer-re)
  14119. ;; Make sure we start editing a line from current entry, not from
  14120. ;; next one. It prevents extending text properties or overlays
  14121. ;; belonging to the latter.
  14122. (when (bolp) (backward-char))
  14123. (let ((begin (1+ (point)))
  14124. (inhibit-read-only t))
  14125. (insert "\n:PROPERTIES:\n:END:")
  14126. (when (eobp) (insert "\n"))
  14127. (org-indent-region begin (point))))))
  14128. (defun org-insert-drawer (&optional arg drawer)
  14129. "Insert a drawer at point.
  14130. When optional argument ARG is non-nil, insert a property drawer.
  14131. Optional argument DRAWER, when non-nil, is a string representing
  14132. drawer's name. Otherwise, the user is prompted for a name.
  14133. If a region is active, insert the drawer around that region
  14134. instead.
  14135. Point is left between drawer's boundaries."
  14136. (interactive "P")
  14137. (let* ((drawer (if arg "PROPERTIES"
  14138. (or drawer (read-from-minibuffer "Drawer: ")))))
  14139. (cond
  14140. ;; With C-u, fall back on `org-insert-property-drawer'
  14141. (arg (org-insert-property-drawer))
  14142. ;; Check validity of suggested drawer's name.
  14143. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14144. (user-error "Invalid drawer name"))
  14145. ;; With an active region, insert a drawer at point.
  14146. ((not (org-region-active-p))
  14147. (progn
  14148. (unless (bolp) (insert "\n"))
  14149. (insert (format ":%s:\n\n:END:\n" drawer))
  14150. (forward-line -2)))
  14151. ;; Otherwise, insert the drawer at point
  14152. (t
  14153. (let ((rbeg (region-beginning))
  14154. (rend (copy-marker (region-end))))
  14155. (unwind-protect
  14156. (progn
  14157. (goto-char rbeg)
  14158. (beginning-of-line)
  14159. (when (save-excursion
  14160. (re-search-forward org-outline-regexp-bol rend t))
  14161. (user-error "Drawers cannot contain headlines"))
  14162. ;; Position point at the beginning of the first
  14163. ;; non-blank line in region. Insert drawer's opening
  14164. ;; there, then indent it.
  14165. (org-skip-whitespace)
  14166. (beginning-of-line)
  14167. (insert ":" drawer ":\n")
  14168. (forward-line -1)
  14169. (indent-for-tab-command)
  14170. ;; Move point to the beginning of the first blank line
  14171. ;; after the last non-blank line in region. Insert
  14172. ;; drawer's closing, then indent it.
  14173. (goto-char rend)
  14174. (skip-chars-backward " \r\t\n")
  14175. (insert "\n:END:")
  14176. (deactivate-mark t)
  14177. (indent-for-tab-command)
  14178. (unless (eolp) (insert "\n")))
  14179. ;; Clear marker, whatever the outcome of insertion is.
  14180. (set-marker rend nil)))))))
  14181. (defvar org-property-set-functions-alist nil
  14182. "Property set function alist.
  14183. Each entry should have the following format:
  14184. (PROPERTY . READ-FUNCTION)
  14185. The read function will be called with the same argument as
  14186. `org-completing-read'.")
  14187. (defun org-set-property-function (property)
  14188. "Get the function that should be used to set PROPERTY.
  14189. This is computed according to `org-property-set-functions-alist'."
  14190. (or (cdr (assoc property org-property-set-functions-alist))
  14191. 'org-completing-read))
  14192. (defun org-read-property-value (property &optional pom)
  14193. "Read value for PROPERTY, as a string.
  14194. When optional argument POM is non-nil, completion uses additional
  14195. information, i.e., allowed or existing values at point or marker
  14196. POM."
  14197. (let* ((completion-ignore-case t)
  14198. (allowed
  14199. (or (org-property-get-allowed-values nil property 'table)
  14200. (and pom (org-property-get-allowed-values pom property 'table))))
  14201. (current (org-entry-get nil property))
  14202. (prompt (format "%s value%s: "
  14203. property
  14204. (if (org-string-nw-p current)
  14205. (format " [%s]" current)
  14206. "")))
  14207. (set-function (org-set-property-function property)))
  14208. (org-trim
  14209. (if allowed
  14210. (funcall set-function
  14211. prompt allowed nil
  14212. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  14213. (let ((all (mapcar #'list
  14214. (append (org-property-values property)
  14215. (and pom
  14216. (org-with-point-at pom
  14217. (org-property-values property)))))))
  14218. (funcall set-function prompt all nil nil "" nil current))))))
  14219. (defvar org-last-set-property nil)
  14220. (defvar org-last-set-property-value nil)
  14221. (defun org-read-property-name ()
  14222. "Read a property name."
  14223. (let ((completion-ignore-case t)
  14224. (default-prop (or (and (org-at-property-p)
  14225. (match-string-no-properties 2))
  14226. org-last-set-property)))
  14227. (org-completing-read
  14228. (concat "Property"
  14229. (if default-prop (concat " [" default-prop "]") "")
  14230. ": ")
  14231. (mapcar #'list (org-buffer-property-keys nil t t))
  14232. nil nil nil nil default-prop)))
  14233. (defun org-set-property-and-value (use-last)
  14234. "Allow to set [PROPERTY]: [value] direction from prompt.
  14235. When use-default, don't even ask, just use the last
  14236. \"[PROPERTY]: [value]\" string from the history."
  14237. (interactive "P")
  14238. (let* ((completion-ignore-case t)
  14239. (pv (or (and use-last org-last-set-property-value)
  14240. (org-completing-read
  14241. "Enter a \"[Property]: [value]\" pair: "
  14242. nil nil nil nil nil
  14243. org-last-set-property-value)))
  14244. prop val)
  14245. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14246. (setq prop (match-string 1 pv)
  14247. val (match-string 2 pv))
  14248. (org-set-property prop val))))
  14249. (defun org-set-property (property value)
  14250. "In the current entry, set PROPERTY to VALUE.
  14251. When called interactively, this will prompt for a property name, offering
  14252. completion on existing and default properties. And then it will prompt
  14253. for a value, offering completion either on allowed values (via an inherited
  14254. xxx_ALL property) or on existing values in other instances of this property
  14255. in the current file.
  14256. Throw an error when trying to set a property with an invalid name."
  14257. (interactive (list nil nil))
  14258. (let ((property (or property (org-read-property-name))))
  14259. ;; `org-entry-put' also makes the following check, but this one
  14260. ;; avoids polluting `org-last-set-property' and
  14261. ;; `org-last-set-property-value' needlessly.
  14262. (unless (org--valid-property-p property)
  14263. (user-error "Invalid property name: \"%s\"" property))
  14264. (let ((value (or value (org-read-property-value property)))
  14265. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14266. (setq org-last-set-property property)
  14267. (setq org-last-set-property-value (concat property ": " value))
  14268. ;; Possibly postprocess the inserted value:
  14269. (when fn (setq value (funcall fn value)))
  14270. (unless (equal (org-entry-get nil property) value)
  14271. (org-entry-put nil property value)))))
  14272. (defun org-find-property (property &optional value)
  14273. "Find first entry in buffer that sets PROPERTY.
  14274. When optional argument VALUE is non-nil, only consider an entry
  14275. if it contains PROPERTY set to this value. If PROPERTY should be
  14276. explicitly set to nil, use string \"nil\" for VALUE.
  14277. Return position where the entry begins, or nil if there is no
  14278. such entry. If narrowing is in effect, only search the visible
  14279. part of the buffer."
  14280. (save-excursion
  14281. (goto-char (point-min))
  14282. (let ((case-fold-search t)
  14283. (re (org-re-property property nil (not value) value)))
  14284. (catch 'exit
  14285. (while (re-search-forward re nil t)
  14286. (when (if value (org-at-property-p)
  14287. (org-entry-get (point) property nil t))
  14288. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14289. (defun org-delete-property (property)
  14290. "In the current entry, delete PROPERTY."
  14291. (interactive
  14292. (let* ((completion-ignore-case t)
  14293. (cat (org-entry-get (point) "CATEGORY"))
  14294. (props0 (org-entry-properties nil 'standard))
  14295. (props (if cat props0
  14296. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14297. (prop (if (< 1 (length props))
  14298. (completing-read "Property: " props nil t)
  14299. (caar props))))
  14300. (list prop)))
  14301. (if (not property)
  14302. (message "No property to delete in this entry")
  14303. (org-entry-delete nil property)
  14304. (message "Property \"%s\" deleted" property)))
  14305. (defun org-delete-property-globally (property)
  14306. "Remove PROPERTY globally, from all entries.
  14307. This function ignores narrowing, if any."
  14308. (interactive
  14309. (let* ((completion-ignore-case t)
  14310. (prop (completing-read
  14311. "Globally remove property: "
  14312. (mapcar #'list (org-buffer-property-keys)))))
  14313. (list prop)))
  14314. (org-with-wide-buffer
  14315. (goto-char (point-min))
  14316. (let ((count 0)
  14317. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14318. (while (re-search-forward re nil t)
  14319. (when (org-entry-delete (point) property) (cl-incf count)))
  14320. (message "Property \"%s\" removed from %d entries" property count))))
  14321. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14322. (defun org-compute-property-at-point ()
  14323. "Compute the property at point.
  14324. This looks for an enclosing column format, extracts the operator and
  14325. then applies it to the property in the column format's scope."
  14326. (interactive)
  14327. (unless (org-at-property-p)
  14328. (user-error "Not at a property"))
  14329. (let ((prop (match-string-no-properties 2)))
  14330. (org-columns-get-format-and-top-level)
  14331. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14332. (user-error "No operator defined for property %s" prop))
  14333. (org-columns-compute prop)))
  14334. (defvar org-property-allowed-value-functions nil
  14335. "Hook for functions supplying allowed values for a specific property.
  14336. The functions must take a single argument, the name of the property, and
  14337. return a flat list of allowed values. If \":ETC\" is one of
  14338. the values, this means that these values are intended as defaults for
  14339. completion, but that other values should be allowed too.
  14340. The functions must return nil if they are not responsible for this
  14341. property.")
  14342. (defun org-property-get-allowed-values (pom property &optional table)
  14343. "Get allowed values for the property PROPERTY.
  14344. When TABLE is non-nil, return an alist that can directly be used for
  14345. completion."
  14346. (let (vals)
  14347. (cond
  14348. ((equal property "TODO")
  14349. (setq vals (org-with-point-at pom
  14350. (append org-todo-keywords-1 '("")))))
  14351. ((equal property "PRIORITY")
  14352. (let ((n org-lowest-priority))
  14353. (while (>= n org-highest-priority)
  14354. (push (char-to-string n) vals)
  14355. (setq n (1- n)))))
  14356. ((equal property "CATEGORY"))
  14357. ((member property org-special-properties))
  14358. ((setq vals (run-hook-with-args-until-success
  14359. 'org-property-allowed-value-functions property)))
  14360. (t
  14361. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14362. (when (and vals (string-match "\\S-" vals))
  14363. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14364. (setq vals (mapcar (lambda (x)
  14365. (cond ((stringp x) x)
  14366. ((numberp x) (number-to-string x))
  14367. ((symbolp x) (symbol-name x))
  14368. (t "???")))
  14369. vals)))))
  14370. (when (member ":ETC" vals)
  14371. (setq vals (remove ":ETC" vals))
  14372. (org-add-props (car vals) '(org-unrestricted t)))
  14373. (if table (mapcar 'list vals) vals)))
  14374. (defun org-property-previous-allowed-value (&optional _previous)
  14375. "Switch to the next allowed value for this property."
  14376. (interactive)
  14377. (org-property-next-allowed-value t))
  14378. (defun org-property-next-allowed-value (&optional previous)
  14379. "Switch to the next allowed value for this property."
  14380. (interactive)
  14381. (unless (org-at-property-p)
  14382. (user-error "Not at a property"))
  14383. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14384. (key (match-string 2))
  14385. (value (match-string 3))
  14386. (allowed (or (org-property-get-allowed-values (point) key)
  14387. (and (member value '("[ ]" "[-]" "[X]"))
  14388. '("[ ]" "[X]"))))
  14389. (heading (save-match-data (nth 4 (org-heading-components))))
  14390. nval)
  14391. (unless allowed
  14392. (user-error "Allowed values for this property have not been defined"))
  14393. (when previous (setq allowed (reverse allowed)))
  14394. (when (member value allowed)
  14395. (setq nval (car (cdr (member value allowed)))))
  14396. (setq nval (or nval (car allowed)))
  14397. (when (equal nval value)
  14398. (user-error "Only one allowed value for this property"))
  14399. (org-at-property-p)
  14400. (replace-match (concat " :" key ": " nval) t t)
  14401. (org-indent-line)
  14402. (beginning-of-line 1)
  14403. (skip-chars-forward " \t")
  14404. (when (equal prop org-effort-property)
  14405. (org-refresh-property
  14406. '((effort . identity)
  14407. (effort-minutes . org-duration-to-minutes))
  14408. nval)
  14409. (when (string= org-clock-current-task heading)
  14410. (setq org-clock-effort nval)
  14411. (org-clock-update-mode-line)))
  14412. (run-hook-with-args 'org-property-changed-functions key nval)))
  14413. (defun org-find-olp (path &optional this-buffer)
  14414. "Return a marker pointing to the entry at outline path OLP.
  14415. If anything goes wrong, throw an error.
  14416. You can wrap this call to catch the error like this:
  14417. (condition-case msg
  14418. (org-mobile-locate-entry (match-string 4))
  14419. (error (nth 1 msg)))
  14420. The return value will then be either a string with the error message,
  14421. or a marker if everything is OK.
  14422. If THIS-BUFFER is set, the outline path does not contain a file,
  14423. only headings."
  14424. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14425. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14426. (level 1)
  14427. (lmin 1)
  14428. (lmax 1)
  14429. end found flevel)
  14430. (unless buffer (error "File not found :%s" file))
  14431. (with-current-buffer buffer
  14432. (unless (derived-mode-p 'org-mode)
  14433. (error "Buffer %s needs to be in Org mode" buffer))
  14434. (org-with-wide-buffer
  14435. (goto-char (point-min))
  14436. (dolist (heading path)
  14437. (let ((re (format org-complex-heading-regexp-format
  14438. (regexp-quote heading)))
  14439. (cnt 0))
  14440. (while (re-search-forward re end t)
  14441. (setq level (- (match-end 1) (match-beginning 1)))
  14442. (when (and (>= level lmin) (<= level lmax))
  14443. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14444. (when (= cnt 0)
  14445. (error "Heading not found on level %d: %s" lmax heading))
  14446. (when (> cnt 1)
  14447. (error "Heading not unique on level %d: %s" lmax heading))
  14448. (goto-char found)
  14449. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14450. (setq end (save-excursion (org-end-of-subtree t t)))))
  14451. (when (org-at-heading-p)
  14452. (point-marker))))))
  14453. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14454. "Find node HEADING in BUFFER.
  14455. Return a marker to the heading if it was found, or nil if not.
  14456. If POS-ONLY is set, return just the position instead of a marker.
  14457. The heading text must match exact, but it may have a TODO keyword,
  14458. a priority cookie and tags in the standard locations."
  14459. (with-current-buffer (or buffer (current-buffer))
  14460. (org-with-wide-buffer
  14461. (goto-char (point-min))
  14462. (let (case-fold-search)
  14463. (when (re-search-forward
  14464. (format org-complex-heading-regexp-format
  14465. (regexp-quote heading)) nil t)
  14466. (if pos-only
  14467. (match-beginning 0)
  14468. (move-marker (make-marker) (match-beginning 0))))))))
  14469. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14470. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14471. When the target headline is found, return a marker to this location."
  14472. (let ((files (directory-files (or dir default-directory)
  14473. t "\\`[^.#].*\\.org\\'"))
  14474. visiting m buffer)
  14475. (catch 'found
  14476. (dolist (file files)
  14477. (message "trying %s" file)
  14478. (setq visiting (org-find-base-buffer-visiting file))
  14479. (setq buffer (or visiting (find-file-noselect file)))
  14480. (setq m (org-find-exact-headline-in-buffer
  14481. heading buffer))
  14482. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14483. (and m (throw 'found m))))))
  14484. (defun org-find-entry-with-id (ident)
  14485. "Locate the entry that contains the ID property with exact value IDENT.
  14486. IDENT can be a string, a symbol or a number, this function will search for
  14487. the string representation of it.
  14488. Return the position where this entry starts, or nil if there is no such entry."
  14489. (interactive "sID: ")
  14490. (let ((id (cond
  14491. ((stringp ident) ident)
  14492. ((symbolp ident) (symbol-name ident))
  14493. ((numberp ident) (number-to-string ident))
  14494. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14495. (org-with-wide-buffer (org-find-property "ID" id))))
  14496. ;;;; Timestamps
  14497. (defvar org-last-changed-timestamp nil)
  14498. (defvar org-last-inserted-timestamp nil
  14499. "The last time stamp inserted with `org-insert-time-stamp'.")
  14500. (defun org-time-stamp (arg &optional inactive)
  14501. "Prompt for a date/time and insert a time stamp.
  14502. If the user specifies a time like HH:MM or if this command is
  14503. called with at least one prefix argument, the time stamp contains
  14504. the date and the time. Otherwise, only the date is included.
  14505. All parts of a date not specified by the user are filled in from
  14506. the timestamp at point, if any, or the current date/time
  14507. otherwise.
  14508. If there is already a timestamp at the cursor, it is replaced.
  14509. With two universal prefix arguments, insert an active timestamp
  14510. with the current time without prompting the user.
  14511. When called from lisp, the timestamp is inactive if INACTIVE is
  14512. non-nil."
  14513. (interactive "P")
  14514. (let* ((ts (cond
  14515. ((org-at-date-range-p t)
  14516. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14517. ((org-at-timestamp-p 'lax) (match-string 0))))
  14518. ;; Default time is either the timestamp at point or today.
  14519. ;; When entering a range, only the range start is considered.
  14520. (default-time (if (not ts) (current-time)
  14521. (apply #'encode-time (org-parse-time-string ts))))
  14522. (default-input (and ts (org-get-compact-tod ts)))
  14523. (repeater (and ts
  14524. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14525. (match-string 0 ts)))
  14526. org-time-was-given
  14527. org-end-time-was-given
  14528. (time
  14529. (and (if (equal arg '(16)) (current-time)
  14530. ;; Preserve `this-command' and `last-command'.
  14531. (let ((this-command this-command)
  14532. (last-command last-command))
  14533. (org-read-date
  14534. arg 'totime nil nil default-time default-input
  14535. inactive))))))
  14536. (cond
  14537. ((and ts
  14538. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14539. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14540. (insert "--")
  14541. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14542. (ts
  14543. ;; Make sure we're on a timestamp. When in the middle of a date
  14544. ;; range, move arbitrarily to range end.
  14545. (unless (org-at-timestamp-p 'lax)
  14546. (skip-chars-forward "-")
  14547. (org-at-timestamp-p 'lax))
  14548. (replace-match "")
  14549. (setq org-last-changed-timestamp
  14550. (org-insert-time-stamp
  14551. time (or org-time-was-given arg)
  14552. inactive nil nil (list org-end-time-was-given)))
  14553. (when repeater
  14554. (backward-char)
  14555. (insert " " repeater)
  14556. (setq org-last-changed-timestamp
  14557. (concat (substring org-last-inserted-timestamp 0 -1)
  14558. " " repeater ">")))
  14559. (message "Timestamp updated"))
  14560. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14561. (t (org-insert-time-stamp
  14562. time (or org-time-was-given arg) inactive nil nil
  14563. (list org-end-time-was-given))))))
  14564. ;; FIXME: can we use this for something else, like computing time differences?
  14565. (defun org-get-compact-tod (s)
  14566. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14567. (let* ((t1 (match-string 1 s))
  14568. (h1 (string-to-number (match-string 2 s)))
  14569. (m1 (string-to-number (match-string 3 s)))
  14570. (t2 (and (match-end 4) (match-string 5 s)))
  14571. (h2 (and t2 (string-to-number (match-string 6 s))))
  14572. (m2 (and t2 (string-to-number (match-string 7 s))))
  14573. dh dm)
  14574. (if (not t2)
  14575. t1
  14576. (setq dh (- h2 h1) dm (- m2 m1))
  14577. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14578. (concat t1 "+" (number-to-string dh)
  14579. (and (/= 0 dm) (format ":%02d" dm)))))))
  14580. (defun org-time-stamp-inactive (&optional arg)
  14581. "Insert an inactive time stamp.
  14582. An inactive time stamp is enclosed in square brackets instead of angle
  14583. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14584. does not link to the calendar and cannot be changed with the S-cursor keys.
  14585. So these are more for recording a certain time/date.
  14586. If the user specifies a time like HH:MM or if this command is called with
  14587. at least one prefix argument, the time stamp contains the date and the time.
  14588. Otherwise, only the date is included.
  14589. When called with two universal prefix arguments, insert an active time stamp
  14590. with the current time without prompting the user."
  14591. (interactive "P")
  14592. (org-time-stamp arg 'inactive))
  14593. (defvar org-date-ovl (make-overlay 1 1))
  14594. (overlay-put org-date-ovl 'face 'org-date-selected)
  14595. (delete-overlay org-date-ovl)
  14596. (defvar org-ans1) ; dynamically scoped parameter
  14597. (defvar org-ans2) ; dynamically scoped parameter
  14598. (defvar org-plain-time-of-day-regexp) ; defined below
  14599. (defvar org-overriding-default-time nil) ; dynamically scoped
  14600. (defvar org-read-date-overlay nil)
  14601. (defvar org-dcst nil) ; dynamically scoped
  14602. (defvar org-read-date-history nil)
  14603. (defvar org-read-date-final-answer nil)
  14604. (defvar org-read-date-analyze-futurep nil)
  14605. (defvar org-read-date-analyze-forced-year nil)
  14606. (defvar org-read-date-inactive)
  14607. (defvar org-read-date-minibuffer-local-map
  14608. (let* ((map (make-sparse-keymap)))
  14609. (set-keymap-parent map minibuffer-local-map)
  14610. (org-defkey map (kbd ".")
  14611. (lambda () (interactive)
  14612. ;; Are we at the beginning of the prompt?
  14613. (if (looking-back "^[^:]+: "
  14614. (let ((inhibit-field-text-motion t))
  14615. (line-beginning-position)))
  14616. (org-eval-in-calendar '(calendar-goto-today))
  14617. (insert "."))))
  14618. (org-defkey map (kbd "C-.")
  14619. (lambda () (interactive)
  14620. (org-eval-in-calendar '(calendar-goto-today))))
  14621. (org-defkey map (kbd "M-S-<left>")
  14622. (lambda () (interactive)
  14623. (org-eval-in-calendar '(calendar-backward-month 1))))
  14624. (org-defkey map (kbd "ESC S-<left>")
  14625. (lambda () (interactive)
  14626. (org-eval-in-calendar '(calendar-backward-month 1))))
  14627. (org-defkey map (kbd "M-S-<right>")
  14628. (lambda () (interactive)
  14629. (org-eval-in-calendar '(calendar-forward-month 1))))
  14630. (org-defkey map (kbd "ESC S-<right>")
  14631. (lambda () (interactive)
  14632. (org-eval-in-calendar '(calendar-forward-month 1))))
  14633. (org-defkey map (kbd "M-S-<up>")
  14634. (lambda () (interactive)
  14635. (org-eval-in-calendar '(calendar-backward-year 1))))
  14636. (org-defkey map (kbd "ESC S-<up>")
  14637. (lambda () (interactive)
  14638. (org-eval-in-calendar '(calendar-backward-year 1))))
  14639. (org-defkey map (kbd "M-S-<down>")
  14640. (lambda () (interactive)
  14641. (org-eval-in-calendar '(calendar-forward-year 1))))
  14642. (org-defkey map (kbd "ESC S-<down>")
  14643. (lambda () (interactive)
  14644. (org-eval-in-calendar '(calendar-forward-year 1))))
  14645. (org-defkey map (kbd "S-<up>")
  14646. (lambda () (interactive)
  14647. (org-eval-in-calendar '(calendar-backward-week 1))))
  14648. (org-defkey map (kbd "S-<down>")
  14649. (lambda () (interactive)
  14650. (org-eval-in-calendar '(calendar-forward-week 1))))
  14651. (org-defkey map (kbd "S-<left>")
  14652. (lambda () (interactive)
  14653. (org-eval-in-calendar '(calendar-backward-day 1))))
  14654. (org-defkey map (kbd "S-<right>")
  14655. (lambda () (interactive)
  14656. (org-eval-in-calendar '(calendar-forward-day 1))))
  14657. (org-defkey map (kbd "!")
  14658. (lambda () (interactive)
  14659. (org-eval-in-calendar '(diary-view-entries))
  14660. (message "")))
  14661. (org-defkey map (kbd ">")
  14662. (lambda () (interactive)
  14663. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14664. (org-defkey map (kbd "<")
  14665. (lambda () (interactive)
  14666. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14667. (org-defkey map (kbd "C-v")
  14668. (lambda () (interactive)
  14669. (org-eval-in-calendar
  14670. '(calendar-scroll-left-three-months 1))))
  14671. (org-defkey map (kbd "M-v")
  14672. (lambda () (interactive)
  14673. (org-eval-in-calendar
  14674. '(calendar-scroll-right-three-months 1))))
  14675. map)
  14676. "Keymap for minibuffer commands when using `org-read-date'.")
  14677. (defvar org-def)
  14678. (defvar org-defdecode)
  14679. (defvar org-with-time)
  14680. (defvar calendar-setup) ; Dynamically scoped.
  14681. (defun org-read-date (&optional with-time to-time from-string prompt
  14682. default-time default-input inactive)
  14683. "Read a date, possibly a time, and make things smooth for the user.
  14684. The prompt will suggest to enter an ISO date, but you can also enter anything
  14685. which will at least partially be understood by `parse-time-string'.
  14686. Unrecognized parts of the date will default to the current day, month, year,
  14687. hour and minute. If this command is called to replace a timestamp at point,
  14688. or to enter the second timestamp of a range, the default time is taken
  14689. from the existing stamp. Furthermore, the command prefers the future,
  14690. so if you are giving a date where the year is not given, and the day-month
  14691. combination is already past in the current year, it will assume you
  14692. mean next year. For details, see the manual. A few examples:
  14693. 3-2-5 --> 2003-02-05
  14694. feb 15 --> currentyear-02-15
  14695. 2/15 --> currentyear-02-15
  14696. sep 12 9 --> 2009-09-12
  14697. 12:45 --> today 12:45
  14698. 22 sept 0:34 --> currentyear-09-22 0:34
  14699. 12 --> currentyear-currentmonth-12
  14700. Fri --> nearest Friday after today
  14701. -Tue --> last Tuesday
  14702. etc.
  14703. Furthermore you can specify a relative date by giving, as the *first* thing
  14704. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14705. change in days weeks, months, years.
  14706. With a single plus or minus, the date is relative to today. With a double
  14707. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14708. +4d --> four days from today
  14709. +4 --> same as above
  14710. +2w --> two weeks from today
  14711. ++5 --> five days from default date
  14712. The function understands only English month and weekday abbreviations.
  14713. While prompting, a calendar is popped up - you can also select the
  14714. date with the mouse (button 1). The calendar shows a period of three
  14715. months. To scroll it to other months, use the keys `>' and `<'.
  14716. If you don't like the calendar, turn it off with
  14717. (setq org-read-date-popup-calendar nil)
  14718. With optional argument TO-TIME, the date will immediately be converted
  14719. to an internal time.
  14720. With an optional argument WITH-TIME, the prompt will suggest to
  14721. also insert a time. Note that when WITH-TIME is not set, you can
  14722. still enter a time, and this function will inform the calling routine
  14723. about this change. The calling routine may then choose to change the
  14724. format used to insert the time stamp into the buffer to include the time.
  14725. With optional argument FROM-STRING, read from this string instead from
  14726. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14727. the time/date that is used for everything that is not specified by the
  14728. user."
  14729. (require 'parse-time)
  14730. (let* ((org-with-time with-time)
  14731. (org-time-stamp-rounding-minutes
  14732. (if (equal org-with-time '(16))
  14733. '(0 0)
  14734. org-time-stamp-rounding-minutes))
  14735. (org-dcst org-display-custom-times)
  14736. (ct (org-current-time))
  14737. (org-def (or org-overriding-default-time default-time ct))
  14738. (org-defdecode (decode-time org-def))
  14739. (cur-frame (selected-frame))
  14740. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14741. (calendar-setup
  14742. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14743. (calendar-move-hook nil)
  14744. (calendar-view-diary-initially-flag nil)
  14745. (calendar-view-holidays-initially-flag nil)
  14746. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14747. ;; Rationalize `org-def' and `org-defdecode', if required.
  14748. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14749. (setf (nth 2 org-defdecode) -1)
  14750. (setf (nth 1 org-defdecode) 59)
  14751. (setq org-def (apply #'encode-time org-defdecode))
  14752. (setq org-defdecode (decode-time org-def)))
  14753. (let* ((timestr (format-time-string
  14754. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14755. org-def))
  14756. (prompt (concat (if prompt (concat prompt " ") "")
  14757. (format "Date+time [%s]: " timestr))))
  14758. (cond
  14759. (from-string (setq ans from-string))
  14760. (org-read-date-popup-calendar
  14761. (save-excursion
  14762. (save-window-excursion
  14763. (calendar)
  14764. (when (eq calendar-setup 'calendar-only)
  14765. (setq cal-frame
  14766. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14767. (select-frame cal-frame))
  14768. (org-eval-in-calendar '(setq cursor-type nil) t)
  14769. (unwind-protect
  14770. (progn
  14771. (calendar-forward-day (- (time-to-days org-def)
  14772. (calendar-absolute-from-gregorian
  14773. (calendar-current-date))))
  14774. (org-eval-in-calendar nil t)
  14775. (let* ((old-map (current-local-map))
  14776. (map (copy-keymap calendar-mode-map))
  14777. (minibuffer-local-map
  14778. (copy-keymap org-read-date-minibuffer-local-map)))
  14779. (org-defkey map (kbd "RET") 'org-calendar-select)
  14780. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14781. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14782. (unwind-protect
  14783. (progn
  14784. (use-local-map map)
  14785. (setq org-read-date-inactive inactive)
  14786. (add-hook 'post-command-hook 'org-read-date-display)
  14787. (setq org-ans0
  14788. (read-string prompt
  14789. default-input
  14790. 'org-read-date-history
  14791. nil))
  14792. ;; org-ans0: from prompt
  14793. ;; org-ans1: from mouse click
  14794. ;; org-ans2: from calendar motion
  14795. (setq ans
  14796. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14797. (remove-hook 'post-command-hook 'org-read-date-display)
  14798. (use-local-map old-map)
  14799. (when org-read-date-overlay
  14800. (delete-overlay org-read-date-overlay)
  14801. (setq org-read-date-overlay nil)))))
  14802. (bury-buffer "*Calendar*")
  14803. (when cal-frame
  14804. (delete-frame cal-frame)
  14805. (select-frame-set-input-focus cur-frame))))))
  14806. (t ; Naked prompt only
  14807. (unwind-protect
  14808. (setq ans (read-string prompt default-input
  14809. 'org-read-date-history timestr))
  14810. (when org-read-date-overlay
  14811. (delete-overlay org-read-date-overlay)
  14812. (setq org-read-date-overlay nil))))))
  14813. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14814. (when org-read-date-analyze-forced-year
  14815. (message "Year was forced into %s"
  14816. (if org-read-date-force-compatible-dates
  14817. "compatible range (1970-2037)"
  14818. "range representable on this machine"))
  14819. (ding))
  14820. ;; One round trip to get rid of 34th of August and stuff like that....
  14821. (setq final (decode-time (apply 'encode-time final)))
  14822. (setq org-read-date-final-answer ans)
  14823. (if to-time
  14824. (apply 'encode-time final)
  14825. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14826. (format "%04d-%02d-%02d %02d:%02d"
  14827. (nth 5 final) (nth 4 final) (nth 3 final)
  14828. (nth 2 final) (nth 1 final))
  14829. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14830. (defun org-read-date-display ()
  14831. "Display the current date prompt interpretation in the minibuffer."
  14832. (when org-read-date-display-live
  14833. (when org-read-date-overlay
  14834. (delete-overlay org-read-date-overlay))
  14835. (when (minibufferp (current-buffer))
  14836. (save-excursion
  14837. (end-of-line 1)
  14838. (while (not (equal (buffer-substring
  14839. (max (point-min) (- (point) 4)) (point))
  14840. " "))
  14841. (insert " ")))
  14842. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14843. " " (or org-ans1 org-ans2)))
  14844. (org-end-time-was-given nil)
  14845. (f (org-read-date-analyze ans org-def org-defdecode))
  14846. (fmts (if org-dcst
  14847. org-time-stamp-custom-formats
  14848. org-time-stamp-formats))
  14849. (fmt (if (or org-with-time
  14850. (and (boundp 'org-time-was-given) org-time-was-given))
  14851. (cdr fmts)
  14852. (car fmts)))
  14853. (txt (format-time-string fmt (apply 'encode-time f)))
  14854. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14855. (txt (concat "=> " txt)))
  14856. (when (and org-end-time-was-given
  14857. (string-match org-plain-time-of-day-regexp txt))
  14858. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14859. org-end-time-was-given
  14860. (substring txt (match-end 0)))))
  14861. (when org-read-date-analyze-futurep
  14862. (setq txt (concat txt " (=>F)")))
  14863. (setq org-read-date-overlay
  14864. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14865. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14866. (defun org-read-date-analyze (ans def defdecode)
  14867. "Analyze the combined answer of the date prompt."
  14868. ;; FIXME: cleanup and comment
  14869. ;; Pass `current-time' result to `decode-time' (instead of calling
  14870. ;; without arguments) so that only `current-time' has to be
  14871. ;; overridden in tests.
  14872. (let ((org-def def)
  14873. (org-defdecode defdecode)
  14874. (nowdecode (decode-time (current-time)))
  14875. delta deltan deltaw deltadef year month day
  14876. hour minute second wday pm h2 m2 tl wday1
  14877. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14878. (setq org-read-date-analyze-futurep nil
  14879. org-read-date-analyze-forced-year nil)
  14880. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14881. (setq ans "+0"))
  14882. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14883. (setq ans (replace-match "" t t ans)
  14884. deltan (car delta)
  14885. deltaw (nth 1 delta)
  14886. deltadef (nth 2 delta)))
  14887. ;; Check if there is an iso week date in there. If yes, store the
  14888. ;; info and postpone interpreting it until the rest of the parsing
  14889. ;; is done.
  14890. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14891. (setq iso-year (when (match-end 1)
  14892. (org-small-year-to-year
  14893. (string-to-number (match-string 1 ans))))
  14894. iso-weekday (when (match-end 3)
  14895. (string-to-number (match-string 3 ans)))
  14896. iso-week (string-to-number (match-string 2 ans)))
  14897. (setq ans (replace-match "" t t ans)))
  14898. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14899. (when (string-match
  14900. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14901. (setq year (if (match-end 2)
  14902. (string-to-number (match-string 2 ans))
  14903. (progn (setq kill-year t)
  14904. (string-to-number (format-time-string "%Y"))))
  14905. month (string-to-number (match-string 3 ans))
  14906. day (string-to-number (match-string 4 ans)))
  14907. (setq year (org-small-year-to-year year))
  14908. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14909. t nil ans)))
  14910. ;; Help matching dotted european dates
  14911. (when (string-match
  14912. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14913. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14914. (setq kill-year t)
  14915. (string-to-number (format-time-string "%Y")))
  14916. day (string-to-number (match-string 1 ans))
  14917. month (string-to-number (match-string 2 ans))
  14918. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14919. t nil ans)))
  14920. ;; Help matching american dates, like 5/30 or 5/30/7
  14921. (when (string-match
  14922. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14923. (setq year (if (match-end 4)
  14924. (string-to-number (match-string 4 ans))
  14925. (progn (setq kill-year t)
  14926. (string-to-number (format-time-string "%Y"))))
  14927. month (string-to-number (match-string 1 ans))
  14928. day (string-to-number (match-string 2 ans)))
  14929. (setq year (org-small-year-to-year year))
  14930. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14931. t nil ans)))
  14932. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14933. ;; If there is a time with am/pm, and *no* time without it, we convert
  14934. ;; so that matching will be successful.
  14935. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14936. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14937. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14938. (setq hour (string-to-number (match-string 1 ans))
  14939. minute (if (match-end 3)
  14940. (string-to-number (match-string 3 ans))
  14941. 0)
  14942. pm (equal ?p
  14943. (string-to-char (downcase (match-string 4 ans)))))
  14944. (if (and (= hour 12) (not pm))
  14945. (setq hour 0)
  14946. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14947. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14948. t t ans))))
  14949. ;; Check if a time range is given as a duration
  14950. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14951. (setq hour (string-to-number (match-string 1 ans))
  14952. h2 (+ hour (string-to-number (match-string 3 ans)))
  14953. minute (string-to-number (match-string 2 ans))
  14954. m2 (+ minute (if (match-end 5) (string-to-number
  14955. (match-string 5 ans))0)))
  14956. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14957. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14958. t t ans)))
  14959. ;; Check if there is a time range
  14960. (when (boundp 'org-end-time-was-given)
  14961. (setq org-time-was-given nil)
  14962. (when (and (string-match org-plain-time-of-day-regexp ans)
  14963. (match-end 8))
  14964. (setq org-end-time-was-given (match-string 8 ans))
  14965. (setq ans (concat (substring ans 0 (match-beginning 7))
  14966. (substring ans (match-end 7))))))
  14967. (setq tl (parse-time-string ans)
  14968. day (or (nth 3 tl) (nth 3 org-defdecode))
  14969. month
  14970. (cond ((nth 4 tl))
  14971. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14972. ;; Day was specified. Make sure DAY+MONTH
  14973. ;; combination happens in the future.
  14974. ((nth 3 tl)
  14975. (setq futurep t)
  14976. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14977. (nth 4 nowdecode)))
  14978. (t (nth 4 org-defdecode)))
  14979. year
  14980. (cond ((and (not kill-year) (nth 5 tl)))
  14981. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14982. ;; Month was guessed in the future and is at least
  14983. ;; equal to NOWDECODE's. Fix year accordingly.
  14984. (futurep
  14985. (if (or (> month (nth 4 nowdecode))
  14986. (>= day (nth 3 nowdecode)))
  14987. (nth 5 nowdecode)
  14988. (1+ (nth 5 nowdecode))))
  14989. ;; Month was specified. Make sure MONTH+YEAR
  14990. ;; combination happens in the future.
  14991. ((nth 4 tl)
  14992. (setq futurep t)
  14993. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  14994. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  14995. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  14996. (t (nth 5 nowdecode))))
  14997. (t (nth 5 org-defdecode)))
  14998. hour (or (nth 2 tl) (nth 2 org-defdecode))
  14999. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15000. second (or (nth 0 tl) 0)
  15001. wday (nth 6 tl))
  15002. (when (and (eq org-read-date-prefer-future 'time)
  15003. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15004. (equal day (nth 3 nowdecode))
  15005. (equal month (nth 4 nowdecode))
  15006. (equal year (nth 5 nowdecode))
  15007. (nth 2 tl)
  15008. (or (< (nth 2 tl) (nth 2 nowdecode))
  15009. (and (= (nth 2 tl) (nth 2 nowdecode))
  15010. (nth 1 tl)
  15011. (< (nth 1 tl) (nth 1 nowdecode)))))
  15012. (setq day (1+ day)
  15013. futurep t))
  15014. ;; Special date definitions below
  15015. (cond
  15016. (iso-week
  15017. ;; There was an iso week
  15018. (require 'cal-iso)
  15019. (setq futurep nil)
  15020. (setq year (or iso-year year)
  15021. day (or iso-weekday wday 1)
  15022. wday nil ; to make sure that the trigger below does not match
  15023. iso-date (calendar-gregorian-from-absolute
  15024. (calendar-iso-to-absolute
  15025. (list iso-week day year))))
  15026. ; FIXME: Should we also push ISO weeks into the future?
  15027. ; (when (and org-read-date-prefer-future
  15028. ; (not iso-year)
  15029. ; (< (calendar-absolute-from-gregorian iso-date)
  15030. ; (time-to-days (current-time))))
  15031. ; (setq year (1+ year)
  15032. ; iso-date (calendar-gregorian-from-absolute
  15033. ; (calendar-iso-to-absolute
  15034. ; (list iso-week day year)))))
  15035. (setq month (car iso-date)
  15036. year (nth 2 iso-date)
  15037. day (nth 1 iso-date)))
  15038. (deltan
  15039. (setq futurep nil)
  15040. (unless deltadef
  15041. ;; Pass `current-time' result to `decode-time' (instead of
  15042. ;; calling without arguments) so that only `current-time' has
  15043. ;; to be overridden in tests.
  15044. (let ((now (decode-time (current-time))))
  15045. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15046. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15047. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15048. ((equal deltaw "m") (setq month (+ month deltan)))
  15049. ((equal deltaw "y") (setq year (+ year deltan)))))
  15050. ((and wday (not (nth 3 tl)))
  15051. ;; Weekday was given, but no day, so pick that day in the week
  15052. ;; on or after the derived date.
  15053. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15054. (unless (equal wday wday1)
  15055. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15056. (when (and (boundp 'org-time-was-given)
  15057. (nth 2 tl))
  15058. (setq org-time-was-given t))
  15059. (when (< year 100) (setq year (+ 2000 year)))
  15060. ;; Check of the date is representable
  15061. (if org-read-date-force-compatible-dates
  15062. (progn
  15063. (when (< year 1970)
  15064. (setq year 1970 org-read-date-analyze-forced-year t))
  15065. (when (> year 2037)
  15066. (setq year 2037 org-read-date-analyze-forced-year t)))
  15067. (condition-case nil
  15068. (ignore (encode-time second minute hour day month year))
  15069. (error
  15070. (setq year (nth 5 org-defdecode))
  15071. (setq org-read-date-analyze-forced-year t))))
  15072. (setq org-read-date-analyze-futurep futurep)
  15073. (list second minute hour day month year)))
  15074. (defvar parse-time-weekdays)
  15075. (defun org-read-date-get-relative (s today default)
  15076. "Check string S for special relative date string.
  15077. TODAY and DEFAULT are internal times, for today and for a default.
  15078. Return shift list (N what def-flag)
  15079. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15080. N is the number of WHATs to shift.
  15081. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15082. the DEFAULT date rather than TODAY."
  15083. (require 'parse-time)
  15084. (when (and
  15085. (string-match
  15086. (concat
  15087. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15088. "\\([0-9]+\\)?"
  15089. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15090. "\\([ \t]\\|$\\)") s)
  15091. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15092. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15093. (string-to-char (substring (match-string 1 s) -1))
  15094. ?+))
  15095. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15096. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15097. (what (if (match-end 3) (match-string 3 s) "d"))
  15098. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15099. (date (if rel default today))
  15100. (wday (nth 6 (decode-time date)))
  15101. delta)
  15102. (if wday1
  15103. (progn
  15104. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15105. (when (= delta 0) (setq delta 7))
  15106. (when (= dir ?-)
  15107. (setq delta (- delta 7))
  15108. (when (= delta 0) (setq delta -7)))
  15109. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15110. (list delta "d" rel))
  15111. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15112. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15113. "Turn a user-specified date into the internal representation.
  15114. The internal representation needed by the calendar is (month day year).
  15115. This is a wrapper to handle the brain-dead convention in calendar that
  15116. user function argument order change dependent on argument order."
  15117. (pcase calendar-date-style
  15118. (`american (list arg1 arg2 arg3))
  15119. (`european (list arg2 arg1 arg3))
  15120. (`iso (list arg2 arg3 arg1))))
  15121. (defun org-eval-in-calendar (form &optional keepdate)
  15122. "Eval FORM in the calendar window and return to current window.
  15123. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15124. (let ((sf (selected-frame))
  15125. (sw (selected-window)))
  15126. (select-window (get-buffer-window "*Calendar*" t))
  15127. (eval form)
  15128. (when (and (not keepdate) (calendar-cursor-to-date))
  15129. (let* ((date (calendar-cursor-to-date))
  15130. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15131. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15132. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15133. (select-window sw)
  15134. (select-frame-set-input-focus sf)))
  15135. (defun org-calendar-select ()
  15136. "Return to `org-read-date' with the date currently selected.
  15137. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15138. (interactive)
  15139. (when (calendar-cursor-to-date)
  15140. (let* ((date (calendar-cursor-to-date))
  15141. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15142. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15143. (when (active-minibuffer-window) (exit-minibuffer))))
  15144. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15145. "Insert a date stamp for the date given by the internal TIME.
  15146. See `format-time-string' for the format of TIME.
  15147. WITH-HM means use the stamp format that includes the time of the day.
  15148. INACTIVE means use square brackets instead of angular ones, so that the
  15149. stamp will not contribute to the agenda.
  15150. PRE and POST are optional strings to be inserted before and after the
  15151. stamp.
  15152. The command returns the inserted time stamp."
  15153. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15154. stamp)
  15155. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15156. (insert-before-markers (or pre ""))
  15157. (when (listp extra)
  15158. (setq extra (car extra))
  15159. (if (and (stringp extra)
  15160. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15161. (setq extra (format "-%02d:%02d"
  15162. (string-to-number (match-string 1 extra))
  15163. (string-to-number (match-string 2 extra))))
  15164. (setq extra nil)))
  15165. (when extra
  15166. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15167. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15168. (insert-before-markers (or post ""))
  15169. (setq org-last-inserted-timestamp stamp)))
  15170. (defun org-toggle-time-stamp-overlays ()
  15171. "Toggle the use of custom time stamp formats."
  15172. (interactive)
  15173. (setq org-display-custom-times (not org-display-custom-times))
  15174. (unless org-display-custom-times
  15175. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15176. (while (setq p (next-single-property-change p 'display))
  15177. (when (and (get-text-property p 'display)
  15178. (eq (get-text-property p 'face) 'org-date))
  15179. (remove-text-properties
  15180. p (setq p (next-single-property-change p 'display))
  15181. '(display t))))
  15182. (set-buffer-modified-p bmp)))
  15183. (org-restart-font-lock)
  15184. (setq org-table-may-need-update t)
  15185. (if org-display-custom-times
  15186. (message "Time stamps are overlaid with custom format")
  15187. (message "Time stamp overlays removed")))
  15188. (defun org-display-custom-time (beg end)
  15189. "Overlay modified time stamp format over timestamp between BEG and END."
  15190. (let* ((ts (buffer-substring beg end))
  15191. t1 with-hm tf time str (off 0))
  15192. (save-match-data
  15193. (setq t1 (org-parse-time-string ts t))
  15194. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15195. (setq off (- (match-end 0) (match-beginning 0)))))
  15196. (setq end (- end off))
  15197. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15198. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15199. time (org-fix-decoded-time t1)
  15200. str (org-add-props
  15201. (format-time-string
  15202. (substring tf 1 -1) (apply 'encode-time time))
  15203. nil 'mouse-face 'highlight))
  15204. (put-text-property beg end 'display str)))
  15205. (defun org-fix-decoded-time (time)
  15206. "Set 0 instead of nil for the first 6 elements of time.
  15207. Don't touch the rest."
  15208. (let ((n 0))
  15209. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15210. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15211. "Difference between TIMESTAMP-STRING and now in days.
  15212. If SECONDS is non-nil, return the difference in seconds."
  15213. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15214. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15215. (funcall fdiff (current-time)))))
  15216. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15217. "Is the time in TIMESTAMP-STRING close to the current date?"
  15218. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15219. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15220. (not (org-entry-is-done-p))))
  15221. (defun org-get-wdays (ts &optional delay zero-delay)
  15222. "Get the deadline lead time appropriate for timestring TS.
  15223. When DELAY is non-nil, get the delay time for scheduled items
  15224. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15225. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15226. don't try to find the delay cookie in the scheduled timestamp."
  15227. (let ((tv (if delay org-scheduled-delay-days
  15228. org-deadline-warning-days)))
  15229. (cond
  15230. ((or (and delay (< tv 0))
  15231. (and delay zero-delay (<= tv 0))
  15232. (and (not delay) (<= tv 0)))
  15233. ;; Enforce this value no matter what
  15234. (- tv))
  15235. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15236. ;; lead time is specified.
  15237. (floor (* (string-to-number (match-string 1 ts))
  15238. (cdr (assoc (match-string 2 ts)
  15239. '(("d" . 1) ("w" . 7)
  15240. ("m" . 30.4) ("y" . 365.25)
  15241. ("h" . 0.041667)))))))
  15242. ;; go for the default.
  15243. (t tv))))
  15244. (defun org-calendar-select-mouse (ev)
  15245. "Return to `org-read-date' with the date currently selected.
  15246. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15247. (interactive "e")
  15248. (mouse-set-point ev)
  15249. (when (calendar-cursor-to-date)
  15250. (let* ((date (calendar-cursor-to-date))
  15251. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15252. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15253. (when (active-minibuffer-window) (exit-minibuffer))))
  15254. (defun org-check-deadlines (ndays)
  15255. "Check if there are any deadlines due or past due.
  15256. A deadline is considered due if it happens within `org-deadline-warning-days'
  15257. days from today's date. If the deadline appears in an entry marked DONE,
  15258. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15259. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15260. are shown."
  15261. (interactive "P")
  15262. (let* ((org-warn-days
  15263. (cond
  15264. ((equal ndays '(4)) 100000)
  15265. (ndays (prefix-numeric-value ndays))
  15266. (t (abs org-deadline-warning-days))))
  15267. (case-fold-search nil)
  15268. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15269. (callback
  15270. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15271. (message "%d deadlines past-due or due within %d days"
  15272. (org-occur regexp nil callback)
  15273. org-warn-days)))
  15274. (defsubst org-re-timestamp (type)
  15275. "Return a regexp for timestamp TYPE.
  15276. Allowed values for TYPE are:
  15277. all: all timestamps
  15278. active: only active timestamps (<...>)
  15279. inactive: only inactive timestamps ([...])
  15280. scheduled: only scheduled timestamps
  15281. deadline: only deadline timestamps
  15282. closed: only closed time-stamps
  15283. When TYPE is nil, fall back on returning a regexp that matches
  15284. both scheduled and deadline timestamps."
  15285. (cl-case type
  15286. (all org-ts-regexp-both)
  15287. (active org-ts-regexp)
  15288. (inactive org-ts-regexp-inactive)
  15289. (scheduled org-scheduled-time-regexp)
  15290. (deadline org-deadline-time-regexp)
  15291. (closed org-closed-time-regexp)
  15292. (otherwise
  15293. (concat "\\<"
  15294. (regexp-opt (list org-deadline-string org-scheduled-string))
  15295. " *<\\([^>]+\\)>"))))
  15296. (defun org-check-before-date (d)
  15297. "Check if there are deadlines or scheduled entries before date D."
  15298. (interactive (list (org-read-date)))
  15299. (let* ((case-fold-search nil)
  15300. (regexp (org-re-timestamp org-ts-type))
  15301. (ts-type org-ts-type)
  15302. (callback
  15303. (lambda ()
  15304. (let ((match (match-string 1)))
  15305. (and (if (memq ts-type '(active inactive all))
  15306. (eq (org-element-type (save-excursion
  15307. (backward-char)
  15308. (org-element-context)))
  15309. 'timestamp)
  15310. (org-at-planning-p))
  15311. (time-less-p
  15312. (org-time-string-to-time match)
  15313. (org-time-string-to-time d)))))))
  15314. (message "%d entries before %s"
  15315. (org-occur regexp nil callback)
  15316. d)))
  15317. (defun org-check-after-date (d)
  15318. "Check if there are deadlines or scheduled entries after date D."
  15319. (interactive (list (org-read-date)))
  15320. (let* ((case-fold-search nil)
  15321. (regexp (org-re-timestamp org-ts-type))
  15322. (ts-type org-ts-type)
  15323. (callback
  15324. (lambda ()
  15325. (let ((match (match-string 1)))
  15326. (and (if (memq ts-type '(active inactive all))
  15327. (eq (org-element-type (save-excursion
  15328. (backward-char)
  15329. (org-element-context)))
  15330. 'timestamp)
  15331. (org-at-planning-p))
  15332. (not (time-less-p
  15333. (org-time-string-to-time match)
  15334. (org-time-string-to-time d))))))))
  15335. (message "%d entries after %s"
  15336. (org-occur regexp nil callback)
  15337. d)))
  15338. (defun org-check-dates-range (start-date end-date)
  15339. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15340. (interactive (list (org-read-date nil nil nil "Range starts")
  15341. (org-read-date nil nil nil "Range end")))
  15342. (let ((case-fold-search nil)
  15343. (regexp (org-re-timestamp org-ts-type))
  15344. (callback
  15345. (let ((type org-ts-type))
  15346. (lambda ()
  15347. (let ((match (match-string 1)))
  15348. (and
  15349. (if (memq type '(active inactive all))
  15350. (eq (org-element-type (save-excursion
  15351. (backward-char)
  15352. (org-element-context)))
  15353. 'timestamp)
  15354. (org-at-planning-p))
  15355. (not (time-less-p
  15356. (org-time-string-to-time match)
  15357. (org-time-string-to-time start-date)))
  15358. (time-less-p
  15359. (org-time-string-to-time match)
  15360. (org-time-string-to-time end-date))))))))
  15361. (message "%d entries between %s and %s"
  15362. (org-occur regexp nil callback) start-date end-date)))
  15363. (defun org-evaluate-time-range (&optional to-buffer)
  15364. "Evaluate a time range by computing the difference between start and end.
  15365. Normally the result is just printed in the echo area, but with prefix arg
  15366. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15367. If the time range is actually in a table, the result is inserted into the
  15368. next column.
  15369. For time difference computation, a year is assumed to be exactly 365
  15370. days in order to avoid rounding problems."
  15371. (interactive "P")
  15372. (or
  15373. (org-clock-update-time-maybe)
  15374. (save-excursion
  15375. (unless (org-at-date-range-p t)
  15376. (goto-char (point-at-bol))
  15377. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15378. (unless (org-at-date-range-p t)
  15379. (user-error "Not at a time-stamp range, and none found in current line")))
  15380. (let* ((ts1 (match-string 1))
  15381. (ts2 (match-string 2))
  15382. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15383. (match-end (match-end 0))
  15384. (time1 (org-time-string-to-time ts1))
  15385. (time2 (org-time-string-to-time ts2))
  15386. (t1 (float-time time1))
  15387. (t2 (float-time time2))
  15388. (diff (abs (- t2 t1)))
  15389. (negative (< (- t2 t1) 0))
  15390. ;; (ys (floor (* 365 24 60 60)))
  15391. (ds (* 24 60 60))
  15392. (hs (* 60 60))
  15393. (fy "%dy %dd %02d:%02d")
  15394. (fy1 "%dy %dd")
  15395. (fd "%dd %02d:%02d")
  15396. (fd1 "%dd")
  15397. (fh "%02d:%02d")
  15398. y d h m align)
  15399. (if havetime
  15400. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15401. y 0
  15402. d (floor (/ diff ds)) diff (mod diff ds)
  15403. h (floor (/ diff hs)) diff (mod diff hs)
  15404. m (floor (/ diff 60)))
  15405. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15406. y 0
  15407. d (floor (+ (/ diff ds) 0.5))
  15408. h 0 m 0))
  15409. (if (not to-buffer)
  15410. (message "%s" (org-make-tdiff-string y d h m))
  15411. (if (org-at-table-p)
  15412. (progn
  15413. (goto-char match-end)
  15414. (setq align t)
  15415. (and (looking-at " *|") (goto-char (match-end 0))))
  15416. (goto-char match-end))
  15417. (when (looking-at
  15418. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15419. (replace-match ""))
  15420. (when negative (insert " -"))
  15421. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15422. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15423. (insert " " (format fh h m))))
  15424. (when align (org-table-align))
  15425. (message "Time difference inserted")))))
  15426. (defun org-make-tdiff-string (y d h m)
  15427. (let ((fmt "")
  15428. (l nil))
  15429. (when (> y 0)
  15430. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15431. (push y l))
  15432. (when (> d 0)
  15433. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15434. (push d l))
  15435. (when (> h 0)
  15436. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15437. (push h l))
  15438. (when (> m 0)
  15439. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15440. (push m l))
  15441. (apply 'format fmt (nreverse l))))
  15442. (defun org-time-string-to-time (s)
  15443. "Convert timestamp string S into internal time."
  15444. (apply #'encode-time (org-parse-time-string s)))
  15445. (defun org-time-string-to-seconds (s)
  15446. "Convert a timestamp string S into a number of seconds."
  15447. (float-time (org-time-string-to-time s)))
  15448. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15449. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15450. "Convert time stamp S to an absolute day number.
  15451. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15452. stamp, get the closest date to DAYNR. If PREFER is
  15453. `past' (respectively `future') return a date past (respectively
  15454. after) or equal to DAYNR.
  15455. POS is the location of time stamp S, as a buffer position in
  15456. BUFFER.
  15457. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15458. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15459. signaled."
  15460. (cond
  15461. ((string-match "\\`%%\\((.*)\\)" s)
  15462. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15463. ;; only able to match individual dates. If it fails, raise an
  15464. ;; error.
  15465. (if (and daynr
  15466. (org-diary-sexp-entry
  15467. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15468. daynr
  15469. (signal 'org-diary-sexp-no-match (list s))))
  15470. (daynr (org-closest-date s daynr prefer))
  15471. (t (time-to-days
  15472. (condition-case errdata
  15473. (apply #'encode-time (org-parse-time-string s))
  15474. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15475. s
  15476. (if (not (and buffer pos)) ""
  15477. (format-message " at %d in buffer `%s'" pos buffer))
  15478. (cdr errdata))))))))
  15479. (defun org-days-to-iso-week (days)
  15480. "Return the iso week number."
  15481. (require 'cal-iso)
  15482. (car (calendar-iso-from-absolute days)))
  15483. (defun org-small-year-to-year (year)
  15484. "Convert 2-digit years into 4-digit years.
  15485. YEAR is expanded into one of the 30 next years, if possible, or
  15486. into a past one. Any year larger than 99 is returned unchanged."
  15487. (if (>= year 100) year
  15488. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15489. (century (/ current 100))
  15490. (offset (- year (% current 100))))
  15491. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15492. ((> offset -70) (+ (* century 100) year))
  15493. (t (+ (* (1+ century) 100) year))))))
  15494. (defun org-time-from-absolute (d)
  15495. "Return the time corresponding to date D.
  15496. D may be an absolute day number, or a calendar-type list (month day year)."
  15497. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15498. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15499. (defvar org-agenda-current-date)
  15500. (defun org-calendar-holiday ()
  15501. "List of holidays, for Diary display in Org mode."
  15502. (require 'holidays)
  15503. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15504. (and hl (mapconcat #'identity hl "; "))))
  15505. (defun org-diary-sexp-entry (sexp entry d)
  15506. "Process a SEXP diary ENTRY for date D."
  15507. (require 'diary-lib)
  15508. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15509. ;; dynamically.
  15510. (let* ((sexp `(let ((entry ,entry)
  15511. (date ',d))
  15512. ,(car (read-from-string sexp))))
  15513. (result (if calendar-debug-sexp (eval sexp)
  15514. (condition-case nil
  15515. (eval sexp)
  15516. (error
  15517. (beep)
  15518. (message "Bad sexp at line %d in %s: %s"
  15519. (org-current-line)
  15520. (buffer-file-name) sexp)
  15521. (sleep-for 2))))))
  15522. (cond ((stringp result) (split-string result "; "))
  15523. ((and (consp result)
  15524. (not (consp (cdr result)))
  15525. (stringp (cdr result))) (cdr result))
  15526. ((and (consp result)
  15527. (stringp (car result))) result)
  15528. (result entry))))
  15529. (defun org-diary-to-ical-string (frombuf)
  15530. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15531. This uses the icalendar.el library."
  15532. (let* ((tmpdir temporary-file-directory)
  15533. (tmpfile (make-temp-name
  15534. (expand-file-name "orgics" tmpdir)))
  15535. buf rtn b e)
  15536. (with-current-buffer frombuf
  15537. (icalendar-export-region (point-min) (point-max) tmpfile)
  15538. (setq buf (find-buffer-visiting tmpfile))
  15539. (set-buffer buf)
  15540. (goto-char (point-min))
  15541. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15542. (setq b (match-beginning 0)))
  15543. (goto-char (point-max))
  15544. (when (re-search-backward "^END:VEVENT" nil t)
  15545. (setq e (match-end 0)))
  15546. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15547. (kill-buffer buf)
  15548. (delete-file tmpfile)
  15549. rtn))
  15550. (defun org-closest-date (start current prefer)
  15551. "Return closest date to CURRENT starting from START.
  15552. CURRENT and START are both time stamps.
  15553. When PREFER is `past', return a date that is either CURRENT or
  15554. past. When PREFER is `future', return a date that is either
  15555. CURRENT or future.
  15556. Only time stamps with a repeater are modified. Any other time
  15557. stamp stay unchanged. In any case, return value is an absolute
  15558. day number."
  15559. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15560. ;; No repeater. Do not shift time stamp.
  15561. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15562. (let ((value (string-to-number (match-string 1 start)))
  15563. (type (match-string 2 start)))
  15564. (if (= 0 value)
  15565. ;; Repeater with a 0-value is considered as void.
  15566. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15567. (let* ((base (org-date-to-gregorian start))
  15568. (target (org-date-to-gregorian current))
  15569. (sday (calendar-absolute-from-gregorian base))
  15570. (cday (calendar-absolute-from-gregorian target))
  15571. n1 n2)
  15572. ;; If START is already past CURRENT, just return START.
  15573. (if (<= cday sday) sday
  15574. ;; Compute closest date before (N1) and closest date past
  15575. ;; (N2) CURRENT.
  15576. (pcase type
  15577. ("h"
  15578. (let ((missing-hours
  15579. (mod (+ (- (* 24 (- cday sday))
  15580. (nth 2 (org-parse-time-string start)))
  15581. org-extend-today-until)
  15582. value)))
  15583. (setf n1 (if (= missing-hours 0) cday
  15584. (- cday (1+ (/ missing-hours 24)))))
  15585. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15586. ((or "d" "w")
  15587. (let ((value (if (equal type "w") (* 7 value) value)))
  15588. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15589. (setf n2 (+ n1 value))))
  15590. ("m"
  15591. (let* ((add-months
  15592. (lambda (d n)
  15593. ;; Add N months to gregorian date D, i.e.,
  15594. ;; a list (MONTH DAY YEAR). Return a valid
  15595. ;; gregorian date.
  15596. (let ((m (+ (nth 0 d) n)))
  15597. (list (mod m 12)
  15598. (nth 1 d)
  15599. (+ (/ m 12) (nth 2 d))))))
  15600. (months ; Complete months to TARGET.
  15601. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15602. (- (nth 0 target) (nth 0 base))
  15603. ;; If START's day is greater than
  15604. ;; TARGET's, remove incomplete month.
  15605. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15606. value)
  15607. value))
  15608. (before (funcall add-months base months)))
  15609. (setf n1 (calendar-absolute-from-gregorian before))
  15610. (setf n2
  15611. (calendar-absolute-from-gregorian
  15612. (funcall add-months before value)))))
  15613. (_
  15614. (let* ((d (nth 1 base))
  15615. (m (nth 0 base))
  15616. (y (nth 2 base))
  15617. (years ; Complete years to TARGET.
  15618. (* (/ (- (nth 2 target)
  15619. y
  15620. ;; If START's month and day are
  15621. ;; greater than TARGET's, remove
  15622. ;; incomplete year.
  15623. (if (or (> (nth 0 target) m)
  15624. (and (= (nth 0 target) m)
  15625. (> (nth 1 target) d)))
  15626. 0
  15627. 1))
  15628. value)
  15629. value))
  15630. (before (list m d (+ y years))))
  15631. (setf n1 (calendar-absolute-from-gregorian before))
  15632. (setf n2 (calendar-absolute-from-gregorian
  15633. (list m d (+ (nth 2 before) value)))))))
  15634. ;; Handle PREFER parameter, if any.
  15635. (cond
  15636. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15637. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15638. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15639. (defun org-date-to-gregorian (d)
  15640. "Turn any specification of date D into a Gregorian date for the calendar."
  15641. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15642. ((and (listp d) (= (length d) 3)) d)
  15643. ((stringp d)
  15644. (let ((d (org-parse-time-string d)))
  15645. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15646. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15647. (defun org-timestamp-up (&optional arg)
  15648. "Increase the date item at the cursor by one.
  15649. If the cursor is on the year, change the year. If it is on the month,
  15650. the day or the time, change that. If the cursor is on the enclosing
  15651. bracket, change the timestamp type.
  15652. With prefix ARG, change by that many units."
  15653. (interactive "p")
  15654. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15655. (defun org-timestamp-down (&optional arg)
  15656. "Decrease the date item at the cursor by one.
  15657. If the cursor is on the year, change the year. If it is on the month,
  15658. the day or the time, change that. If the cursor is on the enclosing
  15659. bracket, change the timestamp type.
  15660. With prefix ARG, change by that many units."
  15661. (interactive "p")
  15662. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15663. (defun org-timestamp-up-day (&optional arg)
  15664. "Increase the date in the time stamp by one day.
  15665. With prefix ARG, change that many days."
  15666. (interactive "p")
  15667. (if (and (not (org-at-timestamp-p 'lax))
  15668. (org-at-heading-p))
  15669. (org-todo 'up)
  15670. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15671. (defun org-timestamp-down-day (&optional arg)
  15672. "Decrease the date in the time stamp by one day.
  15673. With prefix ARG, change that many days."
  15674. (interactive "p")
  15675. (if (and (not (org-at-timestamp-p 'lax))
  15676. (org-at-heading-p))
  15677. (org-todo 'down)
  15678. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15679. (defun org-at-timestamp-p (&optional extended)
  15680. "Non-nil if point is inside a timestamp.
  15681. By default, the function only consider syntactically valid active
  15682. timestamps. However, the caller may have a broader definition
  15683. for timestamps. As a consequence, optional argument EXTENDED can
  15684. be set to the following values
  15685. `inactive'
  15686. Include also syntactically valid inactive timestamps.
  15687. `agenda'
  15688. Include timestamps allowed in Agenda, i.e., those in
  15689. properties drawers, planning lines and clock lines.
  15690. `lax'
  15691. Ignore context. The function matches any part of the
  15692. document looking like a timestamp. This includes comments,
  15693. example blocks...
  15694. For backward-compatibility with Org 9.0, every other non-nil
  15695. value is equivalent to `inactive'.
  15696. When at a timestamp, return the position of the point as a symbol
  15697. among `bracket', `after', `year', `month', `hour', `minute',
  15698. `day' or a number of character from the last know part of the
  15699. time stamp.
  15700. When matching, the match groups are the following:
  15701. group 1: year
  15702. group 2: month
  15703. group 3: day number
  15704. group 4: day name
  15705. group 5: hours, if any
  15706. group 6: minutes, if any"
  15707. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15708. (pos (point))
  15709. (match?
  15710. (let ((boundaries (org-in-regexp regexp)))
  15711. (save-match-data
  15712. (cond ((null boundaries) nil)
  15713. ((eq extended 'lax) t)
  15714. (t
  15715. (or (and (eq extended 'agenda)
  15716. (or (org-at-planning-p)
  15717. (org-at-property-p)
  15718. (and (bound-and-true-p
  15719. org-agenda-include-inactive-timestamps)
  15720. (org-at-clock-log-p))))
  15721. (eq 'timestamp
  15722. (save-excursion
  15723. (when (= pos (cdr boundaries)) (forward-char -1))
  15724. (org-element-type (org-element-context)))))))))))
  15725. (cond
  15726. ((not match?) nil)
  15727. ((= pos (match-beginning 0)) 'bracket)
  15728. ;; Distinguish location right before the closing bracket from
  15729. ;; right after it.
  15730. ((= pos (1- (match-end 0))) 'bracket)
  15731. ((= pos (match-end 0)) 'after)
  15732. ((org-pos-in-match-range pos 2) 'year)
  15733. ((org-pos-in-match-range pos 3) 'month)
  15734. ((org-pos-in-match-range pos 7) 'hour)
  15735. ((org-pos-in-match-range pos 8) 'minute)
  15736. ((or (org-pos-in-match-range pos 4)
  15737. (org-pos-in-match-range pos 5)) 'day)
  15738. ((and (> pos (or (match-end 8) (match-end 5)))
  15739. (< pos (match-end 0)))
  15740. (- pos (or (match-end 8) (match-end 5))))
  15741. (t 'day))))
  15742. (defun org-toggle-timestamp-type ()
  15743. "Toggle the type (<active> or [inactive]) of a time stamp."
  15744. (interactive)
  15745. (when (org-at-timestamp-p 'lax)
  15746. (let ((beg (match-beginning 0)) (end (match-end 0))
  15747. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15748. (save-excursion
  15749. (goto-char beg)
  15750. (while (re-search-forward "[][<>]" end t)
  15751. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15752. t t)))
  15753. (message "Timestamp is now %sactive"
  15754. (if (equal (char-after beg) ?<) "" "in")))))
  15755. (defun org-at-clock-log-p ()
  15756. "Non-nil if point is on a clock log line."
  15757. (and (org-match-line org-clock-line-re)
  15758. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15759. (defvar org-clock-history) ; defined in org-clock.el
  15760. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15761. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15762. "Change the date in the time stamp at point.
  15763. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15764. `year', `minute', `second'. If WHAT is not given, the cursor position
  15765. in the timestamp determines what will be changed.
  15766. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15767. (let ((origin (point))
  15768. (timestamp? (org-at-timestamp-p 'lax))
  15769. origin-cat
  15770. with-hm inactive
  15771. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15772. extra rem
  15773. ts time time0 fixnext clrgx)
  15774. (unless timestamp? (user-error "Not at a timestamp"))
  15775. (if (and (not what) (eq timestamp? 'bracket))
  15776. (org-toggle-timestamp-type)
  15777. ;; Point isn't on brackets. Remember the part of the time-stamp
  15778. ;; the point was in. Indeed, size of time-stamps may change,
  15779. ;; but point must be kept in the same category nonetheless.
  15780. (setq origin-cat timestamp?)
  15781. (when (and (not what) (not (eq timestamp? 'day))
  15782. org-display-custom-times
  15783. (get-text-property (point) 'display)
  15784. (not (get-text-property (1- (point)) 'display)))
  15785. (setq timestamp? 'day))
  15786. (setq timestamp? (or what timestamp?)
  15787. inactive (= (char-after (match-beginning 0)) ?\[)
  15788. ts (match-string 0))
  15789. (replace-match "")
  15790. (when (string-match
  15791. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15792. ts)
  15793. (setq extra (match-string 1 ts))
  15794. (when suppress-tmp-delay
  15795. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15796. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15797. (setq with-hm t))
  15798. (setq time0 (org-parse-time-string ts))
  15799. (when (and updown
  15800. (eq timestamp? 'minute)
  15801. (not current-prefix-arg))
  15802. ;; This looks like s-up and s-down. Change by one rounding step.
  15803. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15804. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15805. (setcar (cdr time0) (+ (nth 1 time0)
  15806. (if (> n 0) (- rem) (- dm rem))))))
  15807. (setq time
  15808. (apply #'encode-time
  15809. (or (car time0) 0)
  15810. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15811. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15812. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15813. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15814. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15815. (nthcdr 6 time0)))
  15816. (when (and (memq timestamp? '(hour minute))
  15817. extra
  15818. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15819. (setq extra (org-modify-ts-extra
  15820. extra
  15821. (if (eq timestamp? 'hour) 2 5)
  15822. n dm)))
  15823. (when (integerp timestamp?)
  15824. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15825. (when (eq what 'calendar)
  15826. (let ((cal-date (org-get-date-from-calendar)))
  15827. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15828. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15829. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15830. (setcar time0 (or (car time0) 0))
  15831. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15832. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15833. (setq time (apply 'encode-time time0))))
  15834. ;; Insert the new time-stamp, and ensure point stays in the same
  15835. ;; category as before (i.e. not after the last position in that
  15836. ;; category).
  15837. (let ((pos (point)))
  15838. ;; Stay before inserted string. `save-excursion' is of no use.
  15839. (setq org-last-changed-timestamp
  15840. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15841. (goto-char pos))
  15842. (save-match-data
  15843. (looking-at org-ts-regexp3)
  15844. (goto-char
  15845. (pcase origin-cat
  15846. ;; `day' category ends before `hour' if any, or at the end
  15847. ;; of the day name.
  15848. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15849. (`hour (min (match-end 7) origin))
  15850. (`minute (min (1- (match-end 8)) origin))
  15851. ((pred integerp) (min (1- (match-end 0)) origin))
  15852. ;; Point was right after the time-stamp. However, the
  15853. ;; time-stamp length might have changed, so refer to
  15854. ;; (match-end 0) instead.
  15855. (`after (match-end 0))
  15856. ;; `year' and `month' have both fixed size: point couldn't
  15857. ;; have moved into another part.
  15858. (_ origin))))
  15859. ;; Update clock if on a CLOCK line.
  15860. (org-clock-update-time-maybe)
  15861. ;; Maybe adjust the closest clock in `org-clock-history'
  15862. (when org-clock-adjust-closest
  15863. (if (not (and (org-at-clock-log-p)
  15864. (< 1 (length (delq nil (mapcar 'marker-position
  15865. org-clock-history))))))
  15866. (message "No clock to adjust")
  15867. (cond ((save-excursion ; fix previous clock?
  15868. (re-search-backward org-ts-regexp0 nil t)
  15869. (looking-back (concat org-clock-string " \\[")
  15870. (line-beginning-position)))
  15871. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15872. ((save-excursion ; fix next clock?
  15873. (re-search-backward org-ts-regexp0 nil t)
  15874. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15875. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15876. (save-window-excursion
  15877. ;; Find closest clock to point, adjust the previous/next one in history
  15878. (let* ((p (save-excursion (org-back-to-heading t)))
  15879. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15880. (clfixnth
  15881. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15882. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15883. (if (not clfixpos)
  15884. (message "No clock to adjust")
  15885. (save-excursion
  15886. (org-goto-marker-or-bmk clfixpos)
  15887. (org-show-subtree)
  15888. (when (re-search-forward clrgx nil t)
  15889. (goto-char (match-beginning 1))
  15890. (let (org-clock-adjust-closest)
  15891. (org-timestamp-change n timestamp? updown))
  15892. (message "Clock adjusted in %s for heading: %s"
  15893. (file-name-nondirectory (buffer-file-name))
  15894. (org-get-heading t t)))))))))
  15895. ;; Try to recenter the calendar window, if any.
  15896. (when (and org-calendar-follow-timestamp-change
  15897. (get-buffer-window "*Calendar*" t)
  15898. (memq timestamp? '(day month year)))
  15899. (org-recenter-calendar (time-to-days time))))))
  15900. (defun org-modify-ts-extra (s pos n dm)
  15901. "Change the different parts of the lead-time and repeat fields in timestamp."
  15902. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15903. ng h m new rem)
  15904. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15905. (cond
  15906. ((or (org-pos-in-match-range pos 2)
  15907. (org-pos-in-match-range pos 3))
  15908. (setq m (string-to-number (match-string 3 s))
  15909. h (string-to-number (match-string 2 s)))
  15910. (if (org-pos-in-match-range pos 2)
  15911. (setq h (+ h n))
  15912. (setq n (* dm (with-no-warnings (cl-signum n))))
  15913. (unless (= 0 (setq rem (% m dm)))
  15914. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15915. (setq m (+ m n)))
  15916. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15917. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15918. (setq h (mod h 24))
  15919. (setq ng 1 new (format "-%02d:%02d" h m)))
  15920. ((org-pos-in-match-range pos 6)
  15921. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15922. ((org-pos-in-match-range pos 5)
  15923. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15924. ((org-pos-in-match-range pos 9)
  15925. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15926. ((org-pos-in-match-range pos 8)
  15927. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15928. (when ng
  15929. (setq s (concat
  15930. (substring s 0 (match-beginning ng))
  15931. new
  15932. (substring s (match-end ng))))))
  15933. s))
  15934. (defun org-recenter-calendar (d)
  15935. "If the calendar is visible, recenter it to date D."
  15936. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15937. (when cwin
  15938. (let ((calendar-move-hook nil))
  15939. (with-selected-window cwin
  15940. (calendar-goto-date
  15941. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15942. (defun org-goto-calendar (&optional arg)
  15943. "Go to the Emacs calendar at the current date.
  15944. If there is a time stamp in the current line, go to that date.
  15945. A prefix ARG can be used to force the current date."
  15946. (interactive "P")
  15947. (let ((calendar-move-hook nil)
  15948. (calendar-view-holidays-initially-flag nil)
  15949. (calendar-view-diary-initially-flag nil)
  15950. diff)
  15951. (when (or (org-at-timestamp-p 'lax)
  15952. (org-match-line (concat ".*" org-ts-regexp)))
  15953. (let ((d1 (time-to-days (current-time)))
  15954. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15955. (setq diff (- d2 d1))))
  15956. (calendar)
  15957. (calendar-goto-today)
  15958. (when (and diff (not arg)) (calendar-forward-day diff))))
  15959. (defun org-get-date-from-calendar ()
  15960. "Return a list (month day year) of date at point in calendar."
  15961. (with-current-buffer "*Calendar*"
  15962. (save-match-data
  15963. (calendar-cursor-to-date))))
  15964. (defun org-date-from-calendar ()
  15965. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15966. If there is already a time stamp at the cursor position, update it."
  15967. (interactive)
  15968. (if (org-at-timestamp-p 'lax)
  15969. (org-timestamp-change 0 'calendar)
  15970. (let ((cal-date (org-get-date-from-calendar)))
  15971. (org-insert-time-stamp
  15972. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15973. (defcustom org-image-actual-width t
  15974. "Should we use the actual width of images when inlining them?
  15975. When set to t, always use the image width.
  15976. When set to a number, use imagemagick (when available) to set
  15977. the image's width to this value.
  15978. When set to a number in a list, try to get the width from any
  15979. #+ATTR.* keyword if it matches a width specification like
  15980. #+ATTR_HTML: :width 300px
  15981. and fall back on that number if none is found.
  15982. When set to nil, try to get the width from an #+ATTR.* keyword
  15983. and fall back on the original width if none is found.
  15984. This requires Emacs >= 24.1, build with imagemagick support."
  15985. :group 'org-appearance
  15986. :version "24.4"
  15987. :package-version '(Org . "8.0")
  15988. :type '(choice
  15989. (const :tag "Use the image width" t)
  15990. (integer :tag "Use a number of pixels")
  15991. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  15992. (const :tag "Use #+ATTR* or don't resize" nil)))
  15993. (defcustom org-agenda-inhibit-startup nil
  15994. "Inhibit startup when preparing agenda buffers.
  15995. When this variable is t, the initialization of the Org agenda
  15996. buffers is inhibited: e.g. the visibility state is not set, the
  15997. tables are not re-aligned, etc."
  15998. :type 'boolean
  15999. :version "24.3"
  16000. :group 'org-agenda)
  16001. (defcustom org-agenda-ignore-properties nil
  16002. "Avoid updating text properties when building the agenda.
  16003. Properties are used to prepare buffers for effort estimates,
  16004. appointments, statistics and subtree-local categories.
  16005. If you don't use these in the agenda, you can add them to this
  16006. list and agenda building will be a bit faster.
  16007. The value is a list, with zero or more of the symbols `effort', `appt',
  16008. `stats' or `category'."
  16009. :type '(set :greedy t
  16010. (const effort)
  16011. (const appt)
  16012. (const stats)
  16013. (const category))
  16014. :version "26.1"
  16015. :package-version '(Org . "8.3")
  16016. :group 'org-agenda)
  16017. ;;;; Files
  16018. (defun org-save-all-org-buffers ()
  16019. "Save all Org buffers without user confirmation."
  16020. (interactive)
  16021. (message "Saving all Org buffers...")
  16022. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16023. (when (featurep 'org-id) (org-id-locations-save))
  16024. (message "Saving all Org buffers... done"))
  16025. (defun org-revert-all-org-buffers ()
  16026. "Revert all Org buffers.
  16027. Prompt for confirmation when there are unsaved changes.
  16028. Be sure you know what you are doing before letting this function
  16029. overwrite your changes.
  16030. This function is useful in a setup where one tracks Org files
  16031. with a version control system, to revert on one machine after pulling
  16032. changes from another. I believe the procedure must be like this:
  16033. 1. M-x org-save-all-org-buffers
  16034. 2. Pull changes from the other machine, resolve conflicts
  16035. 3. M-x org-revert-all-org-buffers"
  16036. (interactive)
  16037. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16038. (user-error "Abort"))
  16039. (save-excursion
  16040. (save-window-excursion
  16041. (dolist (b (buffer-list))
  16042. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16043. (with-current-buffer b buffer-file-name))
  16044. (pop-to-buffer-same-window b)
  16045. (revert-buffer t 'no-confirm)))
  16046. (when (and (featurep 'org-id) org-id-track-globally)
  16047. (org-id-locations-load)))))
  16048. ;;;; Agenda files
  16049. ;;;###autoload
  16050. (defun org-switchb (&optional arg)
  16051. "Switch between Org buffers.
  16052. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16053. With `\\[universal-argument] \\[universal-argument]' \
  16054. prefix, restrict available buffers to agenda files."
  16055. (interactive "P")
  16056. (let ((blist (org-buffer-list
  16057. (cond ((equal arg '(4)) 'files)
  16058. ((equal arg '(16)) 'agenda)))))
  16059. (pop-to-buffer-same-window
  16060. (completing-read "Org buffer: "
  16061. (mapcar #'list (mapcar #'buffer-name blist))
  16062. nil t))))
  16063. (defun org-buffer-list (&optional predicate exclude-tmp)
  16064. "Return a list of Org buffers.
  16065. PREDICATE can be `export', `files' or `agenda'.
  16066. export restrict the list to Export buffers.
  16067. files restrict the list to buffers visiting Org files.
  16068. agenda restrict the list to buffers visiting agenda files.
  16069. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16070. (let* ((bfn nil)
  16071. (agenda-files (and (eq predicate 'agenda)
  16072. (mapcar 'file-truename (org-agenda-files t))))
  16073. (filter
  16074. (cond
  16075. ((eq predicate 'files)
  16076. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16077. ((eq predicate 'export)
  16078. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16079. ((eq predicate 'agenda)
  16080. (lambda (b)
  16081. (with-current-buffer b
  16082. (and (derived-mode-p 'org-mode)
  16083. (setq bfn (buffer-file-name b))
  16084. (member (file-truename bfn) agenda-files)))))
  16085. (t (lambda (b) (with-current-buffer b
  16086. (or (derived-mode-p 'org-mode)
  16087. (string-match "\\*Org .*Export"
  16088. (buffer-name b)))))))))
  16089. (delq nil
  16090. (mapcar
  16091. (lambda(b)
  16092. (if (and (funcall filter b)
  16093. (or (not exclude-tmp)
  16094. (not (string-match "tmp" (buffer-name b)))))
  16095. b
  16096. nil))
  16097. (buffer-list)))))
  16098. (defun org-agenda-files (&optional unrestricted archives)
  16099. "Get the list of agenda files.
  16100. Optional UNRESTRICTED means return the full list even if a restriction
  16101. is currently in place.
  16102. When ARCHIVES is t, include all archive files that are really being
  16103. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16104. `org-agenda-archives-mode' is t."
  16105. (let ((files
  16106. (cond
  16107. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16108. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16109. ((listp org-agenda-files) org-agenda-files)
  16110. (t (error "Invalid value of `org-agenda-files'")))))
  16111. (setq files (apply 'append
  16112. (mapcar (lambda (f)
  16113. (if (file-directory-p f)
  16114. (directory-files
  16115. f t org-agenda-file-regexp)
  16116. (list f)))
  16117. files)))
  16118. (when org-agenda-skip-unavailable-files
  16119. (setq files (delq nil
  16120. (mapcar (function
  16121. (lambda (file)
  16122. (and (file-readable-p file) file)))
  16123. files))))
  16124. (when (or (eq archives t)
  16125. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16126. (setq files (org-add-archive-files files)))
  16127. files))
  16128. (defun org-agenda-file-p (&optional file)
  16129. "Return non-nil, if FILE is an agenda file.
  16130. If FILE is omitted, use the file associated with the current
  16131. buffer."
  16132. (let ((fname (or file (buffer-file-name))))
  16133. (and fname
  16134. (member (file-truename fname)
  16135. (mapcar #'file-truename (org-agenda-files t))))))
  16136. (defun org-edit-agenda-file-list ()
  16137. "Edit the list of agenda files.
  16138. Depending on setup, this either uses customize to edit the variable
  16139. `org-agenda-files', or it visits the file that is holding the list. In the
  16140. latter case, the buffer is set up in a way that saving it automatically kills
  16141. the buffer and restores the previous window configuration."
  16142. (interactive)
  16143. (if (stringp org-agenda-files)
  16144. (let ((cw (current-window-configuration)))
  16145. (find-file org-agenda-files)
  16146. (setq-local org-window-configuration cw)
  16147. (add-hook 'after-save-hook
  16148. (lambda ()
  16149. (set-window-configuration
  16150. (prog1 org-window-configuration
  16151. (kill-buffer (current-buffer))))
  16152. (org-install-agenda-files-menu)
  16153. (message "New agenda file list installed"))
  16154. nil 'local)
  16155. (message "%s" (substitute-command-keys
  16156. "Edit list and finish with \\[save-buffer]")))
  16157. (customize-variable 'org-agenda-files)))
  16158. (defun org-store-new-agenda-file-list (list)
  16159. "Set new value for the agenda file list and save it correctly."
  16160. (if (stringp org-agenda-files)
  16161. (let ((fe (org-read-agenda-file-list t)) b u)
  16162. (while (setq b (find-buffer-visiting org-agenda-files))
  16163. (kill-buffer b))
  16164. (with-temp-file org-agenda-files
  16165. (insert
  16166. (mapconcat
  16167. (lambda (f) ;; Keep un-expanded entries.
  16168. (if (setq u (assoc f fe))
  16169. (cdr u)
  16170. f))
  16171. list "\n")
  16172. "\n")))
  16173. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16174. (org-insert-mode-line-in-empty-file nil))
  16175. (setq org-agenda-files list)
  16176. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16177. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16178. "Read the list of agenda files from a file.
  16179. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16180. filenames, used by `org-store-new-agenda-file-list' to write back
  16181. un-expanded file names."
  16182. (when (file-directory-p org-agenda-files)
  16183. (error "`org-agenda-files' cannot be a single directory"))
  16184. (when (stringp org-agenda-files)
  16185. (with-temp-buffer
  16186. (insert-file-contents org-agenda-files)
  16187. (mapcar
  16188. (lambda (f)
  16189. (let ((e (expand-file-name (substitute-in-file-name f)
  16190. org-directory)))
  16191. (if pair-with-expansion
  16192. (cons e f)
  16193. e)))
  16194. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16195. ;;;###autoload
  16196. (defun org-cycle-agenda-files ()
  16197. "Cycle through the files in `org-agenda-files'.
  16198. If the current buffer visits an agenda file, find the next one in the list.
  16199. If the current buffer does not, find the first agenda file."
  16200. (interactive)
  16201. (let* ((fs (or (org-agenda-files t)
  16202. (user-error "No agenda files")))
  16203. (files (copy-sequence fs))
  16204. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16205. file)
  16206. (when tcf
  16207. (while (and (setq file (pop files))
  16208. (not (equal (file-truename file) tcf)))))
  16209. (find-file (car (or files fs)))
  16210. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16211. (defun org-agenda-file-to-front (&optional to-end)
  16212. "Move/add the current file to the top of the agenda file list.
  16213. If the file is not present in the list, it is added to the front. If it is
  16214. present, it is moved there. With optional argument TO-END, add/move to the
  16215. end of the list."
  16216. (interactive "P")
  16217. (let ((org-agenda-skip-unavailable-files nil)
  16218. (file-alist (mapcar (lambda (x)
  16219. (cons (file-truename x) x))
  16220. (org-agenda-files t)))
  16221. (ctf (file-truename
  16222. (or buffer-file-name
  16223. (user-error "Please save the current buffer to a file"))))
  16224. x had)
  16225. (setq x (assoc ctf file-alist) had x)
  16226. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16227. (if to-end
  16228. (setq file-alist (append (delq x file-alist) (list x)))
  16229. (setq file-alist (cons x (delq x file-alist))))
  16230. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16231. (org-install-agenda-files-menu)
  16232. (message "File %s to %s of agenda file list"
  16233. (if had "moved" "added") (if to-end "end" "front"))))
  16234. (defun org-remove-file (&optional file)
  16235. "Remove current file from the list of files in variable `org-agenda-files'.
  16236. These are the files which are being checked for agenda entries.
  16237. Optional argument FILE means use this file instead of the current."
  16238. (interactive)
  16239. (let* ((org-agenda-skip-unavailable-files nil)
  16240. (file (or file buffer-file-name
  16241. (user-error "Current buffer does not visit a file")))
  16242. (true-file (file-truename file))
  16243. (afile (abbreviate-file-name file))
  16244. (files (delq nil (mapcar
  16245. (lambda (x)
  16246. (unless (equal true-file
  16247. (file-truename x))
  16248. x))
  16249. (org-agenda-files t)))))
  16250. (if (not (= (length files) (length (org-agenda-files t))))
  16251. (progn
  16252. (org-store-new-agenda-file-list files)
  16253. (org-install-agenda-files-menu)
  16254. (message "Removed from Org Agenda list: %s" afile))
  16255. (message "File was not in list: %s (not removed)" afile))))
  16256. (defun org-file-menu-entry (file)
  16257. (vector file (list 'find-file file) t))
  16258. (defun org-check-agenda-file (file)
  16259. "Make sure FILE exists. If not, ask user what to do."
  16260. (unless (file-exists-p file)
  16261. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16262. (abbreviate-file-name file))
  16263. (let ((r (downcase (read-char-exclusive))))
  16264. (cond
  16265. ((equal r ?r)
  16266. (org-remove-file file)
  16267. (throw 'nextfile t))
  16268. (t (user-error "Abort"))))))
  16269. (defun org-get-agenda-file-buffer (file)
  16270. "Get an agenda buffer visiting FILE.
  16271. If the buffer needs to be created, add it to the list of buffers
  16272. which might be released later."
  16273. (let ((buf (org-find-base-buffer-visiting file)))
  16274. (if buf
  16275. buf ; just return it
  16276. ;; Make a new buffer and remember it
  16277. (setq buf (find-file-noselect file))
  16278. (when buf (push buf org-agenda-new-buffers))
  16279. buf)))
  16280. (defun org-release-buffers (blist)
  16281. "Release all buffers in list, asking the user for confirmation when needed.
  16282. When a buffer is unmodified, it is just killed. When modified, it is saved
  16283. \(if the user agrees) and then killed."
  16284. (let (file)
  16285. (dolist (buf blist)
  16286. (setq file (buffer-file-name buf))
  16287. (when (and (buffer-modified-p buf)
  16288. file
  16289. (y-or-n-p (format "Save file %s? " file)))
  16290. (with-current-buffer buf (save-buffer)))
  16291. (kill-buffer buf))))
  16292. (defun org-agenda-prepare-buffers (files)
  16293. "Create buffers for all agenda files, protect archived trees and comments."
  16294. (interactive)
  16295. (let ((pa '(:org-archived t))
  16296. (pc '(:org-comment t))
  16297. (pall '(:org-archived t :org-comment t))
  16298. (inhibit-read-only t)
  16299. (org-inhibit-startup org-agenda-inhibit-startup)
  16300. (rea (org-make-tag-string (list org-archive-tag)))
  16301. re pos)
  16302. (setq org-tag-alist-for-agenda nil
  16303. org-tag-groups-alist-for-agenda nil)
  16304. (save-excursion
  16305. (save-restriction
  16306. (dolist (file files)
  16307. (catch 'nextfile
  16308. (if (bufferp file)
  16309. (set-buffer file)
  16310. (org-check-agenda-file file)
  16311. (set-buffer (org-get-agenda-file-buffer file)))
  16312. (widen)
  16313. (org-set-regexps-and-options 'tags-only)
  16314. (setq pos (point))
  16315. (or (memq 'category org-agenda-ignore-properties)
  16316. (org-refresh-category-properties))
  16317. (or (memq 'stats org-agenda-ignore-properties)
  16318. (org-refresh-stats-properties))
  16319. (or (memq 'effort org-agenda-ignore-properties)
  16320. (org-refresh-effort-properties))
  16321. (or (memq 'appt org-agenda-ignore-properties)
  16322. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16323. (setq org-todo-keywords-for-agenda
  16324. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16325. (setq org-done-keywords-for-agenda
  16326. (append org-done-keywords-for-agenda org-done-keywords))
  16327. (setq org-todo-keyword-alist-for-agenda
  16328. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16329. (setq org-tag-alist-for-agenda
  16330. (org--tag-add-to-alist
  16331. org-tag-alist-for-agenda
  16332. org-current-tag-alist))
  16333. ;; Merge current file's tag groups into global
  16334. ;; `org-tag-groups-alist-for-agenda'.
  16335. (when org-group-tags
  16336. (dolist (alist org-tag-groups-alist)
  16337. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16338. (if old
  16339. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16340. (push alist org-tag-groups-alist-for-agenda)))))
  16341. (with-silent-modifications
  16342. (save-excursion
  16343. (remove-text-properties (point-min) (point-max) pall)
  16344. (when org-agenda-skip-archived-trees
  16345. (goto-char (point-min))
  16346. (while (re-search-forward rea nil t)
  16347. (when (org-at-heading-p t)
  16348. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16349. (goto-char (point-min))
  16350. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16351. (while (re-search-forward re nil t)
  16352. (when (save-match-data (org-in-commented-heading-p t))
  16353. (add-text-properties
  16354. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16355. (goto-char pos)))))
  16356. (setq org-todo-keywords-for-agenda
  16357. (org-uniquify org-todo-keywords-for-agenda))
  16358. (setq org-todo-keyword-alist-for-agenda
  16359. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16360. ;;;; CDLaTeX minor mode
  16361. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16362. "Keymap for the minor `org-cdlatex-mode'.")
  16363. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16364. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16365. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16366. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16367. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16368. (defvar org-cdlatex-texmathp-advice-is-done nil
  16369. "Flag remembering if we have applied the advice to texmathp already.")
  16370. (define-minor-mode org-cdlatex-mode
  16371. "Toggle the minor `org-cdlatex-mode'.
  16372. This mode supports entering LaTeX environment and math in LaTeX fragments
  16373. in Org mode.
  16374. \\{org-cdlatex-mode-map}"
  16375. nil " OCDL" nil
  16376. (when org-cdlatex-mode
  16377. (require 'cdlatex)
  16378. (run-hooks 'cdlatex-mode-hook)
  16379. (cdlatex-compute-tables))
  16380. (unless org-cdlatex-texmathp-advice-is-done
  16381. (setq org-cdlatex-texmathp-advice-is-done t)
  16382. (defadvice texmathp (around org-math-always-on activate)
  16383. "Always return t in Org buffers.
  16384. This is because we want to insert math symbols without dollars even outside
  16385. the LaTeX math segments. If Org mode thinks that point is actually inside
  16386. an embedded LaTeX fragment, let `texmathp' do its job.
  16387. `\\[org-cdlatex-mode-map]'"
  16388. (interactive)
  16389. (let (p)
  16390. (cond
  16391. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16392. ((eq this-command 'cdlatex-math-symbol)
  16393. (setq ad-return-value t
  16394. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16395. (t
  16396. (let ((p (org-inside-LaTeX-fragment-p)))
  16397. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16398. (setq ad-return-value t
  16399. texmathp-why '("Org mode embedded math" . 0))
  16400. (when p ad-do-it)))))))))
  16401. (defun turn-on-org-cdlatex ()
  16402. "Unconditionally turn on `org-cdlatex-mode'."
  16403. (org-cdlatex-mode 1))
  16404. (defun org-try-cdlatex-tab ()
  16405. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16406. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16407. - inside a LaTeX fragment, or
  16408. - after the first word in a line, where an abbreviation expansion could
  16409. insert a LaTeX environment."
  16410. (when org-cdlatex-mode
  16411. (cond
  16412. ;; Before any word on the line: No expansion possible.
  16413. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16414. ;; Just after first word on the line: Expand it. Make sure it
  16415. ;; cannot happen on headlines, though.
  16416. ((save-excursion
  16417. (skip-chars-backward "a-zA-Z0-9*")
  16418. (skip-chars-backward " \t")
  16419. (and (bolp) (not (org-at-heading-p))))
  16420. (cdlatex-tab) t)
  16421. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16422. (defun org-cdlatex-underscore-caret (&optional _arg)
  16423. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16424. Revert to the normal definition outside of these fragments."
  16425. (interactive "P")
  16426. (if (org-inside-LaTeX-fragment-p)
  16427. (call-interactively 'cdlatex-sub-superscript)
  16428. (let (org-cdlatex-mode)
  16429. (call-interactively (key-binding (vector last-input-event))))))
  16430. (defun org-cdlatex-math-modify (&optional _arg)
  16431. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16432. Revert to the normal definition outside of these fragments."
  16433. (interactive "P")
  16434. (if (org-inside-LaTeX-fragment-p)
  16435. (call-interactively 'cdlatex-math-modify)
  16436. (let (org-cdlatex-mode)
  16437. (call-interactively (key-binding (vector last-input-event))))))
  16438. (defun org-cdlatex-environment-indent (&optional environment item)
  16439. "Execute `cdlatex-environment' and indent the inserted environment.
  16440. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16441. The inserted environment is indented to current indentation
  16442. unless point is at the beginning of the line, in which the
  16443. environment remains unintended."
  16444. (interactive)
  16445. ;; cdlatex-environment always return nil. Therefore, capture output
  16446. ;; first and determine if an environment was selected.
  16447. (let* ((beg (point-marker))
  16448. (end (copy-marker (point) t))
  16449. (inserted (progn
  16450. (ignore-errors (cdlatex-environment environment item))
  16451. (< beg end)))
  16452. ;; Figure out how many lines to move forward after the
  16453. ;; environment has been inserted.
  16454. (lines (when inserted
  16455. (save-excursion
  16456. (- (cl-loop while (< beg (point))
  16457. with x = 0
  16458. do (forward-line -1)
  16459. (cl-incf x)
  16460. finally return x)
  16461. (if (progn (goto-char beg)
  16462. (and (progn (skip-chars-forward " \t") (eolp))
  16463. (progn (skip-chars-backward " \t") (bolp))))
  16464. 1 0)))))
  16465. (env (org-trim (delete-and-extract-region beg end))))
  16466. (when inserted
  16467. ;; Get indentation of next line unless at column 0.
  16468. (let ((ind (if (bolp) 0
  16469. (save-excursion
  16470. (org-return-indent)
  16471. (prog1 (current-indentation)
  16472. (when (progn (skip-chars-forward " \t") (eolp))
  16473. (delete-region beg (point)))))))
  16474. (bol (progn (skip-chars-backward " \t") (bolp))))
  16475. ;; Insert a newline before environment unless at column zero
  16476. ;; to "escape" the current line. Insert a newline if
  16477. ;; something is one the same line as \end{ENVIRONMENT}.
  16478. (insert
  16479. (concat (unless bol "\n") env
  16480. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16481. (unless (zerop ind)
  16482. (save-excursion
  16483. (goto-char beg)
  16484. (while (< (point) end)
  16485. (unless (eolp) (indent-line-to ind))
  16486. (forward-line))))
  16487. (goto-char beg)
  16488. (forward-line lines)
  16489. (indent-line-to ind)))
  16490. (set-marker beg nil)
  16491. (set-marker end nil)))
  16492. ;;;; LaTeX fragments
  16493. (defun org-inside-LaTeX-fragment-p ()
  16494. "Test if point is inside a LaTeX fragment.
  16495. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16496. sequence appearing also before point.
  16497. Even though the matchers for math are configurable, this function assumes
  16498. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16499. delimiters are skipped when they have been removed by customization.
  16500. The return value is nil, or a cons cell with the delimiter and the
  16501. position of this delimiter.
  16502. This function does a reasonably good job, but can locally be fooled by
  16503. for example currency specifications. For example it will assume being in
  16504. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16505. fragments that are properly closed, but during editing, we have to live
  16506. with the uncertainty caused by missing closing delimiters. This function
  16507. looks only before point, not after."
  16508. (catch 'exit
  16509. (let ((pos (point))
  16510. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16511. (lim (save-excursion (org-backward-paragraph) (point)))
  16512. dd-on str (start 0) m re)
  16513. (goto-char pos)
  16514. (when dodollar
  16515. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16516. re (nth 1 (assoc "$" org-latex-regexps)))
  16517. (while (string-match re str start)
  16518. (cond
  16519. ((= (match-end 0) (length str))
  16520. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16521. ((= (match-end 0) (- (length str) 5))
  16522. (throw 'exit nil))
  16523. (t (setq start (match-end 0))))))
  16524. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16525. (goto-char pos)
  16526. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16527. (and (match-beginning 2) (throw 'exit nil))
  16528. ;; count $$
  16529. (while (re-search-backward "\\$\\$" lim t)
  16530. (setq dd-on (not dd-on)))
  16531. (goto-char pos)
  16532. (when dd-on (cons "$$" m))))))
  16533. (defun org-inside-latex-macro-p ()
  16534. "Is point inside a LaTeX macro or its arguments?"
  16535. (save-match-data
  16536. (org-in-regexp
  16537. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16538. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16539. "Build an overlay between BEG and END using IMAGE file.
  16540. Argument IMAGETYPE is the extension of the displayed image,
  16541. as a string. It defaults to \"png\"."
  16542. (let ((ov (make-overlay beg end))
  16543. (imagetype (or (intern imagetype) 'png)))
  16544. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16545. (overlay-put ov 'evaporate t)
  16546. (overlay-put ov
  16547. 'modification-hooks
  16548. (list (lambda (o _flag _beg _end &optional _l)
  16549. (delete-overlay o))))
  16550. (overlay-put ov
  16551. 'display
  16552. (list 'image :type imagetype :file image :ascent 'center))))
  16553. (defun org--list-latex-overlays (&optional beg end)
  16554. "List all Org LaTeX overlays in current buffer.
  16555. Limit to overlays between BEG and END when those are provided."
  16556. (cl-remove-if-not
  16557. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16558. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16559. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16560. "Remove all overlays with LaTeX fragment images in current buffer.
  16561. When optional arguments BEG and END are non-nil, remove all
  16562. overlays between them instead. Return a non-nil value when some
  16563. overlays were removed, nil otherwise."
  16564. (let ((overlays (org--list-latex-overlays beg end)))
  16565. (mapc #'delete-overlay overlays)
  16566. overlays))
  16567. (defun org-toggle-latex-fragment (&optional arg)
  16568. "Preview the LaTeX fragment at point, or all locally or globally.
  16569. If the cursor is on a LaTeX fragment, create the image and overlay
  16570. it over the source code, if there is none. Remove it otherwise.
  16571. If there is no fragment at point, display all fragments in the
  16572. current section.
  16573. With prefix ARG, preview or clear image for all fragments in the
  16574. current subtree or in the whole buffer when used before the first
  16575. headline. With a prefix ARG `\\[universal-argument] \
  16576. \\[universal-argument]' preview or clear images
  16577. for all fragments in the buffer."
  16578. (interactive "P")
  16579. (when (display-graphic-p)
  16580. (catch 'exit
  16581. (save-excursion
  16582. (let (beg end msg)
  16583. (cond
  16584. ((or (equal arg '(16))
  16585. (and (equal arg '(4))
  16586. (org-with-limited-levels (org-before-first-heading-p))))
  16587. (if (org-remove-latex-fragment-image-overlays)
  16588. (progn (message "LaTeX fragments images removed from buffer")
  16589. (throw 'exit nil))
  16590. (setq msg "Creating images for buffer...")))
  16591. ((equal arg '(4))
  16592. (org-with-limited-levels (org-back-to-heading t))
  16593. (setq beg (point))
  16594. (setq end (progn (org-end-of-subtree t) (point)))
  16595. (if (org-remove-latex-fragment-image-overlays beg end)
  16596. (progn
  16597. (message "LaTeX fragment images removed from subtree")
  16598. (throw 'exit nil))
  16599. (setq msg "Creating images for subtree...")))
  16600. ((let ((datum (org-element-context)))
  16601. (when (memq (org-element-type datum)
  16602. '(latex-environment latex-fragment))
  16603. (setq beg (org-element-property :begin datum))
  16604. (setq end (org-element-property :end datum))
  16605. (if (org-remove-latex-fragment-image-overlays beg end)
  16606. (progn (message "LaTeX fragment image removed")
  16607. (throw 'exit nil))
  16608. (setq msg "Creating image...")))))
  16609. (t
  16610. (org-with-limited-levels
  16611. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16612. (outline-previous-heading)
  16613. (point)))
  16614. (setq end (progn (outline-next-heading) (point)))
  16615. (if (org-remove-latex-fragment-image-overlays beg end)
  16616. (progn
  16617. (message "LaTeX fragment images removed from section")
  16618. (throw 'exit nil))
  16619. (setq msg "Creating images for section...")))))
  16620. (let ((file (buffer-file-name (buffer-base-buffer))))
  16621. (org-format-latex
  16622. (concat org-preview-latex-image-directory "org-ltximg")
  16623. beg end
  16624. ;; Emacs cannot overlay images from remote hosts. Create
  16625. ;; it in `temporary-file-directory' instead.
  16626. (if (or (not file) (file-remote-p file))
  16627. temporary-file-directory
  16628. default-directory)
  16629. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16630. (message (concat msg "done")))))))
  16631. (defun org-format-latex
  16632. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16633. "Replace LaTeX fragments with links to an image.
  16634. The function takes care of creating the replacement image.
  16635. Only consider fragments between BEG and END when those are
  16636. provided.
  16637. When optional argument OVERLAYS is non-nil, display the image on
  16638. top of the fragment instead of replacing it.
  16639. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16640. Some of the options can be changed using the variable
  16641. `org-format-latex-options', which see."
  16642. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16643. (unless (eq processing-type 'verbatim)
  16644. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16645. (cnt 0)
  16646. checkdir-flag)
  16647. (goto-char (or beg (point-min)))
  16648. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16649. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16650. (overlay-recenter (or end (point-max))))
  16651. (while (re-search-forward math-regexp end t)
  16652. (unless (and overlays
  16653. (eq (get-char-property (point) 'org-overlay-type)
  16654. 'org-latex-overlay))
  16655. (let* ((context (org-element-context))
  16656. (type (org-element-type context)))
  16657. (when (memq type '(latex-environment latex-fragment))
  16658. (let ((block-type (eq type 'latex-environment))
  16659. (value (org-element-property :value context))
  16660. (beg (org-element-property :begin context))
  16661. (end (save-excursion
  16662. (goto-char (org-element-property :end context))
  16663. (skip-chars-backward " \r\t\n")
  16664. (point))))
  16665. (cond
  16666. ((eq processing-type 'mathjax)
  16667. ;; Prepare for MathJax processing.
  16668. (if (not (string-match "\\`\\$\\$?" value))
  16669. (goto-char end)
  16670. (delete-region beg end)
  16671. (if (string= (match-string 0 value) "$$")
  16672. (insert "\\[" (substring value 2 -2) "\\]")
  16673. (insert "\\(" (substring value 1 -1) "\\)"))))
  16674. ((assq processing-type org-preview-latex-process-alist)
  16675. ;; Process to an image.
  16676. (cl-incf cnt)
  16677. (goto-char beg)
  16678. (let* ((processing-info
  16679. (cdr (assq processing-type org-preview-latex-process-alist)))
  16680. (face (face-at-point))
  16681. ;; Get the colors from the face at point.
  16682. (fg
  16683. (let ((color (plist-get org-format-latex-options
  16684. :foreground)))
  16685. (if (and forbuffer (eq color 'auto))
  16686. (face-attribute face :foreground nil 'default)
  16687. color)))
  16688. (bg
  16689. (let ((color (plist-get org-format-latex-options
  16690. :background)))
  16691. (if (and forbuffer (eq color 'auto))
  16692. (face-attribute face :background nil 'default)
  16693. color)))
  16694. (hash (sha1 (prin1-to-string
  16695. (list org-format-latex-header
  16696. org-latex-default-packages-alist
  16697. org-latex-packages-alist
  16698. org-format-latex-options
  16699. forbuffer value fg bg))))
  16700. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16701. (absprefix (expand-file-name prefix dir))
  16702. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16703. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16704. (sep (and block-type "\n\n"))
  16705. (link (concat sep "[[file:" linkfile "]]" sep))
  16706. (options
  16707. (org-combine-plists
  16708. org-format-latex-options
  16709. `(:foreground ,fg :background ,bg))))
  16710. (when msg (message msg cnt))
  16711. (unless checkdir-flag ; Ensure the directory exists.
  16712. (setq checkdir-flag t)
  16713. (let ((todir (file-name-directory absprefix)))
  16714. (unless (file-directory-p todir)
  16715. (make-directory todir t))))
  16716. (unless (file-exists-p movefile)
  16717. (org-create-formula-image
  16718. value movefile options forbuffer processing-type))
  16719. (if overlays
  16720. (progn
  16721. (dolist (o (overlays-in beg end))
  16722. (when (eq (overlay-get o 'org-overlay-type)
  16723. 'org-latex-overlay)
  16724. (delete-overlay o)))
  16725. (org--format-latex-make-overlay beg end movefile imagetype)
  16726. (goto-char end))
  16727. (delete-region beg end)
  16728. (insert
  16729. (org-add-props link
  16730. (list 'org-latex-src
  16731. (replace-regexp-in-string "\"" "" value)
  16732. 'org-latex-src-embed-type
  16733. (if block-type 'paragraph 'character)))))))
  16734. ((eq processing-type 'mathml)
  16735. ;; Process to MathML.
  16736. (unless (org-format-latex-mathml-available-p)
  16737. (user-error "LaTeX to MathML converter not configured"))
  16738. (cl-incf cnt)
  16739. (when msg (message msg cnt))
  16740. (goto-char beg)
  16741. (delete-region beg end)
  16742. (insert (org-format-latex-as-mathml
  16743. value block-type prefix dir)))
  16744. (t
  16745. (error "Unknown conversion process %s for LaTeX fragments"
  16746. processing-type)))))))))))
  16747. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16748. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16749. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16750. sucessful, return the portion between \"<math...> </math>\"
  16751. elements otherwise return nil. When MATHML-FILE is specified,
  16752. write the results in to that file. When invoked as an
  16753. interactive command, prompt for LATEX-FRAG, with initial value
  16754. set to the current active region and echo the results for user
  16755. inspection."
  16756. (interactive (list (let ((frag (when (org-region-active-p)
  16757. (buffer-substring-no-properties
  16758. (region-beginning) (region-end)))))
  16759. (read-string "LaTeX Fragment: " frag nil frag))))
  16760. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16761. (let* ((tmp-in-file
  16762. (let ((file (file-relative-name
  16763. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16764. (write-region latex-frag nil file)
  16765. file))
  16766. (tmp-out-file (file-relative-name
  16767. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16768. (cmd (format-spec
  16769. org-latex-to-mathml-convert-command
  16770. `((?j . ,(and org-latex-to-mathml-jar-file
  16771. (shell-quote-argument
  16772. (expand-file-name
  16773. org-latex-to-mathml-jar-file))))
  16774. (?I . ,(shell-quote-argument tmp-in-file))
  16775. (?i . ,latex-frag)
  16776. (?o . ,(shell-quote-argument tmp-out-file)))))
  16777. mathml shell-command-output)
  16778. (when (called-interactively-p 'any)
  16779. (unless (org-format-latex-mathml-available-p)
  16780. (user-error "LaTeX to MathML converter not configured")))
  16781. (message "Running %s" cmd)
  16782. (setq shell-command-output (shell-command-to-string cmd))
  16783. (setq mathml
  16784. (when (file-readable-p tmp-out-file)
  16785. (with-current-buffer (find-file-noselect tmp-out-file t)
  16786. (goto-char (point-min))
  16787. (when (re-search-forward
  16788. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16789. (regexp-quote
  16790. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16791. nil t)
  16792. (prog1 (match-string 0) (kill-buffer))))))
  16793. (cond
  16794. (mathml
  16795. (setq mathml
  16796. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16797. (when mathml-file
  16798. (write-region mathml nil mathml-file))
  16799. (when (called-interactively-p 'any)
  16800. (message mathml)))
  16801. ((message "LaTeX to MathML conversion failed")
  16802. (message shell-command-output)))
  16803. (delete-file tmp-in-file)
  16804. (when (file-exists-p tmp-out-file)
  16805. (delete-file tmp-out-file))
  16806. mathml))
  16807. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16808. prefix &optional dir)
  16809. "Use `org-create-math-formula' but check local cache first."
  16810. (let* ((absprefix (expand-file-name prefix dir))
  16811. (print-length nil) (print-level nil)
  16812. (formula-id (concat
  16813. "formula-"
  16814. (sha1
  16815. (prin1-to-string
  16816. (list latex-frag
  16817. org-latex-to-mathml-convert-command)))))
  16818. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16819. (formula-cache-dir (file-name-directory formula-cache)))
  16820. (unless (file-directory-p formula-cache-dir)
  16821. (make-directory formula-cache-dir t))
  16822. (unless (file-exists-p formula-cache)
  16823. (org-create-math-formula latex-frag formula-cache))
  16824. (if (file-exists-p formula-cache)
  16825. ;; Successful conversion. Return the link to MathML file.
  16826. (org-add-props
  16827. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16828. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16829. 'org-latex-src-embed-type (if latex-frag-type
  16830. 'paragraph 'character)))
  16831. ;; Failed conversion. Return the LaTeX fragment verbatim
  16832. latex-frag)))
  16833. (defun org--get-display-dpi ()
  16834. "Get the DPI of the display.
  16835. The function assumes that the display has the same pixel width in
  16836. the horizontal and vertical directions."
  16837. (if (display-graphic-p)
  16838. (round (/ (display-pixel-height)
  16839. (/ (display-mm-height) 25.4)))
  16840. (error "Attempt to calculate the dpi of a non-graphic display")))
  16841. (defun org-create-formula-image
  16842. (string tofile options buffer &optional processing-type)
  16843. "Create an image from LaTeX source using external processes.
  16844. The LaTeX STRING is saved to a temporary LaTeX file, then
  16845. converted to an image file by process PROCESSING-TYPE defined in
  16846. `org-preview-latex-process-alist'. A nil value defaults to
  16847. `org-preview-latex-default-process'.
  16848. The generated image file is eventually moved to TOFILE.
  16849. The OPTIONS argument controls the size, foreground color and
  16850. background color of the generated image.
  16851. When BUFFER non-nil, this function is used for LaTeX previewing.
  16852. Otherwise, it is used to deal with LaTeX snippets showed in
  16853. a HTML file."
  16854. (let* ((processing-type (or processing-type
  16855. org-preview-latex-default-process))
  16856. (processing-info
  16857. (cdr (assq processing-type org-preview-latex-process-alist)))
  16858. (programs (plist-get processing-info :programs))
  16859. (error-message (or (plist-get processing-info :message) ""))
  16860. (use-xcolor (plist-get processing-info :use-xcolor))
  16861. (image-input-type (plist-get processing-info :image-input-type))
  16862. (image-output-type (plist-get processing-info :image-output-type))
  16863. (post-clean (or (plist-get processing-info :post-clean)
  16864. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16865. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16866. (latex-header
  16867. (or (plist-get processing-info :latex-header)
  16868. (org-latex-make-preamble
  16869. (org-export-get-environment (org-export-get-backend 'latex))
  16870. org-format-latex-header
  16871. 'snippet)))
  16872. (latex-compiler (plist-get processing-info :latex-compiler))
  16873. (image-converter (plist-get processing-info :image-converter))
  16874. (tmpdir temporary-file-directory)
  16875. (texfilebase (make-temp-name
  16876. (expand-file-name "orgtex" tmpdir)))
  16877. (texfile (concat texfilebase ".tex"))
  16878. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16879. '(1.0 . 1.0)))
  16880. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16881. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16882. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16883. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16884. "Black"))
  16885. (bg (or (plist-get options (if buffer :background :html-background))
  16886. "Transparent"))
  16887. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16888. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16889. (dolist (program programs)
  16890. (org-check-external-command program error-message))
  16891. (if use-xcolor
  16892. (progn (if (eq fg 'default)
  16893. (setq fg (org-latex-color :foreground))
  16894. (setq fg (org-latex-color-format fg)))
  16895. (if (eq bg 'default)
  16896. (setq bg (org-latex-color :background))
  16897. (setq bg (org-latex-color-format
  16898. (if (string= bg "Transparent") "white" bg))))
  16899. (with-temp-file texfile
  16900. (insert latex-header)
  16901. (insert "\n\\begin{document}\n"
  16902. "\\definecolor{fg}{rgb}{" fg "}\n"
  16903. "\\definecolor{bg}{rgb}{" bg "}\n"
  16904. "\n\\pagecolor{bg}\n"
  16905. "\n{\\color{fg}\n"
  16906. string
  16907. "\n}\n"
  16908. "\n\\end{document}\n")))
  16909. (if (eq fg 'default)
  16910. (setq fg (org-dvipng-color :foreground))
  16911. (unless (string= fg "Transparent")
  16912. (setq fg (org-dvipng-color-format fg))))
  16913. (if (eq bg 'default)
  16914. (setq bg (org-dvipng-color :background))
  16915. (unless (string= bg "Transparent")
  16916. (setq bg (org-dvipng-color-format bg))))
  16917. (with-temp-file texfile
  16918. (insert latex-header)
  16919. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16920. (let* ((err-msg (format "Please adjust `%s' part of \
  16921. `org-preview-latex-process-alist'."
  16922. processing-type))
  16923. (image-input-file
  16924. (org-compile-file
  16925. texfile latex-compiler image-input-type err-msg log-buf))
  16926. (image-output-file
  16927. (org-compile-file
  16928. image-input-file image-converter image-output-type err-msg log-buf
  16929. `((?F . ,(shell-quote-argument fg))
  16930. (?B . ,(shell-quote-argument bg))
  16931. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16932. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16933. (copy-file image-output-file tofile 'replace)
  16934. (dolist (e post-clean)
  16935. (when (file-exists-p (concat texfilebase e))
  16936. (delete-file (concat texfilebase e))))
  16937. image-output-file)))
  16938. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16939. "Fill a LaTeX header template TPL.
  16940. In the template, the following place holders will be recognized:
  16941. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16942. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16943. [PACKAGES] \\usepackage statements for PKG
  16944. [NO-PACKAGES] do not include PKG
  16945. [EXTRA] the string EXTRA
  16946. [NO-EXTRA] do not include EXTRA
  16947. For backward compatibility, if both the positive and the negative place
  16948. holder is missing, the positive one (without the \"NO-\") will be
  16949. assumed to be present at the end of the template.
  16950. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16951. EXTRA is a string.
  16952. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16953. (let (rpl (end ""))
  16954. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16955. (setq rpl (if (or (match-end 1) (not def-pkg))
  16956. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16957. tpl (replace-match rpl t t tpl))
  16958. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16959. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16960. (setq rpl (if (or (match-end 1) (not pkg))
  16961. "" (org-latex-packages-to-string pkg snippets-p t))
  16962. tpl (replace-match rpl t t tpl))
  16963. (when pkg (setq end
  16964. (concat end "\n"
  16965. (org-latex-packages-to-string pkg snippets-p)))))
  16966. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16967. (setq rpl (if (or (match-end 1) (not extra))
  16968. "" (concat extra "\n"))
  16969. tpl (replace-match rpl t t tpl))
  16970. (when (and extra (string-match "\\S-" extra))
  16971. (setq end (concat end "\n" extra))))
  16972. (if (string-match "\\S-" end)
  16973. (concat tpl "\n" end)
  16974. tpl)))
  16975. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  16976. "Turn an alist of packages into a string with the \\usepackage macros."
  16977. (setq pkg (mapconcat (lambda(p)
  16978. (cond
  16979. ((stringp p) p)
  16980. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  16981. (format "%% Package %s omitted" (cadr p)))
  16982. ((equal "" (car p))
  16983. (format "\\usepackage{%s}" (cadr p)))
  16984. (t
  16985. (format "\\usepackage[%s]{%s}"
  16986. (car p) (cadr p)))))
  16987. pkg
  16988. "\n"))
  16989. (if newline (concat pkg "\n") pkg))
  16990. (defun org-dvipng-color (attr)
  16991. "Return a RGB color specification for dvipng."
  16992. (org-dvipng-color-format (face-attribute 'default attr nil)))
  16993. (defun org-dvipng-color-format (color-name)
  16994. "Convert COLOR-NAME to a RGB color value for dvipng."
  16995. (apply #'format "rgb %s %s %s"
  16996. (mapcar 'org-normalize-color
  16997. (color-values color-name))))
  16998. (defun org-latex-color (attr)
  16999. "Return a RGB color for the LaTeX color package."
  17000. (org-latex-color-format (face-attribute 'default attr nil)))
  17001. (defun org-latex-color-format (color-name)
  17002. "Convert COLOR-NAME to a RGB color value."
  17003. (apply #'format "%s,%s,%s"
  17004. (mapcar 'org-normalize-color
  17005. (color-values color-name))))
  17006. (defun org-normalize-color (value)
  17007. "Return string to be used as color value for an RGB component."
  17008. (format "%g" (/ value 65535.0)))
  17009. ;; Image display
  17010. (defvar-local org-inline-image-overlays nil)
  17011. (defun org-toggle-inline-images (&optional include-linked)
  17012. "Toggle the display of inline images.
  17013. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17014. (interactive "P")
  17015. (if org-inline-image-overlays
  17016. (progn
  17017. (org-remove-inline-images)
  17018. (when (called-interactively-p 'interactive)
  17019. (message "Inline image display turned off")))
  17020. (org-display-inline-images include-linked)
  17021. (when (called-interactively-p 'interactive)
  17022. (message (if org-inline-image-overlays
  17023. (format "%d images displayed inline"
  17024. (length org-inline-image-overlays))
  17025. "No images to display inline")))))
  17026. (defun org-redisplay-inline-images ()
  17027. "Refresh the display of inline images."
  17028. (interactive)
  17029. (if (not org-inline-image-overlays)
  17030. (org-toggle-inline-images)
  17031. (org-toggle-inline-images)
  17032. (org-toggle-inline-images)))
  17033. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17034. "Display inline images.
  17035. An inline image is a link which follows either of these
  17036. conventions:
  17037. 1. Its path is a file with an extension matching return value
  17038. from `image-file-name-regexp' and it has no contents.
  17039. 2. Its description consists in a single link of the previous
  17040. type.
  17041. When optional argument INCLUDE-LINKED is non-nil, also links with
  17042. a text description part will be inlined. This can be nice for
  17043. a quick look at those images, but it does not reflect what
  17044. exported files will look like.
  17045. When optional argument REFRESH is non-nil, refresh existing
  17046. images between BEG and END. This will create new image displays
  17047. only if necessary. BEG and END default to the buffer
  17048. boundaries."
  17049. (interactive "P")
  17050. (when (display-graphic-p)
  17051. (unless refresh
  17052. (org-remove-inline-images)
  17053. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17054. (org-with-wide-buffer
  17055. (goto-char (or beg (point-min)))
  17056. (let* ((case-fold-search t)
  17057. (file-extension-re (image-file-name-regexp))
  17058. (link-abbrevs (mapcar #'car
  17059. (append org-link-abbrev-alist-local
  17060. org-link-abbrev-alist)))
  17061. ;; Check absolute, relative file names and explicit
  17062. ;; "file:" links. Also check link abbreviations since
  17063. ;; some might expand to "file" links.
  17064. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17065. (if (not link-abbrevs) ""
  17066. (format "\\|\\(?:%s:\\)"
  17067. (regexp-opt link-abbrevs))))))
  17068. (while (re-search-forward file-types-re end t)
  17069. (let ((link (save-match-data (org-element-context))))
  17070. ;; Check if we're at an inline image, i.e., an image file
  17071. ;; link without a description (unless INCLUDE-LINKED is
  17072. ;; non-nil).
  17073. (when (and (equal "file" (org-element-property :type link))
  17074. (or include-linked
  17075. (null (org-element-contents link)))
  17076. (string-match-p file-extension-re
  17077. (org-element-property :path link)))
  17078. (let ((file (expand-file-name
  17079. (org-link-unescape
  17080. (org-element-property :path link)))))
  17081. (when (file-exists-p file)
  17082. (let ((width
  17083. ;; Apply `org-image-actual-width' specifications.
  17084. (cond
  17085. ((not (image-type-available-p 'imagemagick)) nil)
  17086. ((eq org-image-actual-width t) nil)
  17087. ((listp org-image-actual-width)
  17088. (or
  17089. ;; First try to find a width among
  17090. ;; attributes associated to the paragraph
  17091. ;; containing link.
  17092. (let ((paragraph
  17093. (let ((e link))
  17094. (while (and (setq e (org-element-property
  17095. :parent e))
  17096. (not (eq (org-element-type e)
  17097. 'paragraph))))
  17098. e)))
  17099. (when paragraph
  17100. (save-excursion
  17101. (goto-char (org-element-property :begin paragraph))
  17102. (when
  17103. (re-search-forward
  17104. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17105. (org-element-property
  17106. :post-affiliated paragraph)
  17107. t)
  17108. (string-to-number (match-string 1))))))
  17109. ;; Otherwise, fall-back to provided number.
  17110. (car org-image-actual-width)))
  17111. ((numberp org-image-actual-width)
  17112. org-image-actual-width)))
  17113. (old (get-char-property-and-overlay
  17114. (org-element-property :begin link)
  17115. 'org-image-overlay)))
  17116. (if (and (car-safe old) refresh)
  17117. (image-refresh (overlay-get (cdr old) 'display))
  17118. (let ((image (create-image file
  17119. (and width 'imagemagick)
  17120. nil
  17121. :width width)))
  17122. (when image
  17123. (let ((ov (make-overlay
  17124. (org-element-property :begin link)
  17125. (progn
  17126. (goto-char
  17127. (org-element-property :end link))
  17128. (skip-chars-backward " \t")
  17129. (point)))))
  17130. (overlay-put ov 'display image)
  17131. (overlay-put ov 'face 'default)
  17132. (overlay-put ov 'org-image-overlay t)
  17133. (overlay-put
  17134. ov 'modification-hooks
  17135. (list 'org-display-inline-remove-overlay))
  17136. (push ov org-inline-image-overlays)))))))))))))))
  17137. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17138. "Remove inline-display overlay if a corresponding region is modified."
  17139. (let ((inhibit-modification-hooks t))
  17140. (when (and ov after)
  17141. (delete ov org-inline-image-overlays)
  17142. (delete-overlay ov))))
  17143. (defun org-remove-inline-images ()
  17144. "Remove inline display of images."
  17145. (interactive)
  17146. (mapc #'delete-overlay org-inline-image-overlays)
  17147. (setq org-inline-image-overlays nil))
  17148. ;;; Key bindings
  17149. (defun org-remap (map &rest commands)
  17150. "In MAP, remap the functions given in COMMANDS.
  17151. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17152. (let (new old)
  17153. (while commands
  17154. (setq old (pop commands) new (pop commands))
  17155. (org-defkey map (vector 'remap old) new))))
  17156. ;;;; Outline functions that can be remapped in Org
  17157. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17158. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17159. (define-key org-mode-map [remap outline-forward-same-level]
  17160. #'org-forward-heading-same-level)
  17161. (define-key org-mode-map [remap outline-backward-same-level]
  17162. #'org-backward-heading-same-level)
  17163. (define-key org-mode-map [remap outline-show-branches]
  17164. #'org-kill-note-or-show-branches)
  17165. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17166. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17167. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17168. (define-key org-mode-map [remap outline-next-visible-heading]
  17169. #'org-next-visible-heading)
  17170. (define-key org-mode-map [remap outline-previous-visible-heading]
  17171. #'org-previous-visible-heading)
  17172. (define-key org-mode-map [remap show-children] #'org-show-children)
  17173. ;;;; Make `C-c C-x' a prefix key
  17174. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17175. ;;;; TAB key with modifiers
  17176. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17177. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17178. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17179. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17180. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17181. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17182. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17183. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17184. ;;;; RET key with modifiers
  17185. (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
  17186. (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
  17187. (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
  17188. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17189. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17190. ;;;; Cursor keys with modifiers
  17191. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17192. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17193. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17194. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17195. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17196. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17197. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17198. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17199. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17200. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17201. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17202. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17203. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17204. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17205. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17206. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17207. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17208. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17209. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17210. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17211. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17212. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17213. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17214. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17215. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17216. ;;;; Babel keys
  17217. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17218. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17219. (define-key org-babel-map key def))
  17220. ;;;; Extra keys for TTY access.
  17221. ;; We only set them when really needed because otherwise the
  17222. ;; menus don't show the simple keys
  17223. (when (or org-use-extra-keys (not window-system))
  17224. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17225. (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
  17226. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17227. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17228. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17229. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17230. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17231. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17232. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17233. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17234. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17235. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17236. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17237. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17238. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17239. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17240. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17241. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17242. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17243. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17244. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17245. ;;;; Narrow map
  17246. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17247. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17248. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17249. ;;;; Remap usual Emacs bindings
  17250. (org-remap org-mode-map
  17251. 'self-insert-command 'org-self-insert-command
  17252. 'delete-char 'org-delete-char
  17253. 'delete-backward-char 'org-delete-backward-char
  17254. 'kill-line 'org-kill-line
  17255. 'open-line 'org-open-line
  17256. 'yank 'org-yank
  17257. 'comment-dwim 'org-comment-dwim
  17258. 'move-beginning-of-line 'org-beginning-of-line
  17259. 'move-end-of-line 'org-end-of-line
  17260. 'forward-paragraph 'org-forward-paragraph
  17261. 'backward-paragraph 'org-backward-paragraph
  17262. 'backward-sentence 'org-backward-sentence
  17263. 'forward-sentence 'org-forward-sentence
  17264. 'fill-paragraph 'org-fill-paragraph
  17265. 'delete-indentation 'org-delete-indentation
  17266. 'transpose-words 'org-transpose-words)
  17267. ;;;; All the other keys
  17268. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17269. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17270. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17271. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17272. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17273. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17274. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17275. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17276. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17277. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17278. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17279. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17280. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17281. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17282. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17283. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17284. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17285. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17286. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17287. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17288. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17289. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17290. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17291. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17292. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17293. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17294. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17295. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17296. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17297. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17298. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17299. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17300. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17301. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17302. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17303. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17304. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17305. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17306. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17307. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17308. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17309. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17310. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17311. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17312. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17313. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17314. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17315. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17316. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17317. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17318. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17319. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17320. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17321. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17322. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17323. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17324. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17325. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17326. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17327. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17328. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17329. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17330. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17331. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17332. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17333. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17334. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17335. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17336. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17337. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17338. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17339. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17340. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17341. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17342. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17343. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17344. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17345. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17346. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17347. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17348. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17349. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17350. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17351. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17352. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17353. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17354. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17355. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17356. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17357. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17358. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17359. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17360. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17361. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17362. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17363. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17364. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17365. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17366. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17367. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17368. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17369. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17370. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17371. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17372. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17373. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17374. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17375. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17376. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17377. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17378. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17379. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17380. (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
  17381. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17382. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17383. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17384. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17385. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17386. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17387. (org-defkey org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17388. (org-defkey org-mode-map (kbd "C-c C-x !") #'org-reload)
  17389. (org-defkey org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17390. (org-defkey org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17391. (org-defkey org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17392. (org-defkey org-mode-map (kbd "C-c C-x I") #'org-info-find-node)
  17393. ;;; Speed commands
  17394. (defconst org-speed-commands-default
  17395. '(
  17396. ("Outline Navigation")
  17397. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17398. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17399. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17400. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17401. ("F" . org-next-block)
  17402. ("B" . org-previous-block)
  17403. ("u" . (org-speed-move-safe 'outline-up-heading))
  17404. ("j" . org-goto)
  17405. ("g" . (org-refile t))
  17406. ("Outline Visibility")
  17407. ("c" . org-cycle)
  17408. ("C" . org-shifttab)
  17409. (" " . org-display-outline-path)
  17410. ("s" . org-toggle-narrow-to-subtree)
  17411. ("k" . org-cut-subtree)
  17412. ("=" . org-columns)
  17413. ("Outline Structure Editing")
  17414. ("U" . org-metaup)
  17415. ("D" . org-metadown)
  17416. ("r" . org-metaright)
  17417. ("l" . org-metaleft)
  17418. ("R" . org-shiftmetaright)
  17419. ("L" . org-shiftmetaleft)
  17420. ("i" . (progn (forward-char 1) (call-interactively
  17421. 'org-insert-heading-respect-content)))
  17422. ("^" . org-sort)
  17423. ("w" . org-refile)
  17424. ("a" . org-archive-subtree-default-with-confirmation)
  17425. ("@" . org-mark-subtree)
  17426. ("#" . org-toggle-comment)
  17427. ("Clock Commands")
  17428. ("I" . org-clock-in)
  17429. ("O" . org-clock-out)
  17430. ("Meta Data Editing")
  17431. ("t" . org-todo)
  17432. ("," . (org-priority))
  17433. ("0" . (org-priority ?\ ))
  17434. ("1" . (org-priority ?A))
  17435. ("2" . (org-priority ?B))
  17436. ("3" . (org-priority ?C))
  17437. (":" . org-set-tags-command)
  17438. ("e" . org-set-effort)
  17439. ("E" . org-inc-effort)
  17440. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17441. (org-entry-put (point) "APPT_WARNTIME" m)))
  17442. ("Agenda Views etc")
  17443. ("v" . org-agenda)
  17444. ("/" . org-sparse-tree)
  17445. ("Misc")
  17446. ("o" . org-open-at-point)
  17447. ("?" . org-speed-command-help)
  17448. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17449. (">" . (org-agenda-remove-restriction-lock))
  17450. )
  17451. "The default speed commands.")
  17452. (defun org-print-speed-command (e)
  17453. (if (> (length (car e)) 1)
  17454. (progn
  17455. (princ "\n")
  17456. (princ (car e))
  17457. (princ "\n")
  17458. (princ (make-string (length (car e)) ?-))
  17459. (princ "\n"))
  17460. (princ (car e))
  17461. (princ " ")
  17462. (if (symbolp (cdr e))
  17463. (princ (symbol-name (cdr e)))
  17464. (prin1 (cdr e)))
  17465. (princ "\n")))
  17466. (defun org-speed-command-help ()
  17467. "Show the available speed commands."
  17468. (interactive)
  17469. (if (not org-use-speed-commands)
  17470. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17471. (with-output-to-temp-buffer "*Help*"
  17472. (princ "User-defined Speed commands\n===========================\n")
  17473. (mapc #'org-print-speed-command org-speed-commands-user)
  17474. (princ "\n")
  17475. (princ "Built-in Speed commands\n=======================\n")
  17476. (mapc #'org-print-speed-command org-speed-commands-default))
  17477. (with-current-buffer "*Help*"
  17478. (setq truncate-lines t))))
  17479. (defun org-speed-move-safe (cmd)
  17480. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17481. If not, return to the original position and throw an error."
  17482. (interactive)
  17483. (let ((pos (point)))
  17484. (call-interactively cmd)
  17485. (unless (and (bolp) (org-at-heading-p))
  17486. (goto-char pos)
  17487. (error "Boundary reached while executing %s" cmd))))
  17488. (defvar org-self-insert-command-undo-counter 0)
  17489. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17490. (defvar org-speed-command nil)
  17491. (defun org-speed-command-activate (keys)
  17492. "Hook for activating single-letter speed commands.
  17493. `org-speed-commands-default' specifies a minimal command set.
  17494. Use `org-speed-commands-user' for further customization."
  17495. (when (or (and (bolp) (looking-at org-outline-regexp))
  17496. (and (functionp org-use-speed-commands)
  17497. (funcall org-use-speed-commands)))
  17498. (cdr (assoc keys (append org-speed-commands-user
  17499. org-speed-commands-default)))))
  17500. (defun org-babel-speed-command-activate (keys)
  17501. "Hook for activating single-letter code block commands."
  17502. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17503. (cdr (assoc keys org-babel-key-bindings))))
  17504. (defcustom org-speed-command-hook
  17505. '(org-speed-command-activate org-babel-speed-command-activate)
  17506. "Hook for activating speed commands at strategic locations.
  17507. Hook functions are called in sequence until a valid handler is
  17508. found.
  17509. Each hook takes a single argument, a user-pressed command key
  17510. which is also a `self-insert-command' from the global map.
  17511. Within the hook, examine the cursor position and the command key
  17512. and return nil or a valid handler as appropriate. Handler could
  17513. be one of an interactive command, a function, or a form.
  17514. Set `org-use-speed-commands' to non-nil value to enable this
  17515. hook. The default setting is `org-speed-command-activate'."
  17516. :group 'org-structure
  17517. :version "24.1"
  17518. :type 'hook)
  17519. (defun org-self-insert-command (N)
  17520. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17521. If the cursor is in a table looking at whitespace, the whitespace is
  17522. overwritten, and the table is not marked as requiring realignment."
  17523. (interactive "p")
  17524. (org-check-before-invisible-edit 'insert)
  17525. (cond
  17526. ((and org-use-speed-commands
  17527. (let ((kv (this-command-keys-vector)))
  17528. (setq org-speed-command
  17529. (run-hook-with-args-until-success
  17530. 'org-speed-command-hook
  17531. (make-string 1 (aref kv (1- (length kv))))))))
  17532. (cond
  17533. ((commandp org-speed-command)
  17534. (setq this-command org-speed-command)
  17535. (call-interactively org-speed-command))
  17536. ((functionp org-speed-command)
  17537. (funcall org-speed-command))
  17538. ((and org-speed-command (listp org-speed-command))
  17539. (eval org-speed-command))
  17540. (t (let (org-use-speed-commands)
  17541. (call-interactively 'org-self-insert-command)))))
  17542. ((and
  17543. (= N 1)
  17544. (not (org-region-active-p))
  17545. (org-at-table-p)
  17546. (progn
  17547. ;; Check if we blank the field, and if that triggers align.
  17548. (and (featurep 'org-table)
  17549. org-table-auto-blank-field
  17550. (memq last-command
  17551. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17552. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17553. ;; Got extra space, this field does not determine
  17554. ;; column width.
  17555. (let (org-table-may-need-update) (org-table-blank-field))
  17556. ;; No extra space, this field may determine column
  17557. ;; width.
  17558. (org-table-blank-field)))
  17559. t)
  17560. (looking-at "[^|\n]* |"))
  17561. ;; There is room for insertion without re-aligning the table.
  17562. (self-insert-command N)
  17563. (org-table-with-shrunk-field
  17564. (save-excursion
  17565. (skip-chars-forward "^|")
  17566. ;; Do not delete last space, which is
  17567. ;; `org-table-separator-space', but the regular space before
  17568. ;; it.
  17569. (delete-region (- (point) 2) (1- (point))))))
  17570. (t
  17571. (setq org-table-may-need-update t)
  17572. (self-insert-command N)
  17573. (org-fix-tags-on-the-fly)
  17574. (when org-self-insert-cluster-for-undo
  17575. (if (not (eq last-command 'org-self-insert-command))
  17576. (setq org-self-insert-command-undo-counter 1)
  17577. (if (>= org-self-insert-command-undo-counter 20)
  17578. (setq org-self-insert-command-undo-counter 1)
  17579. (and (> org-self-insert-command-undo-counter 0)
  17580. buffer-undo-list (listp buffer-undo-list)
  17581. (not (cadr buffer-undo-list)) ; remove nil entry
  17582. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17583. (setq org-self-insert-command-undo-counter
  17584. (1+ org-self-insert-command-undo-counter))))))))
  17585. (defun org-check-before-invisible-edit (kind)
  17586. "Check is editing if kind KIND would be dangerous with invisible text around.
  17587. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17588. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17589. (when (and org-catch-invisible-edits
  17590. (or (not (boundp 'visible-mode)) (not visible-mode))
  17591. (or (get-char-property (point) 'invisible)
  17592. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17593. ;; OK, we need to take a closer look. Do not consider
  17594. ;; invisibility obtained through text properties (e.g., link
  17595. ;; fontification), as it cannot be toggled.
  17596. (let* ((invisible-at-point
  17597. (pcase (get-char-property-and-overlay (point) 'invisible)
  17598. (`(,_ . ,(and (pred overlayp) o)) o)))
  17599. ;; Assume that point cannot land in the middle of an
  17600. ;; overlay, or between two overlays.
  17601. (invisible-before-point
  17602. (and (not invisible-at-point)
  17603. (not (bobp))
  17604. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17605. (`(,_ . ,(and (pred overlayp) o)) o))))
  17606. (border-and-ok-direction
  17607. (or
  17608. ;; Check if we are acting predictably before invisible
  17609. ;; text.
  17610. (and invisible-at-point
  17611. (memq kind '(insert delete-backward)))
  17612. ;; Check if we are acting predictably after invisible text
  17613. ;; This works not well, and I have turned it off. It seems
  17614. ;; better to always show and stop after invisible text.
  17615. ;; (and (not invisible-at-point) invisible-before-point
  17616. ;; (memq kind '(insert delete)))
  17617. )))
  17618. (when (or invisible-at-point invisible-before-point)
  17619. (when (eq org-catch-invisible-edits 'error)
  17620. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17621. (if (and org-custom-properties-overlays
  17622. (y-or-n-p "Display invisible properties in this buffer? "))
  17623. (org-toggle-custom-properties-visibility)
  17624. ;; Make the area visible
  17625. (save-excursion
  17626. (when invisible-before-point
  17627. (goto-char
  17628. (previous-single-char-property-change (point) 'invisible)))
  17629. ;; Remove whatever overlay is currently making yet-to-be
  17630. ;; edited text invisible. Also remove nested invisibility
  17631. ;; related overlays.
  17632. (delete-overlay (or invisible-at-point invisible-before-point))
  17633. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17634. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17635. (`(,_ . ,(and (pred overlayp) o))
  17636. (delete-overlay o)
  17637. t)))))
  17638. (cond
  17639. ((eq org-catch-invisible-edits 'show)
  17640. ;; That's it, we do the edit after showing
  17641. (message
  17642. "Unfolding invisible region around point before editing")
  17643. (sit-for 1))
  17644. ((and (eq org-catch-invisible-edits 'smart)
  17645. border-and-ok-direction)
  17646. (message "Unfolding invisible region around point before editing"))
  17647. (t
  17648. ;; Don't do the edit, make the user repeat it in full visibility
  17649. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17650. (defun org-fix-tags-on-the-fly ()
  17651. "Align tags in headline at point.
  17652. Unlike `org-align-tags', this function does nothing if point is
  17653. either not currently on a tagged headline or on a tag."
  17654. (when (and (org-match-line org-tag-line-re)
  17655. (< (point) (match-beginning 1)))
  17656. (org-align-tags)))
  17657. (defun org-delete-backward-char (N)
  17658. "Like `delete-backward-char', insert whitespace at field end in tables.
  17659. When deleting backwards, in tables this function will insert whitespace in
  17660. front of the next \"|\" separator, to keep the table aligned. The table will
  17661. still be marked for re-alignment if the field did fill the entire column,
  17662. because, in this case the deletion might narrow the column."
  17663. (interactive "p")
  17664. (save-match-data
  17665. (org-check-before-invisible-edit 'delete-backward)
  17666. (if (and (= N 1)
  17667. (not overwrite-mode)
  17668. (not (org-region-active-p))
  17669. (not (eq (char-before) ?|))
  17670. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17671. (looking-at-p ".*?|")
  17672. (org-at-table-p))
  17673. (progn (forward-char -1) (org-delete-char 1))
  17674. (backward-delete-char N)
  17675. (org-fix-tags-on-the-fly))))
  17676. (defun org-delete-char (N)
  17677. "Like `delete-char', but insert whitespace at field end in tables.
  17678. When deleting characters, in tables this function will insert whitespace in
  17679. front of the next \"|\" separator, to keep the table aligned. The table will
  17680. still be marked for re-alignment if the field did fill the entire column,
  17681. because, in this case the deletion might narrow the column."
  17682. (interactive "p")
  17683. (save-match-data
  17684. (org-check-before-invisible-edit 'delete)
  17685. (cond
  17686. ((or (/= N 1)
  17687. (eq (char-after) ?|)
  17688. (save-excursion (skip-chars-backward " \t") (bolp))
  17689. (not (org-at-table-p)))
  17690. (delete-char N)
  17691. (org-fix-tags-on-the-fly))
  17692. ((looking-at ".\\(.*?\\)|")
  17693. (let* ((update? org-table-may-need-update)
  17694. (noalign (looking-at-p ".*? |")))
  17695. (delete-char 1)
  17696. (org-table-with-shrunk-field
  17697. (save-excursion
  17698. ;; Last space is `org-table-separator-space', so insert
  17699. ;; a regular one before it instead.
  17700. (goto-char (- (match-end 0) 2))
  17701. (insert " ")))
  17702. ;; If there were two spaces at the end, this field does not
  17703. ;; determine the width of the column.
  17704. (when noalign (setq org-table-may-need-update update?))))
  17705. (t
  17706. (delete-char N)))))
  17707. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17708. (put 'org-self-insert-command 'delete-selection
  17709. (lambda ()
  17710. (not (run-hook-with-args-until-success
  17711. 'self-insert-uses-region-functions))))
  17712. (put 'orgtbl-self-insert-command 'delete-selection
  17713. (lambda ()
  17714. (not (run-hook-with-args-until-success
  17715. 'self-insert-uses-region-functions))))
  17716. (put 'org-delete-char 'delete-selection 'supersede)
  17717. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17718. (put 'org-yank 'delete-selection 'yank)
  17719. ;; Make `flyspell-mode' delay after some commands
  17720. (put 'org-self-insert-command 'flyspell-delayed t)
  17721. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17722. (put 'org-delete-char 'flyspell-delayed t)
  17723. (put 'org-delete-backward-char 'flyspell-delayed t)
  17724. ;; Make pabbrev-mode expand after Org mode commands
  17725. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17726. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17727. (defun org-transpose-words ()
  17728. "Transpose words for Org.
  17729. This uses the `org-mode-transpose-word-syntax-table' syntax
  17730. table, which interprets characters in `org-emphasis-alist' as
  17731. word constituents."
  17732. (interactive)
  17733. (with-syntax-table org-mode-transpose-word-syntax-table
  17734. (call-interactively 'transpose-words)))
  17735. (defvar org-ctrl-c-ctrl-c-hook nil
  17736. "Hook for functions attaching themselves to `C-c C-c'.
  17737. This can be used to add additional functionality to the C-c C-c
  17738. key which executes context-dependent commands. This hook is run
  17739. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17740. run after the last test.
  17741. Each function will be called with no arguments. The function
  17742. must check if the context is appropriate for it to act. If yes,
  17743. it should do its thing and then return a non-nil value. If the
  17744. context is wrong, just do nothing and return nil.")
  17745. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17746. "Hook for functions attaching themselves to `C-c C-c'.
  17747. This can be used to add additional functionality to the C-c C-c
  17748. key which executes context-dependent commands. This hook is run
  17749. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17750. before the first test.
  17751. Each function will be called with no arguments. The function
  17752. must check if the context is appropriate for it to act. If yes,
  17753. it should do its thing and then return a non-nil value. If the
  17754. context is wrong, just do nothing and return nil.")
  17755. (defvar org-tab-first-hook nil
  17756. "Hook for functions to attach themselves to TAB.
  17757. See `org-ctrl-c-ctrl-c-hook' for more information.
  17758. This hook runs as the first action when TAB is pressed, even before
  17759. `org-cycle' messes around with the `outline-regexp' to cater for
  17760. inline tasks and plain list item folding.
  17761. If any function in this hook returns t, any other actions that
  17762. would have been caused by TAB (such as table field motion or visibility
  17763. cycling) will not occur.")
  17764. (defvar org-tab-after-check-for-table-hook nil
  17765. "Hook for functions to attach themselves to TAB.
  17766. See `org-ctrl-c-ctrl-c-hook' for more information.
  17767. This hook runs after it has been established that the cursor is not in a
  17768. table, but before checking if the cursor is in a headline or if global cycling
  17769. should be done.
  17770. If any function in this hook returns t, not other actions like visibility
  17771. cycling will be done.")
  17772. (defvar org-tab-after-check-for-cycling-hook nil
  17773. "Hook for functions to attach themselves to TAB.
  17774. See `org-ctrl-c-ctrl-c-hook' for more information.
  17775. This hook runs after it has been established that not table field motion and
  17776. not visibility should be done because of current context. This is probably
  17777. the place where a package like yasnippets can hook in.")
  17778. (defvar org-tab-before-tab-emulation-hook nil
  17779. "Hook for functions to attach themselves to TAB.
  17780. See `org-ctrl-c-ctrl-c-hook' for more information.
  17781. This hook runs after every other options for TAB have been exhausted, but
  17782. before indentation and \t insertion takes place.")
  17783. (defvar org-metaleft-hook nil
  17784. "Hook for functions attaching themselves to `M-left'.
  17785. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17786. (defvar org-metaright-hook nil
  17787. "Hook for functions attaching themselves to `M-right'.
  17788. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17789. (defvar org-metaup-hook nil
  17790. "Hook for functions attaching themselves to `M-up'.
  17791. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17792. (defvar org-metadown-hook nil
  17793. "Hook for functions attaching themselves to `M-down'.
  17794. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17795. (defvar org-shiftmetaleft-hook nil
  17796. "Hook for functions attaching themselves to `M-S-left'.
  17797. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17798. (defvar org-shiftmetaright-hook nil
  17799. "Hook for functions attaching themselves to `M-S-right'.
  17800. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17801. (defvar org-shiftmetaup-hook nil
  17802. "Hook for functions attaching themselves to `M-S-up'.
  17803. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17804. (defvar org-shiftmetadown-hook nil
  17805. "Hook for functions attaching themselves to `M-S-down'.
  17806. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17807. (defvar org-metareturn-hook nil
  17808. "Hook for functions attaching themselves to `M-RET'.
  17809. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17810. (defvar org-shiftup-hook nil
  17811. "Hook for functions attaching themselves to `S-up'.
  17812. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17813. (defvar org-shiftup-final-hook nil
  17814. "Hook for functions attaching themselves to `S-up'.
  17815. This one runs after all other options except shift-select have been excluded.
  17816. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17817. (defvar org-shiftdown-hook nil
  17818. "Hook for functions attaching themselves to `S-down'.
  17819. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17820. (defvar org-shiftdown-final-hook nil
  17821. "Hook for functions attaching themselves to `S-down'.
  17822. This one runs after all other options except shift-select have been excluded.
  17823. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17824. (defvar org-shiftleft-hook nil
  17825. "Hook for functions attaching themselves to `S-left'.
  17826. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17827. (defvar org-shiftleft-final-hook nil
  17828. "Hook for functions attaching themselves to `S-left'.
  17829. This one runs after all other options except shift-select have been excluded.
  17830. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17831. (defvar org-shiftright-hook nil
  17832. "Hook for functions attaching themselves to `S-right'.
  17833. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17834. (defvar org-shiftright-final-hook nil
  17835. "Hook for functions attaching themselves to `S-right'.
  17836. This one runs after all other options except shift-select have been excluded.
  17837. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17838. (defun org-modifier-cursor-error ()
  17839. "Throw an error, a modified cursor command was applied in wrong context."
  17840. (user-error "This command is active in special context like tables, headlines or items"))
  17841. (defun org-shiftselect-error ()
  17842. "Throw an error because Shift-Cursor command was applied in wrong context."
  17843. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17844. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17845. (user-error "This command works only in special context like headlines or timestamps")))
  17846. (defun org-call-for-shift-select (cmd)
  17847. (let ((this-command-keys-shift-translated t))
  17848. (call-interactively cmd)))
  17849. (defun org-shifttab (&optional arg)
  17850. "Global visibility cycling or move to previous table field.
  17851. Call `org-table-previous-field' within a table.
  17852. When ARG is nil, cycle globally through visibility states.
  17853. When ARG is a numeric prefix, show contents of this level."
  17854. (interactive "P")
  17855. (cond
  17856. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17857. ((integerp arg)
  17858. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17859. (message "Content view to level: %d" arg)
  17860. (org-content (prefix-numeric-value arg2))
  17861. (org-cycle-show-empty-lines t)
  17862. (setq org-cycle-global-status 'overview)))
  17863. (t (call-interactively 'org-global-cycle))))
  17864. (defun org-shiftmetaleft ()
  17865. "Promote subtree or delete table column.
  17866. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17867. `org-table-delete-column', depending on context. See the
  17868. individual commands for more information."
  17869. (interactive)
  17870. (cond
  17871. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17872. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17873. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17874. ((if (not (org-region-active-p)) (org-at-item-p)
  17875. (save-excursion (goto-char (region-beginning))
  17876. (org-at-item-p)))
  17877. (call-interactively 'org-outdent-item-tree))
  17878. (t (org-modifier-cursor-error))))
  17879. (defun org-shiftmetaright ()
  17880. "Demote subtree or insert table column.
  17881. Calls `org-demote-subtree', `org-indent-item-tree', or
  17882. `org-table-insert-column', depending on context. See the
  17883. individual commands for more information."
  17884. (interactive)
  17885. (cond
  17886. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17887. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17888. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17889. ((if (not (org-region-active-p)) (org-at-item-p)
  17890. (save-excursion (goto-char (region-beginning))
  17891. (org-at-item-p)))
  17892. (call-interactively 'org-indent-item-tree))
  17893. (t (org-modifier-cursor-error))))
  17894. (defun org-shiftmetaup (&optional _arg)
  17895. "Drag the line at point up.
  17896. In a table, kill the current row.
  17897. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17898. but also adjust the previous clocked item in the clock history.
  17899. Everywhere else, drag the line at point up."
  17900. (interactive "P")
  17901. (cond
  17902. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17903. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17904. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17905. (call-interactively 'org-timestamp-up)))
  17906. (t (call-interactively 'org-drag-line-backward))))
  17907. (defun org-shiftmetadown (&optional _arg)
  17908. "Drag the line at point down.
  17909. In a table, insert an empty row at the current line.
  17910. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17911. but also adjust the previous clocked item in the clock history.
  17912. Everywhere else, drag the line at point down."
  17913. (interactive "P")
  17914. (cond
  17915. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17916. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17917. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17918. (call-interactively 'org-timestamp-down)))
  17919. (t (call-interactively 'org-drag-line-forward))))
  17920. (defsubst org-hidden-tree-error ()
  17921. (user-error
  17922. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17923. (defun org-metaleft (&optional _arg)
  17924. "Promote heading, list item at point or move table column left.
  17925. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17926. depending on context. With no specific context, calls the Emacs
  17927. default `backward-word'. See the individual commands for more
  17928. information.
  17929. This function runs the hook `org-metaleft-hook' as a first step,
  17930. and returns at first non-nil value."
  17931. (interactive "P")
  17932. (cond
  17933. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17934. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17935. ((org-with-limited-levels
  17936. (or (org-at-heading-p)
  17937. (and (org-region-active-p)
  17938. (save-excursion
  17939. (goto-char (region-beginning))
  17940. (org-at-heading-p)))))
  17941. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17942. (call-interactively 'org-do-promote))
  17943. ;; At an inline task.
  17944. ((org-at-heading-p)
  17945. (call-interactively 'org-inlinetask-promote))
  17946. ((or (org-at-item-p)
  17947. (and (org-region-active-p)
  17948. (save-excursion
  17949. (goto-char (region-beginning))
  17950. (org-at-item-p))))
  17951. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17952. (call-interactively 'org-outdent-item))
  17953. (t (call-interactively 'backward-word))))
  17954. (defun org-metaright (&optional _arg)
  17955. "Demote heading, list item at point or move table column right.
  17956. In front of a drawer or a block keyword, indent it correctly.
  17957. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17958. `org-indent-drawer' or `org-indent-block' depending on context.
  17959. With no specific context, calls the Emacs default `forward-word'.
  17960. See the individual commands for more information.
  17961. This function runs the hook `org-metaright-hook' as a first step,
  17962. and returns at first non-nil value."
  17963. (interactive "P")
  17964. (cond
  17965. ((run-hook-with-args-until-success 'org-metaright-hook))
  17966. ((org-at-table-p) (call-interactively 'org-table-move-column))
  17967. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  17968. ((org-at-block-p) (call-interactively 'org-indent-block))
  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-demote))
  17977. ;; At an inline task.
  17978. ((org-at-heading-p)
  17979. (call-interactively 'org-inlinetask-demote))
  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-indent-item))
  17987. (t (call-interactively 'forward-word))))
  17988. (defun org-check-for-hidden (what)
  17989. "Check if there are hidden headlines/items in the current visual line.
  17990. WHAT can be either `headlines' or `items'. If the current line is
  17991. an outline or item heading and it has a folded subtree below it,
  17992. this function returns t, nil otherwise."
  17993. (let ((re (cond
  17994. ((eq what 'headlines) org-outline-regexp-bol)
  17995. ((eq what 'items) (org-item-beginning-re))
  17996. (t (error "This should not happen"))))
  17997. beg end)
  17998. (save-excursion
  17999. (catch 'exit
  18000. (unless (org-region-active-p)
  18001. (setq beg (point-at-bol))
  18002. (beginning-of-line 2)
  18003. (while (and (not (eobp)) ;; this is like `next-line'
  18004. (get-char-property (1- (point)) 'invisible))
  18005. (beginning-of-line 2))
  18006. (setq end (point))
  18007. (goto-char beg)
  18008. (goto-char (point-at-eol))
  18009. (setq end (max end (point)))
  18010. (while (re-search-forward re end t)
  18011. (when (get-char-property (match-beginning 0) 'invisible)
  18012. (throw 'exit t))))
  18013. nil))))
  18014. (defun org-metaup (&optional _arg)
  18015. "Move subtree up or move table row up.
  18016. Calls `org-move-subtree-up' or `org-table-move-row' or
  18017. `org-move-item-up', depending on context. See the individual commands
  18018. for more information."
  18019. (interactive "P")
  18020. (cond
  18021. ((run-hook-with-args-until-success 'org-metaup-hook))
  18022. ((org-region-active-p)
  18023. (let* ((a (save-excursion
  18024. (goto-char (min (region-beginning) (region-end)))
  18025. (line-beginning-position)))
  18026. (b (save-excursion
  18027. (goto-char (max (region-beginning) (region-end)))
  18028. (if (bolp) (1- (point)) (line-end-position))))
  18029. (c (save-excursion
  18030. (goto-char a)
  18031. (move-beginning-of-line 0)
  18032. (point)))
  18033. (d (save-excursion
  18034. (goto-char a)
  18035. (move-end-of-line 0)
  18036. (point))))
  18037. (transpose-regions a b c d)
  18038. (goto-char c)))
  18039. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18040. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18041. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18042. (t (org-drag-element-backward))))
  18043. (defun org-metadown (&optional _arg)
  18044. "Move subtree down or move table row down.
  18045. Calls `org-move-subtree-down' or `org-table-move-row' or
  18046. `org-move-item-down', depending on context. See the individual
  18047. commands for more information."
  18048. (interactive "P")
  18049. (cond
  18050. ((run-hook-with-args-until-success 'org-metadown-hook))
  18051. ((org-region-active-p)
  18052. (let* ((a (save-excursion
  18053. (goto-char (min (region-beginning) (region-end)))
  18054. (line-beginning-position)))
  18055. (b (save-excursion
  18056. (goto-char (max (region-beginning) (region-end)))
  18057. (if (bolp) (1- (point)) (line-end-position))))
  18058. (c (save-excursion
  18059. (goto-char b)
  18060. (move-beginning-of-line (if (bolp) 1 2))
  18061. (point)))
  18062. (d (save-excursion
  18063. (goto-char b)
  18064. (move-end-of-line (if (bolp) 1 2))
  18065. (point))))
  18066. (transpose-regions a b c d)
  18067. (goto-char d)))
  18068. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18069. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18070. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18071. (t (org-drag-element-forward))))
  18072. (defun org-shiftup (&optional arg)
  18073. "Increase item in timestamp or increase priority of current headline.
  18074. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18075. depending on context. See the individual commands for more information."
  18076. (interactive "P")
  18077. (cond
  18078. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18079. ((and org-support-shift-select (org-region-active-p))
  18080. (org-call-for-shift-select 'previous-line))
  18081. ((org-at-timestamp-p 'lax)
  18082. (call-interactively (if org-edit-timestamp-down-means-later
  18083. 'org-timestamp-down 'org-timestamp-up)))
  18084. ((and (not (eq org-support-shift-select 'always))
  18085. org-enable-priority-commands
  18086. (org-at-heading-p))
  18087. (call-interactively 'org-priority-up))
  18088. ((and (not org-support-shift-select) (org-at-item-p))
  18089. (call-interactively 'org-previous-item))
  18090. ((org-clocktable-try-shift 'up arg))
  18091. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18092. (org-support-shift-select
  18093. (org-call-for-shift-select 'previous-line))
  18094. (t (org-shiftselect-error))))
  18095. (defun org-shiftdown (&optional arg)
  18096. "Decrease item in timestamp or decrease priority of current headline.
  18097. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18098. depending on context. See the individual commands for more information."
  18099. (interactive "P")
  18100. (cond
  18101. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18102. ((and org-support-shift-select (org-region-active-p))
  18103. (org-call-for-shift-select 'next-line))
  18104. ((org-at-timestamp-p 'lax)
  18105. (call-interactively (if org-edit-timestamp-down-means-later
  18106. 'org-timestamp-up 'org-timestamp-down)))
  18107. ((and (not (eq org-support-shift-select 'always))
  18108. org-enable-priority-commands
  18109. (org-at-heading-p))
  18110. (call-interactively 'org-priority-down))
  18111. ((and (not org-support-shift-select) (org-at-item-p))
  18112. (call-interactively 'org-next-item))
  18113. ((org-clocktable-try-shift 'down arg))
  18114. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18115. (org-support-shift-select
  18116. (org-call-for-shift-select 'next-line))
  18117. (t (org-shiftselect-error))))
  18118. (defun org-shiftright (&optional arg)
  18119. "Cycle the thing at point or in the current line, depending on context.
  18120. Depending on context, this does one of the following:
  18121. - switch a timestamp at point one day into the future
  18122. - on a headline, switch to the next TODO keyword.
  18123. - on an item, switch entire list to the next bullet type
  18124. - on a property line, switch to the next allowed value
  18125. - on a clocktable definition line, move time block into the future"
  18126. (interactive "P")
  18127. (cond
  18128. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18129. ((and org-support-shift-select (org-region-active-p))
  18130. (org-call-for-shift-select 'forward-char))
  18131. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18132. ((and (not (eq org-support-shift-select 'always))
  18133. (org-at-heading-p))
  18134. (let ((org-inhibit-logging
  18135. (not org-treat-S-cursor-todo-selection-as-state-change))
  18136. (org-inhibit-blocking
  18137. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18138. (org-call-with-arg 'org-todo 'right)))
  18139. ((or (and org-support-shift-select
  18140. (not (eq org-support-shift-select 'always))
  18141. (org-at-item-bullet-p))
  18142. (and (not org-support-shift-select) (org-at-item-p)))
  18143. (org-call-with-arg 'org-cycle-list-bullet nil))
  18144. ((and (not (eq org-support-shift-select 'always))
  18145. (org-at-property-p))
  18146. (call-interactively 'org-property-next-allowed-value))
  18147. ((org-clocktable-try-shift 'right arg))
  18148. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18149. (org-support-shift-select
  18150. (org-call-for-shift-select 'forward-char))
  18151. (t (org-shiftselect-error))))
  18152. (defun org-shiftleft (&optional arg)
  18153. "Cycle the thing at point or in the current line, depending on context.
  18154. Depending on context, this does one of the following:
  18155. - switch a timestamp at point one day into the past
  18156. - on a headline, switch to the previous TODO keyword.
  18157. - on an item, switch entire list to the previous bullet type
  18158. - on a property line, switch to the previous allowed value
  18159. - on a clocktable definition line, move time block into the past"
  18160. (interactive "P")
  18161. (cond
  18162. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18163. ((and org-support-shift-select (org-region-active-p))
  18164. (org-call-for-shift-select 'backward-char))
  18165. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18166. ((and (not (eq org-support-shift-select 'always))
  18167. (org-at-heading-p))
  18168. (let ((org-inhibit-logging
  18169. (not org-treat-S-cursor-todo-selection-as-state-change))
  18170. (org-inhibit-blocking
  18171. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18172. (org-call-with-arg 'org-todo 'left)))
  18173. ((or (and org-support-shift-select
  18174. (not (eq org-support-shift-select 'always))
  18175. (org-at-item-bullet-p))
  18176. (and (not org-support-shift-select) (org-at-item-p)))
  18177. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18178. ((and (not (eq org-support-shift-select 'always))
  18179. (org-at-property-p))
  18180. (call-interactively 'org-property-previous-allowed-value))
  18181. ((org-clocktable-try-shift 'left arg))
  18182. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18183. (org-support-shift-select
  18184. (org-call-for-shift-select 'backward-char))
  18185. (t (org-shiftselect-error))))
  18186. (defun org-shiftcontrolright ()
  18187. "Switch to next TODO set."
  18188. (interactive)
  18189. (cond
  18190. ((and org-support-shift-select (org-region-active-p))
  18191. (org-call-for-shift-select 'forward-word))
  18192. ((and (not (eq org-support-shift-select 'always))
  18193. (org-at-heading-p))
  18194. (org-call-with-arg 'org-todo 'nextset))
  18195. (org-support-shift-select
  18196. (org-call-for-shift-select 'forward-word))
  18197. (t (org-shiftselect-error))))
  18198. (defun org-shiftcontrolleft ()
  18199. "Switch to previous TODO set."
  18200. (interactive)
  18201. (cond
  18202. ((and org-support-shift-select (org-region-active-p))
  18203. (org-call-for-shift-select 'backward-word))
  18204. ((and (not (eq org-support-shift-select 'always))
  18205. (org-at-heading-p))
  18206. (org-call-with-arg 'org-todo 'previousset))
  18207. (org-support-shift-select
  18208. (org-call-for-shift-select 'backward-word))
  18209. (t (org-shiftselect-error))))
  18210. (defun org-shiftcontrolup (&optional n)
  18211. "Change timestamps synchronously up in CLOCK log lines.
  18212. Optional argument N tells to change by that many units."
  18213. (interactive "P")
  18214. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18215. (let (org-support-shift-select)
  18216. (org-clock-timestamps-up n))
  18217. (user-error "Not at a clock log")))
  18218. (defun org-shiftcontroldown (&optional n)
  18219. "Change timestamps synchronously down in CLOCK log lines.
  18220. Optional argument N tells to change by that many units."
  18221. (interactive "P")
  18222. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18223. (let (org-support-shift-select)
  18224. (org-clock-timestamps-down n))
  18225. (user-error "Not at a clock log")))
  18226. (defun org-increase-number-at-point (&optional inc)
  18227. "Increment the number at point.
  18228. With an optional prefix numeric argument INC, increment using
  18229. this numeric value."
  18230. (interactive "p")
  18231. (if (not (number-at-point))
  18232. (user-error "Not on a number")
  18233. (unless inc (setq inc 1))
  18234. (let ((pos (point))
  18235. (beg (skip-chars-backward "-+^/*0-9eE."))
  18236. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18237. (setq nap (buffer-substring-no-properties
  18238. (+ pos beg) (+ pos beg end)))
  18239. (delete-region (+ pos beg) (+ pos beg end))
  18240. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18241. (when (org-at-table-p)
  18242. (org-table-align)
  18243. (org-table-end-of-field 1))))
  18244. (defun org-decrease-number-at-point (&optional inc)
  18245. "Decrement the number at point.
  18246. With an optional prefix numeric argument INC, decrement using
  18247. this numeric value."
  18248. (interactive "p")
  18249. (org-increase-number-at-point (- (or inc 1))))
  18250. (defun org-ctrl-c-ret ()
  18251. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18252. (interactive)
  18253. (cond
  18254. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18255. (t (call-interactively 'org-insert-heading))))
  18256. (defun org-find-visible ()
  18257. (let ((s (point)))
  18258. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18259. (get-char-property s 'invisible)))
  18260. s))
  18261. (defun org-find-invisible ()
  18262. (let ((s (point)))
  18263. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18264. (not (get-char-property s 'invisible))))
  18265. s))
  18266. (defun org-copy-visible (beg end)
  18267. "Copy the visible parts of the region."
  18268. (interactive "r")
  18269. (let ((result ""))
  18270. (while (/= beg end)
  18271. (when (get-char-property beg 'invisible)
  18272. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18273. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18274. (setq result (concat result (buffer-substring beg next)))
  18275. (setq beg next)))
  18276. (setq deactivate-mark t)
  18277. (kill-new result)
  18278. (message "Visible strings have been copied to the kill ring.")))
  18279. (defun org-copy-special ()
  18280. "Copy region in table or copy current subtree.
  18281. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18282. context. See the individual commands for more information."
  18283. (interactive)
  18284. (call-interactively
  18285. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18286. (defun org-cut-special ()
  18287. "Cut region in table or cut current subtree.
  18288. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18289. context. See the individual commands for more information."
  18290. (interactive)
  18291. (call-interactively
  18292. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18293. (defun org-paste-special (arg)
  18294. "Paste rectangular region into table, or past subtree relative to level.
  18295. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18296. See the individual commands for more information."
  18297. (interactive "P")
  18298. (if (org-at-table-p)
  18299. (org-table-paste-rectangle)
  18300. (org-paste-subtree arg)))
  18301. (defun org-edit-special (&optional arg)
  18302. "Call a special editor for the element at point.
  18303. When at a table, call the formula editor with `org-table-edit-formulas'.
  18304. When in a source code block, call `org-edit-src-code'.
  18305. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18306. When in an export block, call `org-edit-export-block'.
  18307. When in a LaTeX environment, call `org-edit-latex-environment'.
  18308. When at an #+INCLUDE keyword, visit the included file.
  18309. When at a footnote reference, call `org-edit-footnote-reference'.
  18310. When at a planning line call, `org-deadline' and/or `org-schedule'.
  18311. When at an active timestamp, call `org-time-stamp'.
  18312. When at an inactive timestamp, call `org-time-stamp-inactive'.
  18313. On a link, call `ffap' to visit the link at point.
  18314. Otherwise, return a user error."
  18315. (interactive "P")
  18316. (let ((element (org-element-at-point)))
  18317. (barf-if-buffer-read-only)
  18318. (pcase (org-element-type element)
  18319. (`src-block
  18320. (if (not arg) (org-edit-src-code)
  18321. (let* ((info (org-babel-get-src-block-info))
  18322. (lang (nth 0 info))
  18323. (params (nth 2 info))
  18324. (session (cdr (assq :session params))))
  18325. (if (not session) (org-edit-src-code)
  18326. ;; At a source block with a session and function called
  18327. ;; with an ARG: switch to the buffer related to the
  18328. ;; inferior process.
  18329. (switch-to-buffer
  18330. (funcall (intern (concat "org-babel-prep-session:" lang))
  18331. session params))))))
  18332. (`keyword
  18333. (unless (member (org-element-property :key element)
  18334. '("INCLUDE" "SETUPFILE"))
  18335. (user-error "No special environment to edit here"))
  18336. (org-open-link-from-string
  18337. (format "[[%s]]"
  18338. (expand-file-name
  18339. (let ((value (org-strip-quotes
  18340. (org-element-property :value element))))
  18341. (cond
  18342. ((not (org-string-nw-p value))
  18343. (user-error "No file to edit"))
  18344. ((org-file-url-p value)
  18345. (user-error "Files located with a URL cannot be edited"))
  18346. (t value)))))))
  18347. (`table
  18348. (if (eq (org-element-property :type element) 'table.el)
  18349. (org-edit-table.el)
  18350. (call-interactively 'org-table-edit-formulas)))
  18351. ;; Only Org tables contain `table-row' type elements.
  18352. (`table-row (call-interactively 'org-table-edit-formulas))
  18353. (`example-block (org-edit-src-code))
  18354. (`export-block (org-edit-export-block))
  18355. (`fixed-width (org-edit-fixed-width-region))
  18356. (`latex-environment (org-edit-latex-environment))
  18357. (`planning
  18358. (let ((proplist (cadr element)))
  18359. (mapc #'call-interactively
  18360. (remq nil
  18361. (list
  18362. (when (plist-get proplist :deadline) #'org-deadline)
  18363. (when (plist-get proplist :scheduled) #'org-schedule))))))
  18364. (_
  18365. ;; No notable element at point. Though, we may be at a link or
  18366. ;; a footnote reference, which are objects. Thus, scan deeper.
  18367. (let ((context (org-element-context element)))
  18368. (pcase (org-element-type context)
  18369. (`footnote-reference (org-edit-footnote-reference))
  18370. (`inline-src-block (org-edit-inline-src-code))
  18371. (`timestamp (if (eq 'inactive (org-element-property :type context))
  18372. (call-interactively #'org-time-stamp-inactive)
  18373. (call-interactively #'org-time-stamp)))
  18374. (`link (call-interactively #'ffap))
  18375. (_ (user-error "No special environment to edit here"))))))))
  18376. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18377. (defun org-ctrl-c-ctrl-c (&optional arg)
  18378. "Set tags in headline, or update according to changed information at point.
  18379. This command does many different things, depending on context:
  18380. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18381. this is what we do.
  18382. - If the cursor is on a statistics cookie, update it.
  18383. - If the cursor is in a headline, prompt for tags and insert them
  18384. into the current line, aligned to `org-tags-column'. When called
  18385. with prefix arg, realign all tags in the current buffer.
  18386. - If the cursor is in one of the special #+KEYWORD lines, this
  18387. triggers scanning the buffer for these lines and updating the
  18388. information.
  18389. - If the cursor is inside a table, realign the table. This command
  18390. works even if the automatic table editor has been turned off.
  18391. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18392. the entire table.
  18393. - If the cursor is at a footnote reference or definition, jump to
  18394. the corresponding definition or references, respectively.
  18395. - If the cursor is a the beginning of a dynamic block, update it.
  18396. - If the current buffer is a capture buffer, close note and file it.
  18397. - If the cursor is on a <<<target>>>, update radio targets and
  18398. corresponding links in this buffer.
  18399. - If the cursor is on a numbered item in a plain list, renumber the
  18400. ordered list.
  18401. - If the cursor is on a checkbox, toggle it.
  18402. - If the cursor is on a code block, evaluate it. The variable
  18403. `org-confirm-babel-evaluate' can be used to control prompting
  18404. before code block evaluation, by default every code block
  18405. evaluation requires confirmation. Code block evaluation can be
  18406. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18407. (interactive "P")
  18408. (cond
  18409. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18410. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18411. (org-remove-occur-highlights)
  18412. (message "Temporary highlights/overlays removed from current buffer"))
  18413. ((and (local-variable-p 'org-finish-function)
  18414. (fboundp org-finish-function))
  18415. (funcall org-finish-function))
  18416. ((org-babel-hash-at-point))
  18417. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18418. (t
  18419. (let* ((context
  18420. (org-element-lineage
  18421. (org-element-context)
  18422. ;; Limit to supported contexts.
  18423. '(babel-call clock dynamic-block footnote-definition
  18424. footnote-reference inline-babel-call inline-src-block
  18425. inlinetask item keyword node-property paragraph
  18426. plain-list planning property-drawer radio-target
  18427. src-block statistics-cookie table table-cell table-row
  18428. timestamp)
  18429. t))
  18430. (type (org-element-type context)))
  18431. ;; For convenience: at the first line of a paragraph on the same
  18432. ;; line as an item, apply function on that item instead.
  18433. (when (eq type 'paragraph)
  18434. (let ((parent (org-element-property :parent context)))
  18435. (when (and (eq (org-element-type parent) 'item)
  18436. (= (line-beginning-position)
  18437. (org-element-property :begin parent)))
  18438. (setq context parent)
  18439. (setq type 'item))))
  18440. ;; Act according to type of element or object at point.
  18441. ;;
  18442. ;; Do nothing on a blank line, except if it is contained in
  18443. ;; a source block. Hence, we first check if point is in such
  18444. ;; a block and then if it is at a blank line.
  18445. (pcase type
  18446. ((or `inline-src-block `src-block)
  18447. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18448. (org-babel-eval-wipe-error-buffer)
  18449. (org-babel-execute-src-block
  18450. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18451. ((guard (org-match-line "[ \t]*$"))
  18452. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18453. (user-error
  18454. (substitute-command-keys
  18455. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18456. ((or `babel-call `inline-babel-call)
  18457. (let ((info (org-babel-lob-get-info context)))
  18458. (when info (org-babel-execute-src-block nil info))))
  18459. (`clock (org-clock-update-time-maybe))
  18460. (`dynamic-block
  18461. (save-excursion
  18462. (goto-char (org-element-property :post-affiliated context))
  18463. (org-update-dblock)))
  18464. (`footnote-definition
  18465. (goto-char (org-element-property :post-affiliated context))
  18466. (call-interactively 'org-footnote-action))
  18467. (`footnote-reference (call-interactively #'org-footnote-action))
  18468. ((or `headline `inlinetask)
  18469. (save-excursion (goto-char (org-element-property :begin context))
  18470. (call-interactively #'org-set-tags-command)))
  18471. (`item
  18472. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18473. ;; unconditionally, whereas `C-u' will toggle its presence.
  18474. ;; Without a universal argument, if the item has a checkbox,
  18475. ;; toggle it. Otherwise repair the list.
  18476. (let* ((box (org-element-property :checkbox context))
  18477. (struct (org-element-property :structure context))
  18478. (old-struct (copy-tree struct))
  18479. (parents (org-list-parents-alist struct))
  18480. (prevs (org-list-prevs-alist struct))
  18481. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18482. (org-list-set-checkbox
  18483. (org-element-property :begin context) struct
  18484. (cond ((equal arg '(16)) "[-]")
  18485. ((and (not box) (equal arg '(4))) "[ ]")
  18486. ((or (not box) (equal arg '(4))) nil)
  18487. ((eq box 'on) "[ ]")
  18488. (t "[X]")))
  18489. ;; Mimic `org-list-write-struct' but with grabbing a return
  18490. ;; value from `org-list-struct-fix-box'.
  18491. (org-list-struct-fix-ind struct parents 2)
  18492. (org-list-struct-fix-item-end struct)
  18493. (org-list-struct-fix-bul struct prevs)
  18494. (org-list-struct-fix-ind struct parents)
  18495. (let ((block-item
  18496. (org-list-struct-fix-box struct parents prevs orderedp)))
  18497. (if (and box (equal struct old-struct))
  18498. (if (equal arg '(16))
  18499. (message "Checkboxes already reset")
  18500. (user-error "Cannot toggle this checkbox: %s"
  18501. (if (eq box 'on)
  18502. "all subitems checked"
  18503. "unchecked subitems")))
  18504. (org-list-struct-apply-struct struct old-struct)
  18505. (org-update-checkbox-count-maybe))
  18506. (when block-item
  18507. (message "Checkboxes were removed due to empty box at line %d"
  18508. (org-current-line block-item))))))
  18509. (`keyword
  18510. (let ((org-inhibit-startup-visibility-stuff t)
  18511. (org-startup-align-all-tables nil))
  18512. (when (boundp 'org-table-coordinate-overlays)
  18513. (mapc #'delete-overlay org-table-coordinate-overlays)
  18514. (setq org-table-coordinate-overlays nil))
  18515. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18516. (message "Local setup has been refreshed"))
  18517. (`plain-list
  18518. ;; At a plain list, with a double C-u argument, set
  18519. ;; checkboxes of each item to "[-]", whereas a single one
  18520. ;; will toggle their presence according to the state of the
  18521. ;; first item in the list. Without an argument, repair the
  18522. ;; list.
  18523. (let* ((begin (org-element-property :contents-begin context))
  18524. (struct (org-element-property :structure context))
  18525. (old-struct (copy-tree struct))
  18526. (first-box (save-excursion
  18527. (goto-char begin)
  18528. (looking-at org-list-full-item-re)
  18529. (match-string-no-properties 3)))
  18530. (new-box (cond ((equal arg '(16)) "[-]")
  18531. ((equal arg '(4)) (unless first-box "[ ]"))
  18532. ((equal first-box "[X]") "[ ]")
  18533. (t "[X]"))))
  18534. (cond
  18535. (arg
  18536. (dolist (pos
  18537. (org-list-get-all-items
  18538. begin struct (org-list-prevs-alist struct)))
  18539. (org-list-set-checkbox pos struct new-box)))
  18540. ((and first-box (eq (point) begin))
  18541. ;; For convenience, when point is at bol on the first
  18542. ;; item of the list and no argument is provided, simply
  18543. ;; toggle checkbox of that item, if any.
  18544. (org-list-set-checkbox begin struct new-box)))
  18545. (when (equal
  18546. (org-list-write-struct
  18547. struct (org-list-parents-alist struct) old-struct)
  18548. old-struct)
  18549. (message "Cannot update this checkbox"))
  18550. (org-update-checkbox-count-maybe)))
  18551. ((or `property-drawer `node-property)
  18552. (call-interactively #'org-property-action))
  18553. (`radio-target
  18554. (call-interactively #'org-update-radio-target-regexp))
  18555. (`statistics-cookie
  18556. (call-interactively #'org-update-statistics-cookies))
  18557. ((or `table `table-cell `table-row)
  18558. ;; At a table, recalculate every field and align it. Also
  18559. ;; send the table if necessary. If the table has
  18560. ;; a `table.el' type, just give up. At a table row or cell,
  18561. ;; maybe recalculate line but always align table.
  18562. (if (eq (org-element-property :type context) 'table.el)
  18563. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18564. Use `\\[org-edit-special]' to edit table.el tables"))
  18565. (if (or (eq type 'table)
  18566. ;; Check if point is at a TBLFM line.
  18567. (and (eq type 'table-row)
  18568. (= (point) (org-element-property :end context))))
  18569. (save-excursion
  18570. (if (org-at-TBLFM-p)
  18571. (progn (require 'org-table)
  18572. (org-table-calc-current-TBLFM))
  18573. (goto-char (org-element-property :contents-begin context))
  18574. (org-call-with-arg 'org-table-recalculate (or arg t))
  18575. (orgtbl-send-table 'maybe)))
  18576. (org-table-maybe-eval-formula)
  18577. (cond (arg (call-interactively #'org-table-recalculate))
  18578. ((org-table-maybe-recalculate-line))
  18579. (t (org-table-align))))))
  18580. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18581. (org-timestamp-change 0 'day))
  18582. ((and `nil (guard (org-at-heading-p)))
  18583. ;; When point is on an unsupported object type, we can miss
  18584. ;; the fact that it also is at a heading. Handle it here.
  18585. (call-interactively #'org-set-tags-command))
  18586. ((guard
  18587. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18588. (_
  18589. (user-error
  18590. (substitute-command-keys
  18591. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18592. (defun org-mode-restart ()
  18593. (interactive)
  18594. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18595. (funcall major-mode)
  18596. (hack-local-variables)
  18597. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18598. (org-indent-mode -1))
  18599. (org-reset-file-cache))
  18600. (message "%s restarted" major-mode))
  18601. (defun org-kill-note-or-show-branches ()
  18602. "Abort storing current note, or call `outline-show-branches'."
  18603. (interactive)
  18604. (if (not org-finish-function)
  18605. (save-excursion
  18606. (save-restriction
  18607. (org-narrow-to-subtree)
  18608. (org-flag-subtree t)
  18609. (call-interactively 'outline-show-branches)
  18610. (org-hide-archived-subtrees (point-min) (point-max))))
  18611. (let ((org-note-abort t))
  18612. (funcall org-finish-function))))
  18613. (defun org-delete-indentation (&optional arg)
  18614. "Join current line to previous and fix whitespace at join.
  18615. If previous line is a headline add to headline title. Otherwise
  18616. the function calls `delete-indentation'.
  18617. With a non-nil optional argument, join it to the following one."
  18618. (interactive "*P")
  18619. (if (save-excursion
  18620. (beginning-of-line (if arg 1 0))
  18621. (let ((case-fold-search nil))
  18622. (looking-at org-complex-heading-regexp)))
  18623. ;; At headline.
  18624. (let ((tags-column (when (match-beginning 5)
  18625. (save-excursion (goto-char (match-beginning 5))
  18626. (current-column))))
  18627. (string (concat " " (progn (when arg (forward-line 1))
  18628. (org-trim (delete-and-extract-region
  18629. (line-beginning-position)
  18630. (line-end-position)))))))
  18631. (unless (bobp) (delete-region (point) (1- (point))))
  18632. (goto-char (or (match-end 4)
  18633. (match-beginning 5)
  18634. (match-end 0)))
  18635. (skip-chars-backward " \t")
  18636. (save-excursion (insert string))
  18637. ;; Adjust alignment of tags.
  18638. (cond
  18639. ((not tags-column)) ;no tags
  18640. (org-auto-align-tags (org-align-tags))
  18641. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18642. (delete-indentation arg)))
  18643. (defun org-open-line (n)
  18644. "Insert a new row in tables, call `open-line' elsewhere.
  18645. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18646. As a special case, when a document starts with a table, allow to
  18647. call `open-line' on the very first character."
  18648. (interactive "*p")
  18649. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18650. (org-table-insert-row)
  18651. (open-line n)))
  18652. (defun org-return (&optional indent)
  18653. "Goto next table row or insert a newline.
  18654. Calls `org-table-next-row' or `newline', depending on context.
  18655. When optional INDENT argument is non-nil, call
  18656. `newline-and-indent' instead of `newline'.
  18657. When `org-return-follows-link' is non-nil and point is on
  18658. a timestamp or a link, call `org-open-at-point'. However, it
  18659. will not happen if point is in a table or on a \"dead\"
  18660. object (e.g., within a comment). In these case, you need to use
  18661. `org-open-at-point' directly."
  18662. (interactive)
  18663. (let ((context (if org-return-follows-link (org-element-context)
  18664. (org-element-at-point))))
  18665. (cond
  18666. ;; In a table, call `org-table-next-row'. However, before first
  18667. ;; column or after last one, split the table.
  18668. ((or (and (eq (org-element-type context) 'table)
  18669. (>= (point) (org-element-property :contents-begin context))
  18670. (< (point) (org-element-property :contents-end context)))
  18671. (org-element-lineage context '(table-row table-cell) t))
  18672. (if (or (looking-at-p "[ \t]*$")
  18673. (save-excursion (skip-chars-backward " \t") (bolp)))
  18674. (insert "\n")
  18675. (org-table-justify-field-maybe)
  18676. (call-interactively #'org-table-next-row)))
  18677. ;; On a link or a timestamp, call `org-open-at-point' if
  18678. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18679. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18680. ((and org-return-follows-link
  18681. (or (and (eq 'link (org-element-type context))
  18682. ;; Ensure point is not on the white spaces after
  18683. ;; the link.
  18684. (let ((origin (point)))
  18685. (org-with-point-at (org-element-property :end context)
  18686. (skip-chars-backward " \t")
  18687. (> (point) origin))))
  18688. (org-in-regexp org-ts-regexp-both nil t)
  18689. (org-in-regexp org-tsr-regexp-both nil t)
  18690. (org-in-regexp org-any-link-re nil t)))
  18691. (call-interactively #'org-open-at-point))
  18692. ;; Insert newline in heading, but preserve tags.
  18693. ((and (not (bolp))
  18694. (save-excursion (beginning-of-line)
  18695. (let ((case-fold-search nil))
  18696. (looking-at org-complex-heading-regexp))))
  18697. ;; At headline. Split line. However, if point is on keyword,
  18698. ;; priority cookie or tags, do not break any of them: add
  18699. ;; a newline after the headline instead.
  18700. (let ((tags-column (and (match-beginning 5)
  18701. (save-excursion (goto-char (match-beginning 5))
  18702. (current-column))))
  18703. (string
  18704. (when (and (match-end 4) (org-point-in-group (point) 4))
  18705. (delete-and-extract-region (point) (match-end 4)))))
  18706. ;; Adjust tag alignment.
  18707. (cond
  18708. ((not (and tags-column string)))
  18709. (org-auto-align-tags (org-align-tags))
  18710. (t (org--align-tags-here tags-column))) ;preserve tags column
  18711. (end-of-line)
  18712. (org-show-entry)
  18713. (if indent (newline-and-indent) (newline))
  18714. (when string (save-excursion (insert (org-trim string))))))
  18715. ;; In a list, make sure indenting keeps trailing text within.
  18716. ((and indent
  18717. (not (eolp))
  18718. (org-element-lineage context '(item)))
  18719. (let ((trailing-data
  18720. (delete-and-extract-region (point) (line-end-position))))
  18721. (newline-and-indent)
  18722. (save-excursion (insert trailing-data))))
  18723. (t
  18724. ;; Do not auto-fill when point is in an Org property drawer.
  18725. (let ((auto-fill-function (and (not (org-at-property-p))
  18726. auto-fill-function)))
  18727. (if indent
  18728. (newline-and-indent)
  18729. (newline)))))))
  18730. (defun org-return-indent ()
  18731. "Goto next table row or insert a newline and indent.
  18732. Calls `org-table-next-row' or `newline-and-indent', depending on
  18733. context. See the individual commands for more information."
  18734. (interactive)
  18735. (org-return t))
  18736. (defun org-ctrl-c-tab (&optional _arg)
  18737. "Toggle columns width in a table, or show children.
  18738. Call `org-table-toggle-column-width' if point is in a table.
  18739. Otherwise, call `org-show-children'."
  18740. (interactive "p")
  18741. (call-interactively
  18742. (if (org-at-table-p) #'org-table-toggle-column-width
  18743. #'org-show-children)))
  18744. (defun org-ctrl-c-star ()
  18745. "Compute table, or change heading status of lines.
  18746. Calls `org-table-recalculate' or `org-toggle-heading',
  18747. depending on context."
  18748. (interactive)
  18749. (cond
  18750. ((org-at-table-p)
  18751. (call-interactively 'org-table-recalculate))
  18752. (t
  18753. ;; Convert all lines in region to list items
  18754. (call-interactively 'org-toggle-heading))))
  18755. (defun org-ctrl-c-minus ()
  18756. "Insert separator line in table or modify bullet status of line.
  18757. Also turns a plain line or a region of lines into list items.
  18758. Calls `org-table-insert-hline', `org-toggle-item', or
  18759. `org-cycle-list-bullet', depending on context."
  18760. (interactive)
  18761. (cond
  18762. ((org-at-table-p)
  18763. (call-interactively 'org-table-insert-hline))
  18764. ((org-region-active-p)
  18765. (call-interactively 'org-toggle-item))
  18766. ((org-in-item-p)
  18767. (call-interactively 'org-cycle-list-bullet))
  18768. (t
  18769. (call-interactively 'org-toggle-item))))
  18770. (defun org-toggle-heading (&optional nstars)
  18771. "Convert headings to normal text, or items or text to headings.
  18772. If there is no active region, only convert the current line.
  18773. With a `\\[universal-argument]' prefix, convert the whole list at
  18774. point into heading.
  18775. In a region:
  18776. - If the first non blank line is a headline, remove the stars
  18777. from all headlines in the region.
  18778. - If it is a normal line, turn each and every normal line (i.e.,
  18779. not an heading or an item) in the region into headings. If you
  18780. want to convert only the first line of this region, use one
  18781. universal prefix argument.
  18782. - If it is a plain list item, turn all plain list items into headings.
  18783. When converting a line into a heading, the number of stars is chosen
  18784. such that the lines become children of the current entry. However,
  18785. when a numeric prefix argument is given, its value determines the
  18786. number of stars to add."
  18787. (interactive "P")
  18788. (let ((skip-blanks
  18789. (function
  18790. ;; Return beginning of first non-blank line, starting from
  18791. ;; line at POS.
  18792. (lambda (pos)
  18793. (save-excursion
  18794. (goto-char pos)
  18795. (while (org-at-comment-p) (forward-line))
  18796. (skip-chars-forward " \r\t\n")
  18797. (point-at-bol)))))
  18798. beg end toggled)
  18799. ;; Determine boundaries of changes. If a universal prefix has
  18800. ;; been given, put the list in a region. If region ends at a bol,
  18801. ;; do not consider the last line to be in the region.
  18802. (when (and current-prefix-arg (org-at-item-p))
  18803. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18804. (org-mark-element))
  18805. (if (org-region-active-p)
  18806. (setq beg (funcall skip-blanks (region-beginning))
  18807. end (copy-marker (save-excursion
  18808. (goto-char (region-end))
  18809. (if (bolp) (point) (point-at-eol)))))
  18810. (setq beg (funcall skip-blanks (point-at-bol))
  18811. end (copy-marker (point-at-eol))))
  18812. ;; Ensure inline tasks don't count as headings.
  18813. (org-with-limited-levels
  18814. (save-excursion
  18815. (goto-char beg)
  18816. (cond
  18817. ;; Case 1. Started at an heading: de-star headings.
  18818. ((org-at-heading-p)
  18819. (while (< (point) end)
  18820. (when (org-at-heading-p t)
  18821. (looking-at org-outline-regexp) (replace-match "")
  18822. (setq toggled t))
  18823. (forward-line)))
  18824. ;; Case 2. Started at an item: change items into headlines.
  18825. ;; One star will be added by `org-list-to-subtree'.
  18826. ((org-at-item-p)
  18827. (while (< (point) end)
  18828. (when (org-at-item-p)
  18829. ;; Pay attention to cases when region ends before list.
  18830. (let* ((struct (org-list-struct))
  18831. (list-end
  18832. (min (org-list-get-bottom-point struct) (1+ end))))
  18833. (save-restriction
  18834. (narrow-to-region (point) list-end)
  18835. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18836. (setq toggled t))
  18837. (forward-line)))
  18838. ;; Case 3. Started at normal text: make every line an heading,
  18839. ;; skipping headlines and items.
  18840. (t (let* ((stars
  18841. (make-string
  18842. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18843. (add-stars
  18844. (cond (nstars "") ; stars from prefix only
  18845. ((equal stars "") "*") ; before first heading
  18846. (org-odd-levels-only "**") ; inside heading, odd
  18847. (t "*"))) ; inside heading, oddeven
  18848. (rpl (concat stars add-stars " "))
  18849. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18850. (while (< (point) (if (equal nstars '(4)) lend end))
  18851. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18852. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18853. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18854. (forward-line)))))))
  18855. (unless toggled (message "Cannot toggle heading from here"))))
  18856. (defun org-meta-return (&optional arg)
  18857. "Insert a new heading or wrap a region in a table.
  18858. Calls `org-insert-heading', `org-insert-item' or
  18859. `org-table-wrap-region', depending on context. When called with
  18860. an argument, unconditionally call `org-insert-heading'."
  18861. (interactive "P")
  18862. (org-check-before-invisible-edit 'insert)
  18863. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18864. (call-interactively (cond (arg #'org-insert-heading)
  18865. ((org-at-table-p) #'org-table-wrap-region)
  18866. ((org-in-item-p) #'org-insert-item)
  18867. (t #'org-insert-heading)))))
  18868. ;;; Menu entries
  18869. (defsubst org-in-subtree-not-table-p ()
  18870. "Are we in a subtree and not in a table?"
  18871. (and (not (org-before-first-heading-p))
  18872. (not (org-at-table-p))))
  18873. ;; Define the Org mode menus
  18874. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18875. '("Tbl"
  18876. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18877. ["Next Field" org-cycle (org-at-table-p)]
  18878. ["Previous Field" org-shifttab (org-at-table-p)]
  18879. ["Next Row" org-return (org-at-table-p)]
  18880. "--"
  18881. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18882. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18883. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18884. "--"
  18885. ("Column"
  18886. ["Move Column Left" org-metaleft (org-at-table-p)]
  18887. ["Move Column Right" org-metaright (org-at-table-p)]
  18888. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18889. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18890. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18891. ("Row"
  18892. ["Move Row Up" org-metaup (org-at-table-p)]
  18893. ["Move Row Down" org-metadown (org-at-table-p)]
  18894. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18895. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18896. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18897. "--"
  18898. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18899. ("Rectangle"
  18900. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18901. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18902. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18903. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18904. "--"
  18905. ("Calculate"
  18906. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18907. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18908. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18909. "--"
  18910. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18911. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18912. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18913. "--"
  18914. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18915. "--"
  18916. ["Sum Column/Rectangle" org-table-sum
  18917. (or (org-at-table-p) (org-region-active-p))]
  18918. ["Which Column?" org-table-current-column (org-at-table-p)])
  18919. ["Debug Formulas"
  18920. org-table-toggle-formula-debugger
  18921. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18922. ["Show Col/Row Numbers"
  18923. org-table-toggle-coordinate-overlays
  18924. :style toggle
  18925. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18926. "--"
  18927. ["Create" org-table-create (not (org-at-table-p))]
  18928. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18929. ["Import from File" org-table-import (not (org-at-table-p))]
  18930. ["Export to File" org-table-export (org-at-table-p)]
  18931. "--"
  18932. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18933. "--"
  18934. ("Plot"
  18935. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18936. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18937. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18938. '("Org"
  18939. ("Show/Hide"
  18940. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18941. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18942. ["Sparse Tree..." org-sparse-tree t]
  18943. ["Reveal Context" org-reveal t]
  18944. ["Show All" org-show-all t]
  18945. "--"
  18946. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18947. "--"
  18948. ["New Heading" org-insert-heading t]
  18949. ("Navigate Headings"
  18950. ["Up" outline-up-heading t]
  18951. ["Next" outline-next-visible-heading t]
  18952. ["Previous" outline-previous-visible-heading t]
  18953. ["Next Same Level" outline-forward-same-level t]
  18954. ["Previous Same Level" outline-backward-same-level t]
  18955. "--"
  18956. ["Jump" org-goto t])
  18957. ("Edit Structure"
  18958. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18959. "--"
  18960. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18961. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18962. "--"
  18963. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18964. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18965. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18966. "--"
  18967. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18968. "--"
  18969. ["Copy visible text" org-copy-visible t]
  18970. "--"
  18971. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18972. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18973. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18974. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18975. "--"
  18976. ["Sort Region/Children" org-sort t]
  18977. "--"
  18978. ["Convert to odd levels" org-convert-to-odd-levels t]
  18979. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18980. ("Editing"
  18981. ["Emphasis..." org-emphasize t]
  18982. ["Edit Source Example" org-edit-special t]
  18983. "--"
  18984. ["Footnote new/jump" org-footnote-action t]
  18985. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18986. ("Archive"
  18987. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  18988. "--"
  18989. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  18990. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  18991. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  18992. )
  18993. "--"
  18994. ("Hyperlinks"
  18995. ["Store Link (Global)" org-store-link t]
  18996. ["Find existing link to here" org-occur-link-in-agenda-files t]
  18997. ["Insert Link" org-insert-link t]
  18998. ["Follow Link" org-open-at-point t]
  18999. "--"
  19000. ["Next link" org-next-link t]
  19001. ["Previous link" org-previous-link t]
  19002. "--"
  19003. ["Descriptive Links"
  19004. org-toggle-link-display
  19005. :style radio
  19006. :selected org-descriptive-links
  19007. ]
  19008. ["Literal Links"
  19009. org-toggle-link-display
  19010. :style radio
  19011. :selected (not org-descriptive-links)])
  19012. "--"
  19013. ("TODO Lists"
  19014. ["TODO/DONE/-" org-todo t]
  19015. ("Select keyword"
  19016. ["Next keyword" org-shiftright (org-at-heading-p)]
  19017. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19018. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19019. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19020. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19021. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19022. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19023. "--"
  19024. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19025. :selected org-enforce-todo-dependencies :style toggle :active t]
  19026. "Settings for tree at point"
  19027. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19028. :selected (org-entry-get nil "ORDERED")
  19029. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19030. ["Do Children parallel" org-toggle-ordered-property :style radio
  19031. :selected (not (org-entry-get nil "ORDERED"))
  19032. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19033. "--"
  19034. ["Set Priority" org-priority t]
  19035. ["Priority Up" org-shiftup t]
  19036. ["Priority Down" org-shiftdown t]
  19037. "--"
  19038. ["Get news from all feeds" org-feed-update-all t]
  19039. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19040. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19041. ("TAGS and Properties"
  19042. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19043. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19044. "--"
  19045. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19046. ["Column view of properties" org-columns t]
  19047. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19048. ("Dates and Scheduling"
  19049. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19050. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19051. ("Change Date"
  19052. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19053. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19054. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19055. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19056. ["Compute Time Range" org-evaluate-time-range t]
  19057. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19058. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19059. "--"
  19060. ["Custom time format" org-toggle-time-stamp-overlays
  19061. :style radio :selected org-display-custom-times]
  19062. "--"
  19063. ["Goto Calendar" org-goto-calendar t]
  19064. ["Date from Calendar" org-date-from-calendar t]
  19065. "--"
  19066. ["Start/Restart Timer" org-timer-start t]
  19067. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19068. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19069. ["Insert Timer String" org-timer t]
  19070. ["Insert Timer Item" org-timer-item t])
  19071. ("Logging work"
  19072. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19073. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19074. ["Clock out" org-clock-out t]
  19075. ["Clock cancel" org-clock-cancel t]
  19076. "--"
  19077. ["Mark as default task" org-clock-mark-default-task t]
  19078. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19079. ["Goto running clock" org-clock-goto t]
  19080. "--"
  19081. ["Display times" org-clock-display t]
  19082. ["Create clock table" org-clock-report t]
  19083. "--"
  19084. ["Record DONE time"
  19085. (progn (setq org-log-done (not org-log-done))
  19086. (message "Switching to %s will %s record a timestamp"
  19087. (car org-done-keywords)
  19088. (if org-log-done "automatically" "not")))
  19089. :style toggle :selected org-log-done])
  19090. "--"
  19091. ["Agenda Command..." org-agenda t]
  19092. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19093. ("File List for Agenda")
  19094. ("Special views current file"
  19095. ["TODO Tree" org-show-todo-tree t]
  19096. ["Check Deadlines" org-check-deadlines t]
  19097. ["Tags/Property tree" org-match-sparse-tree t])
  19098. "--"
  19099. ["Export/Publish..." org-export-dispatch t]
  19100. ("LaTeX"
  19101. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19102. :style toggle :selected org-cdlatex-mode]
  19103. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19104. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19105. ["Modify math symbol" org-cdlatex-math-modify
  19106. (org-inside-LaTeX-fragment-p)]
  19107. ["Insert citation" org-reftex-citation t])
  19108. "--"
  19109. ("MobileOrg"
  19110. ["Push Files and Views" org-mobile-push t]
  19111. ["Get Captured and Flagged" org-mobile-pull t]
  19112. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19113. "--"
  19114. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19115. "--"
  19116. ("Documentation"
  19117. ["Show Version" org-version t]
  19118. ["Info Documentation" org-info t]
  19119. ["Browse Org News" org-browse-news 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. (defun org-info (&optional node)
  19132. "Read documentation for Org in the info system.
  19133. With optional NODE, go directly to that node."
  19134. (interactive)
  19135. (info (format "(org)%s" (or node ""))))
  19136. (defun org-browse-news ()
  19137. "Browse the news for the latest major release."
  19138. (interactive)
  19139. (browse-url "https://orgmode.org/Changes.html"))
  19140. ;;;###autoload
  19141. (defun org-submit-bug-report ()
  19142. "Submit a bug report on Org via mail.
  19143. Don't hesitate to report any problems or inaccurate documentation.
  19144. If you don't have setup sending mail from (X)Emacs, please copy the
  19145. output buffer into your mail program, as it gives us important
  19146. information about your Org version and configuration."
  19147. (interactive)
  19148. (require 'reporter)
  19149. (defvar reporter-prompt-for-summary-p)
  19150. (org-load-modules-maybe)
  19151. (org-require-autoloaded-modules)
  19152. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19153. (reporter-submit-bug-report
  19154. "emacs-orgmode@gnu.org"
  19155. (org-version nil 'full)
  19156. (let (list)
  19157. (save-window-excursion
  19158. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19159. (delete-other-windows)
  19160. (erase-buffer)
  19161. (insert "You are about to submit a bug report to the Org mailing list.
  19162. We would like to add your full Org and Outline configuration to the
  19163. bug report. This greatly simplifies the work of the maintainer and
  19164. other experts on the mailing list.
  19165. HOWEVER, some variables you have customized may contain private
  19166. information. The names of customers, colleagues, or friends, might
  19167. appear in the form of file names, tags, todo states, or search strings.
  19168. If you answer yes to the prompt, you might want to check and remove
  19169. such private information before sending the email.")
  19170. (add-text-properties (point-min) (point-max) '(face org-warning))
  19171. (when (yes-or-no-p "Include your Org configuration ")
  19172. (mapatoms
  19173. (lambda (v)
  19174. (and (boundp v)
  19175. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19176. (or (and (symbol-value v)
  19177. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19178. (and
  19179. (get v 'custom-type) (get v 'standard-value)
  19180. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19181. (push v list)))))
  19182. (kill-buffer (get-buffer "*Warn about privacy*"))
  19183. list))
  19184. nil nil
  19185. "Remember to cover the basics, that is, what you expected to happen and
  19186. what in fact did happen. You don't know how to make a good report? See
  19187. https://orgmode.org/manual/Feedback.html#Feedback
  19188. Your bug report will be posted to the Org mailing list.
  19189. ------------------------------------------------------------------------")
  19190. (save-excursion
  19191. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19192. (replace-match "\\1Bug: \\3 [\\2]")))))
  19193. (defun org-install-agenda-files-menu ()
  19194. (let ((bl (buffer-list)))
  19195. (save-excursion
  19196. (while bl
  19197. (set-buffer (pop bl))
  19198. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19199. (when (derived-mode-p 'org-mode)
  19200. (easy-menu-change
  19201. '("Org") "File List for Agenda"
  19202. (append
  19203. (list
  19204. ["Edit File List" (org-edit-agenda-file-list) t]
  19205. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19206. ["Remove Current File from List" org-remove-file t]
  19207. ["Cycle through agenda files" org-cycle-agenda-files t]
  19208. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19209. "--")
  19210. (mapcar 'org-file-menu-entry
  19211. ;; Prevent initialization from failing.
  19212. (ignore-errors (org-agenda-files t)))))))))
  19213. ;;;; Documentation
  19214. (defun org-require-autoloaded-modules ()
  19215. (interactive)
  19216. (mapc #'require
  19217. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19218. org-table org-timer)))
  19219. ;;;###autoload
  19220. (defun org-reload (&optional uncompiled)
  19221. "Reload all Org Lisp files.
  19222. With prefix arg UNCOMPILED, load the uncompiled versions."
  19223. (interactive "P")
  19224. (require 'loadhist)
  19225. (let* ((org-dir (org-find-library-dir "org"))
  19226. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19227. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19228. (remove-re (format "\\`%s\\'"
  19229. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19230. (feats (delete-dups
  19231. (mapcar 'file-name-sans-extension
  19232. (mapcar 'file-name-nondirectory
  19233. (delq nil
  19234. (mapcar 'feature-file
  19235. features))))))
  19236. (lfeat (append
  19237. (sort
  19238. (setq feats
  19239. (delq nil (mapcar
  19240. (lambda (f)
  19241. (if (and (string-match feature-re f)
  19242. (not (string-match remove-re f)))
  19243. f nil))
  19244. feats)))
  19245. 'string-lessp)
  19246. (list "org-version" "org")))
  19247. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19248. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19249. load-uncore load-misses)
  19250. (setq load-misses
  19251. (delq 't
  19252. (mapcar (lambda (f)
  19253. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19254. (and (string= org-dir contrib-dir)
  19255. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19256. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19257. (add-to-list 'load-uncore f 'append)
  19258. 't)
  19259. f))
  19260. lfeat)))
  19261. (when load-uncore
  19262. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19263. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19264. (if load-misses
  19265. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19266. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19267. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19268. ;;;###autoload
  19269. (defun org-customize ()
  19270. "Call the customize function with org as argument."
  19271. (interactive)
  19272. (org-load-modules-maybe)
  19273. (org-require-autoloaded-modules)
  19274. (customize-browse 'org))
  19275. (defun org-create-customize-menu ()
  19276. "Create a full customization menu for Org mode, insert it into the menu."
  19277. (interactive)
  19278. (org-load-modules-maybe)
  19279. (org-require-autoloaded-modules)
  19280. (if (fboundp 'customize-menu-create)
  19281. (progn
  19282. (easy-menu-change
  19283. '("Org") "Customize"
  19284. `(["Browse Org group" org-customize t]
  19285. "--"
  19286. ,(customize-menu-create 'org)
  19287. ["Set" Custom-set t]
  19288. ["Save" Custom-save t]
  19289. ["Reset to Current" Custom-reset-current t]
  19290. ["Reset to Saved" Custom-reset-saved t]
  19291. ["Reset to Standard Settings" Custom-reset-standard t]))
  19292. (message "\"Org\"-menu now contains full customization menu"))
  19293. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19294. ;;;; Miscellaneous stuff
  19295. ;;; Generally useful functions
  19296. (defun org-link-display-format (s)
  19297. "Replace links in string S with their description.
  19298. If there is no description, use the link target."
  19299. (save-match-data
  19300. (replace-regexp-in-string
  19301. org-bracket-link-analytic-regexp
  19302. (lambda (m)
  19303. (if (match-end 5) (match-string 5 m)
  19304. (concat (match-string 1 m) (match-string 3 m))))
  19305. s nil t)))
  19306. (defun org-toggle-link-display ()
  19307. "Toggle the literal or descriptive display of links."
  19308. (interactive)
  19309. (if org-descriptive-links
  19310. (remove-from-invisibility-spec '(org-link))
  19311. (add-to-invisibility-spec '(org-link)))
  19312. (org-restart-font-lock)
  19313. (setq org-descriptive-links (not org-descriptive-links)))
  19314. (defun org-in-clocktable-p ()
  19315. "Check if the cursor is in a clocktable."
  19316. (let ((pos (point)) start)
  19317. (save-excursion
  19318. (end-of-line 1)
  19319. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19320. (setq start (match-beginning 0))
  19321. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19322. (>= (match-end 0) pos)
  19323. start))))
  19324. (defun org-in-verbatim-emphasis ()
  19325. (save-match-data
  19326. (and (org-in-regexp org-verbatim-re 2)
  19327. (>= (point) (match-beginning 3))
  19328. (<= (point) (match-end 4)))))
  19329. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19330. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19331. (if (and marker (marker-buffer marker)
  19332. (buffer-live-p (marker-buffer marker)))
  19333. (progn
  19334. (pop-to-buffer-same-window (marker-buffer marker))
  19335. (when (or (> marker (point-max)) (< marker (point-min)))
  19336. (widen))
  19337. (goto-char marker)
  19338. (org-show-context 'org-goto))
  19339. (if bookmark
  19340. (bookmark-jump bookmark)
  19341. (error "Cannot find location"))))
  19342. (defun org-quote-csv-field (s)
  19343. "Quote field for inclusion in CSV material."
  19344. (if (string-match "[\",]" s)
  19345. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19346. s))
  19347. (defun org-force-self-insert (N)
  19348. "Needed to enforce self-insert under remapping."
  19349. (interactive "p")
  19350. (self-insert-command N))
  19351. (defun org-fill-template (template alist)
  19352. "Find each %key of ALIST in TEMPLATE and replace it."
  19353. (let ((case-fold-search nil))
  19354. (dolist (entry (sort (copy-sequence alist)
  19355. (lambda (a b) (< (length (car a)) (length (car b))))))
  19356. (setq template
  19357. (replace-regexp-in-string
  19358. (concat "%" (regexp-quote (car entry)))
  19359. (or (cdr entry) "") template t t)))
  19360. template))
  19361. (defun org-quote-vert (s)
  19362. "Replace \"|\" with \"\\vert\"."
  19363. (while (string-match "|" s)
  19364. (setq s (replace-match "\\vert" t t s)))
  19365. s)
  19366. (defun org-uuidgen-p (s)
  19367. "Is S an ID created by UUIDGEN?"
  19368. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19369. (defun org-in-src-block-p (&optional inside)
  19370. "Whether point is in a code source block.
  19371. When INSIDE is non-nil, don't consider we are within a source
  19372. block when point is at #+BEGIN_SRC or #+END_SRC."
  19373. (let ((case-fold-search t))
  19374. (or (and (eq (get-char-property (point) 'src-block) t))
  19375. (and (not inside)
  19376. (save-match-data
  19377. (save-excursion
  19378. (beginning-of-line)
  19379. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19380. (defun org-context ()
  19381. "Return a list of contexts of the current cursor position.
  19382. If several contexts apply, all are returned.
  19383. Each context entry is a list with a symbol naming the context, and
  19384. two positions indicating start and end of the context. Possible
  19385. contexts are:
  19386. :headline anywhere in a headline
  19387. :headline-stars on the leading stars in a headline
  19388. :todo-keyword on a TODO keyword (including DONE) in a headline
  19389. :tags on the TAGS in a headline
  19390. :priority on the priority cookie in a headline
  19391. :item on the first line of a plain list item
  19392. :item-bullet on the bullet/number of a plain list item
  19393. :checkbox on the checkbox in a plain list item
  19394. :table in an Org table
  19395. :table-special on a special filed in a table
  19396. :table-table in a table.el table
  19397. :clocktable in a clocktable
  19398. :src-block in a source block
  19399. :link on a hyperlink
  19400. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19401. :target on a <<target>>
  19402. :radio-target on a <<<radio-target>>>
  19403. :latex-fragment on a LaTeX fragment
  19404. :latex-preview on a LaTeX fragment with overlaid preview image
  19405. This function expects the position to be visible because it uses font-lock
  19406. faces as a help to recognize the following contexts: :table-special, :link,
  19407. and :keyword."
  19408. (let* ((f (get-text-property (point) 'face))
  19409. (faces (if (listp f) f (list f)))
  19410. (case-fold-search t)
  19411. (p (point)) clist o)
  19412. ;; First the large context
  19413. (cond
  19414. ((org-at-heading-p t)
  19415. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19416. (when (progn
  19417. (beginning-of-line 1)
  19418. (looking-at org-todo-line-tags-regexp))
  19419. (push (org-point-in-group p 1 :headline-stars) clist)
  19420. (push (org-point-in-group p 2 :todo-keyword) clist)
  19421. (push (org-point-in-group p 4 :tags) clist))
  19422. (goto-char p)
  19423. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19424. (when (looking-at "\\[#[A-Z0-9]\\]")
  19425. (push (org-point-in-group p 0 :priority) clist)))
  19426. ((org-at-item-p)
  19427. (push (org-point-in-group p 2 :item-bullet) clist)
  19428. (push (list :item (point-at-bol)
  19429. (save-excursion (org-end-of-item) (point)))
  19430. clist)
  19431. (and (org-at-item-checkbox-p)
  19432. (push (org-point-in-group p 0 :checkbox) clist)))
  19433. ((org-at-table-p)
  19434. (push (list :table (org-table-begin) (org-table-end)) clist)
  19435. (when (memq 'org-formula faces)
  19436. (push (list :table-special
  19437. (previous-single-property-change p 'face)
  19438. (next-single-property-change p 'face)) clist)))
  19439. ((org-at-table-p 'any)
  19440. (push (list :table-table) clist)))
  19441. (goto-char p)
  19442. (let ((case-fold-search t))
  19443. ;; New the "medium" contexts: clocktables, source blocks
  19444. (cond ((org-in-clocktable-p)
  19445. (push (list :clocktable
  19446. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19447. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19448. (match-beginning 1))
  19449. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19450. (match-end 0))) clist))
  19451. ((org-in-src-block-p)
  19452. (push (list :src-block
  19453. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19454. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19455. (match-beginning 1))
  19456. (and (search-forward "#+END_SRC" nil t)
  19457. (match-beginning 0))) clist))))
  19458. (goto-char p)
  19459. ;; Now the small context
  19460. (cond
  19461. ((org-at-timestamp-p)
  19462. (push (org-point-in-group p 0 :timestamp) clist))
  19463. ((memq 'org-link faces)
  19464. (push (list :link
  19465. (previous-single-property-change p 'face)
  19466. (next-single-property-change p 'face)) clist))
  19467. ((memq 'org-special-keyword faces)
  19468. (push (list :keyword
  19469. (previous-single-property-change p 'face)
  19470. (next-single-property-change p 'face)) clist))
  19471. ((org-at-target-p)
  19472. (push (org-point-in-group p 0 :target) clist)
  19473. (goto-char (1- (match-beginning 0)))
  19474. (when (looking-at org-radio-target-regexp)
  19475. (push (org-point-in-group p 0 :radio-target) clist))
  19476. (goto-char p))
  19477. ((setq o (cl-some
  19478. (lambda (o)
  19479. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19480. o))
  19481. (overlays-at (point))))
  19482. (push (list :latex-fragment
  19483. (overlay-start o) (overlay-end o)) clist)
  19484. (push (list :latex-preview
  19485. (overlay-start o) (overlay-end o)) clist))
  19486. ((org-inside-LaTeX-fragment-p)
  19487. ;; FIXME: positions wrong.
  19488. (push (list :latex-fragment (point) (point)) clist)))
  19489. (setq clist (nreverse (delq nil clist)))
  19490. clist))
  19491. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19492. "Non-nil when point is between matches of START-RE and END-RE.
  19493. Also return a non-nil value when point is on one of the matches.
  19494. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19495. buffer positions. Default values are the positions of headlines
  19496. surrounding the point.
  19497. The functions returns a cons cell whose car (resp. cdr) is the
  19498. position before START-RE (resp. after END-RE)."
  19499. (save-match-data
  19500. (let ((pos (point))
  19501. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19502. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19503. beg end)
  19504. (save-excursion
  19505. ;; Point is on a block when on START-RE or if START-RE can be
  19506. ;; found before it...
  19507. (and (or (org-in-regexp start-re)
  19508. (re-search-backward start-re limit-up t))
  19509. (setq beg (match-beginning 0))
  19510. ;; ... and END-RE after it...
  19511. (goto-char (match-end 0))
  19512. (re-search-forward end-re limit-down t)
  19513. (> (setq end (match-end 0)) pos)
  19514. ;; ... without another START-RE in-between.
  19515. (goto-char (match-beginning 0))
  19516. (not (re-search-backward start-re (1+ beg) t))
  19517. ;; Return value.
  19518. (cons beg end))))))
  19519. (defun org-in-block-p (names)
  19520. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19521. NAMES is a list of strings containing names of blocks.
  19522. Return first block name matched, or nil. Beware that in case of
  19523. nested blocks, the returned name may not belong to the closest
  19524. block from point."
  19525. (save-match-data
  19526. (catch 'exit
  19527. (let ((case-fold-search t)
  19528. (lim-up (save-excursion (outline-previous-heading)))
  19529. (lim-down (save-excursion (outline-next-heading))))
  19530. (dolist (name names)
  19531. (let ((n (regexp-quote name)))
  19532. (when (org-between-regexps-p
  19533. (concat "^[ \t]*#\\+begin_" n)
  19534. (concat "^[ \t]*#\\+end_" n)
  19535. lim-up lim-down)
  19536. (throw 'exit n)))))
  19537. nil)))
  19538. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19539. "Call `multi-occur' with buffers for all agenda files."
  19540. (interactive "sOrg-files matching: ")
  19541. (let* ((files (org-agenda-files))
  19542. (tnames (mapcar #'file-truename files))
  19543. (extra org-agenda-text-search-extra-files))
  19544. (when (eq (car extra) 'agenda-archives)
  19545. (setq extra (cdr extra))
  19546. (setq files (org-add-archive-files files)))
  19547. (dolist (f extra)
  19548. (unless (member (file-truename f) tnames)
  19549. (unless (member f files) (setq files (append files (list f))))
  19550. (setq tnames (append tnames (list (file-truename f))))))
  19551. (multi-occur
  19552. (mapcar (lambda (x)
  19553. (with-current-buffer
  19554. ;; FIXME: Why not just (find-file-noselect x)?
  19555. ;; Is it to avoid the "revert buffer" prompt?
  19556. (or (get-file-buffer x) (find-file-noselect x))
  19557. (widen)
  19558. (current-buffer)))
  19559. files)
  19560. regexp)))
  19561. (add-hook 'occur-mode-find-occurrence-hook
  19562. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19563. (defun org-occur-link-in-agenda-files ()
  19564. "Create a link and search for it in the agendas.
  19565. The link is not stored in `org-stored-links', it is just created
  19566. for the search purpose."
  19567. (interactive)
  19568. (let ((link (condition-case nil
  19569. (org-store-link nil)
  19570. (error "Unable to create a link to here"))))
  19571. (org-occur-in-agenda-files (regexp-quote link))))
  19572. (defun org-back-over-empty-lines ()
  19573. "Move backwards over whitespace, to the beginning of the first empty line.
  19574. Returns the number of empty lines passed."
  19575. (let ((pos (point)))
  19576. (if (cdr (assq 'heading org-blank-before-new-entry))
  19577. (skip-chars-backward " \t\n\r")
  19578. (unless (eobp)
  19579. (forward-line -1)))
  19580. (beginning-of-line 2)
  19581. (goto-char (min (point) pos))
  19582. (count-lines (point) pos)))
  19583. (defun org-replace-escapes (string table)
  19584. "Replace %-escapes in STRING with values in TABLE.
  19585. TABLE is an association list with keys like \"%a\" and string values.
  19586. The sequences in STRING may contain normal field width and padding information,
  19587. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19588. so values can contain further %-escapes if they are define later in TABLE."
  19589. (let ((tbl (copy-alist table))
  19590. (case-fold-search nil)
  19591. (pchg 0)
  19592. re rpl)
  19593. (dolist (e tbl)
  19594. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19595. (when (and (cdr e) (string-match re (cdr e)))
  19596. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19597. (safe "SREF"))
  19598. (add-text-properties 0 3 (list 'sref sref) safe)
  19599. (setcdr e (replace-match safe t t (cdr e)))))
  19600. (while (string-match re string)
  19601. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19602. (cdr e)))
  19603. (setq string (replace-match rpl t t string))))
  19604. (while (setq pchg (next-property-change pchg string))
  19605. (let ((sref (get-text-property pchg 'sref string)))
  19606. (when (and sref (string-match "SREF" string pchg))
  19607. (setq string (replace-match sref t t string)))))
  19608. string))
  19609. ;;; TODO: Only called once, from ox-odt which should probably use
  19610. ;;; org-export-inline-image-p or something.
  19611. (defun org-file-image-p (file)
  19612. "Return non-nil if FILE is an image."
  19613. (save-match-data
  19614. (string-match (image-file-name-regexp) file)))
  19615. (defun org-get-cursor-date (&optional with-time)
  19616. "Return the date at cursor in as a time.
  19617. This works in the calendar and in the agenda, anywhere else it just
  19618. returns the current time.
  19619. If WITH-TIME is non-nil, returns the time of the event at point (in
  19620. the agenda) or the current time of the day."
  19621. (let (date day defd tp hod mod)
  19622. (when with-time
  19623. (setq tp (get-text-property (point) 'time))
  19624. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19625. (setq hod (string-to-number (match-string 1 tp))
  19626. mod (string-to-number (match-string 2 tp))))
  19627. (or tp (let ((now (decode-time)))
  19628. (setq hod (nth 2 now)
  19629. mod (nth 1 now)))))
  19630. (cond
  19631. ((eq major-mode 'calendar-mode)
  19632. (setq date (calendar-cursor-to-date)
  19633. defd (encode-time 0 (or mod 0) (or hod 0)
  19634. (nth 1 date) (nth 0 date) (nth 2 date))))
  19635. ((eq major-mode 'org-agenda-mode)
  19636. (setq day (get-text-property (point) 'day))
  19637. (when day
  19638. (setq date (calendar-gregorian-from-absolute day)
  19639. defd (encode-time 0 (or mod 0) (or hod 0)
  19640. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19641. (or defd (current-time))))
  19642. (defun org-mark-subtree (&optional up)
  19643. "Mark the current subtree.
  19644. This puts point at the start of the current subtree, and mark at
  19645. the end. If a numeric prefix UP is given, move up into the
  19646. hierarchy of headlines by UP levels before marking the subtree."
  19647. (interactive "P")
  19648. (org-with-limited-levels
  19649. (cond ((org-at-heading-p) (beginning-of-line))
  19650. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19651. (t (outline-previous-visible-heading 1))))
  19652. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19653. (if (called-interactively-p 'any)
  19654. (call-interactively 'org-mark-element)
  19655. (org-mark-element)))
  19656. ;;; Indentation
  19657. (defvar org-element-greater-elements)
  19658. (defun org--get-expected-indentation (element contentsp)
  19659. "Expected indentation column for current line, according to ELEMENT.
  19660. ELEMENT is an element containing point. CONTENTSP is non-nil
  19661. when indentation is to be computed according to contents of
  19662. ELEMENT."
  19663. (let ((type (org-element-type element))
  19664. (start (org-element-property :begin element))
  19665. (post-affiliated (org-element-property :post-affiliated element)))
  19666. (org-with-wide-buffer
  19667. (cond
  19668. (contentsp
  19669. (cl-case type
  19670. ((diary-sexp footnote-definition) 0)
  19671. ((headline inlinetask nil)
  19672. (if (not org-adapt-indentation) 0
  19673. (let ((level (org-current-level)))
  19674. (if level (1+ level) 0))))
  19675. ((item plain-list) (org-list-item-body-column post-affiliated))
  19676. (t
  19677. (goto-char start)
  19678. (current-indentation))))
  19679. ((memq type '(headline inlinetask nil))
  19680. (if (org-match-line "[ \t]*$")
  19681. (org--get-expected-indentation element t)
  19682. 0))
  19683. ((memq type '(diary-sexp footnote-definition)) 0)
  19684. ;; First paragraph of a footnote definition or an item.
  19685. ;; Indent like parent.
  19686. ((< (line-beginning-position) start)
  19687. (org--get-expected-indentation
  19688. (org-element-property :parent element) t))
  19689. ;; At first line: indent according to previous sibling, if any,
  19690. ;; ignoring footnote definitions and inline tasks, or parent's
  19691. ;; contents.
  19692. ((= (line-beginning-position) start)
  19693. (catch 'exit
  19694. (while t
  19695. (if (= (point-min) start) (throw 'exit 0)
  19696. (goto-char (1- start))
  19697. (let* ((previous (org-element-at-point))
  19698. (parent previous))
  19699. (while (and parent (<= (org-element-property :end parent) start))
  19700. (setq previous parent
  19701. parent (org-element-property :parent parent)))
  19702. (cond
  19703. ((not previous) (throw 'exit 0))
  19704. ((> (org-element-property :end previous) start)
  19705. (throw 'exit (org--get-expected-indentation previous t)))
  19706. ((memq (org-element-type previous)
  19707. '(footnote-definition inlinetask))
  19708. (setq start (org-element-property :begin previous)))
  19709. (t (goto-char (org-element-property :begin previous))
  19710. (throw 'exit
  19711. (if (bolp) (current-indentation)
  19712. ;; At first paragraph in an item or
  19713. ;; a footnote definition.
  19714. (org--get-expected-indentation
  19715. (org-element-property :parent previous) t))))))))))
  19716. ;; Otherwise, move to the first non-blank line above.
  19717. (t
  19718. (beginning-of-line)
  19719. (let ((pos (point)))
  19720. (skip-chars-backward " \r\t\n")
  19721. (cond
  19722. ;; Two blank lines end a footnote definition or a plain
  19723. ;; list. When we indent an empty line after them, the
  19724. ;; containing list or footnote definition is over, so it
  19725. ;; qualifies as a previous sibling. Therefore, we indent
  19726. ;; like its first line.
  19727. ((and (memq type '(footnote-definition plain-list))
  19728. (> (count-lines (point) pos) 2))
  19729. (goto-char start)
  19730. (current-indentation))
  19731. ;; Line above is the first one of a paragraph at the
  19732. ;; beginning of an item or a footnote definition. Indent
  19733. ;; like parent.
  19734. ((< (line-beginning-position) start)
  19735. (org--get-expected-indentation
  19736. (org-element-property :parent element) t))
  19737. ;; Line above is the beginning of an element, i.e., point
  19738. ;; was originally on the blank lines between element's start
  19739. ;; and contents.
  19740. ((= (line-beginning-position) post-affiliated)
  19741. (org--get-expected-indentation element t))
  19742. ;; POS is after contents in a greater element. Indent like
  19743. ;; the beginning of the element.
  19744. ((and (memq type org-element-greater-elements)
  19745. (let ((cend (org-element-property :contents-end element)))
  19746. (and cend (<= cend pos))))
  19747. ;; As a special case, if point is at the end of a footnote
  19748. ;; definition or an item, indent like the very last element
  19749. ;; within. If that last element is an item, indent like
  19750. ;; its contents.
  19751. (if (memq type '(footnote-definition item plain-list))
  19752. (let ((last (org-element-at-point)))
  19753. (goto-char pos)
  19754. (org--get-expected-indentation
  19755. last (eq (org-element-type last) 'item)))
  19756. (goto-char start)
  19757. (current-indentation)))
  19758. ;; In any other case, indent like the current line.
  19759. (t (current-indentation)))))))))
  19760. (defun org--align-node-property ()
  19761. "Align node property at point.
  19762. Alignment is done according to `org-property-format', which see."
  19763. (when (save-excursion
  19764. (beginning-of-line)
  19765. (looking-at org-property-re))
  19766. (replace-match
  19767. (concat (match-string 4)
  19768. (org-trim
  19769. (format org-property-format (match-string 1) (match-string 3))))
  19770. t t)))
  19771. (defun org-indent-line ()
  19772. "Indent line depending on context.
  19773. Indentation is done according to the following rules:
  19774. - Footnote definitions, diary sexps, headlines and inline tasks
  19775. have to start at column 0.
  19776. - On the very first line of an element, consider, in order, the
  19777. next rules until one matches:
  19778. 1. If there's a sibling element before, ignoring footnote
  19779. definitions and inline tasks, indent like its first line.
  19780. 2. If element has a parent, indent like its contents. More
  19781. precisely, if parent is an item, indent after the
  19782. description part, if any, or the bullet (see
  19783. `org-list-description-max-indent'). Else, indent like
  19784. parent's first line.
  19785. 3. Otherwise, indent relatively to current level, if
  19786. `org-adapt-indentation' is non-nil, or to left margin.
  19787. - On a blank line at the end of an element, indent according to
  19788. the type of the element. More precisely
  19789. 1. If element is a plain list, an item, or a footnote
  19790. definition, indent like the very last element within.
  19791. 2. If element is a paragraph, indent like its last non blank
  19792. line.
  19793. 3. Otherwise, indent like its very first line.
  19794. - In the code part of a source block, use language major mode
  19795. to indent current line if `org-src-tab-acts-natively' is
  19796. non-nil. If it is nil, do nothing.
  19797. - Otherwise, indent like the first non-blank line above.
  19798. The function doesn't indent an item as it could break the whole
  19799. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19800. `\\[org-shiftmetaright]'.
  19801. Also align node properties according to `org-property-format'."
  19802. (interactive)
  19803. (cond
  19804. ((org-at-heading-p) 'noindent)
  19805. (t
  19806. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19807. (type (org-element-type element)))
  19808. (cond ((and (memq type '(plain-list item))
  19809. (= (line-beginning-position)
  19810. (org-element-property :post-affiliated element)))
  19811. 'noindent)
  19812. ((and (eq type 'latex-environment)
  19813. (>= (point) (org-element-property :post-affiliated element))
  19814. (< (point) (org-with-wide-buffer
  19815. (goto-char (org-element-property :end element))
  19816. (skip-chars-backward " \r\t\n")
  19817. (line-beginning-position 2))))
  19818. 'noindent)
  19819. ((and (eq type 'src-block)
  19820. org-src-tab-acts-natively
  19821. (> (line-beginning-position)
  19822. (org-element-property :post-affiliated element))
  19823. (< (line-beginning-position)
  19824. (org-with-wide-buffer
  19825. (goto-char (org-element-property :end element))
  19826. (skip-chars-backward " \r\t\n")
  19827. (line-beginning-position))))
  19828. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19829. (t
  19830. (let ((column (org--get-expected-indentation element nil)))
  19831. ;; Preserve current column.
  19832. (if (<= (current-column) (current-indentation))
  19833. (indent-line-to column)
  19834. (save-excursion (indent-line-to column))))
  19835. ;; Align node property. Also preserve current column.
  19836. (when (eq type 'node-property)
  19837. (let ((column (current-column)))
  19838. (org--align-node-property)
  19839. (org-move-to-column column)))))))))
  19840. (defun org-indent-region (start end)
  19841. "Indent each non-blank line in the region.
  19842. Called from a program, START and END specify the region to
  19843. indent. The function will not indent contents of example blocks,
  19844. verse blocks and export blocks as leading white spaces are
  19845. assumed to be significant there."
  19846. (interactive "r")
  19847. (save-excursion
  19848. (goto-char start)
  19849. (skip-chars-forward " \r\t\n")
  19850. (unless (eobp) (beginning-of-line))
  19851. (let ((indent-to
  19852. (lambda (ind pos)
  19853. ;; Set IND as indentation for all lines between point and
  19854. ;; POS. Blank lines are ignored. Leave point after POS
  19855. ;; once done.
  19856. (let ((limit (copy-marker pos)))
  19857. (while (< (point) limit)
  19858. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19859. (forward-line))
  19860. (set-marker limit nil))))
  19861. (end (copy-marker end)))
  19862. (while (< (point) end)
  19863. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19864. (let* ((element (org-element-at-point))
  19865. (type (org-element-type element))
  19866. (element-end (copy-marker (org-element-property :end element)))
  19867. (ind (org--get-expected-indentation element nil)))
  19868. (cond
  19869. ;; Element indented as a single block. Example blocks
  19870. ;; preserving indentation are a special case since the
  19871. ;; "contents" must not be indented whereas the block
  19872. ;; boundaries can.
  19873. ((or (memq type '(export-block latex-environment))
  19874. (and (eq type 'example-block)
  19875. (not
  19876. (or org-src-preserve-indentation
  19877. (org-element-property :preserve-indent element)))))
  19878. (let ((offset (- ind (current-indentation))))
  19879. (unless (zerop offset)
  19880. (indent-rigidly (org-element-property :begin element)
  19881. (org-element-property :end element)
  19882. offset)))
  19883. (goto-char element-end))
  19884. ;; Elements indented line wise. Be sure to exclude
  19885. ;; example blocks (preserving indentation) and source
  19886. ;; blocks from this category as they are treated
  19887. ;; specially later.
  19888. ((or (memq type '(paragraph table table-row))
  19889. (not (or (org-element-property :contents-begin element)
  19890. (memq type '(example-block src-block)))))
  19891. (when (eq type 'node-property)
  19892. (org--align-node-property)
  19893. (beginning-of-line))
  19894. (funcall indent-to ind (min element-end end)))
  19895. ;; Elements consisting of three parts: before the
  19896. ;; contents, the contents, and after the contents. The
  19897. ;; contents are treated specially, according to the
  19898. ;; element type, or not indented at all. Other parts are
  19899. ;; indented as a single block.
  19900. (t
  19901. (let* ((post (copy-marker
  19902. (org-element-property :post-affiliated element)))
  19903. (cbeg
  19904. (copy-marker
  19905. (cond
  19906. ((not (org-element-property :contents-begin element))
  19907. ;; Fake contents for source blocks.
  19908. (org-with-wide-buffer
  19909. (goto-char post)
  19910. (line-beginning-position 2)))
  19911. ((memq type '(footnote-definition item plain-list))
  19912. ;; Contents in these elements could start on
  19913. ;; the same line as the beginning of the
  19914. ;; element. Make sure we start indenting
  19915. ;; from the second line.
  19916. (org-with-wide-buffer
  19917. (goto-char post)
  19918. (end-of-line)
  19919. (skip-chars-forward " \r\t\n")
  19920. (if (eobp) (point) (line-beginning-position))))
  19921. (t (org-element-property :contents-begin element)))))
  19922. (cend (copy-marker
  19923. (or (org-element-property :contents-end element)
  19924. ;; Fake contents for source blocks.
  19925. (org-with-wide-buffer
  19926. (goto-char element-end)
  19927. (skip-chars-backward " \r\t\n")
  19928. (line-beginning-position)))
  19929. t)))
  19930. ;; Do not change items indentation individually as it
  19931. ;; might break the list as a whole. On the other
  19932. ;; hand, when at a plain list, indent it as a whole.
  19933. (cond ((eq type 'plain-list)
  19934. (let ((offset (- ind (current-indentation))))
  19935. (unless (zerop offset)
  19936. (indent-rigidly (org-element-property :begin element)
  19937. (org-element-property :end element)
  19938. offset))
  19939. (goto-char cbeg)))
  19940. ((eq type 'item) (goto-char cbeg))
  19941. (t (funcall indent-to ind (min cbeg end))))
  19942. (when (< (point) end)
  19943. (cl-case type
  19944. ((example-block verse-block))
  19945. (src-block
  19946. ;; In a source block, indent source code
  19947. ;; according to language major mode, but only if
  19948. ;; `org-src-tab-acts-natively' is non-nil.
  19949. (when (and (< (point) end) org-src-tab-acts-natively)
  19950. (ignore-errors
  19951. (org-babel-do-in-edit-buffer
  19952. (indent-region (point-min) (point-max))))))
  19953. (t (org-indent-region (point) (min cend end))))
  19954. (goto-char (min cend end))
  19955. (when (< (point) end)
  19956. (funcall indent-to ind (min element-end end))))
  19957. (set-marker post nil)
  19958. (set-marker cbeg nil)
  19959. (set-marker cend nil))))
  19960. (set-marker element-end nil))))
  19961. (set-marker end nil))))
  19962. (defun org-indent-drawer ()
  19963. "Indent the drawer at point."
  19964. (interactive)
  19965. (unless (save-excursion
  19966. (beginning-of-line)
  19967. (looking-at-p org-drawer-regexp))
  19968. (user-error "Not at a drawer"))
  19969. (let ((element (org-element-at-point)))
  19970. (unless (memq (org-element-type element) '(drawer property-drawer))
  19971. (user-error "Not at a drawer"))
  19972. (org-with-wide-buffer
  19973. (org-indent-region (org-element-property :begin element)
  19974. (org-element-property :end element))))
  19975. (message "Drawer at point indented"))
  19976. (defun org-indent-block ()
  19977. "Indent the block at point."
  19978. (interactive)
  19979. (unless (save-excursion
  19980. (beginning-of-line)
  19981. (let ((case-fold-search t))
  19982. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19983. (user-error "Not at a block"))
  19984. (let ((element (org-element-at-point)))
  19985. (unless (memq (org-element-type element)
  19986. '(comment-block center-block dynamic-block example-block
  19987. export-block quote-block special-block
  19988. src-block verse-block))
  19989. (user-error "Not at a block"))
  19990. (org-with-wide-buffer
  19991. (org-indent-region (org-element-property :begin element)
  19992. (org-element-property :end element))))
  19993. (message "Block at point indented"))
  19994. ;;; Filling
  19995. ;; We use our own fill-paragraph and auto-fill functions.
  19996. ;; `org-fill-paragraph' relies on adaptive filling and context
  19997. ;; checking. Appropriate `fill-prefix' is computed with
  19998. ;; `org-adaptive-fill-function'.
  19999. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20000. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20001. ;; `org-adaptive-fill-function' value. Internally,
  20002. ;; `org-comment-line-break-function' breaks the line.
  20003. ;; `org-setup-filling' installs filling and auto-filling related
  20004. ;; variables during `org-mode' initialization.
  20005. (defun org-setup-filling ()
  20006. (require 'org-element)
  20007. ;; Prevent auto-fill from inserting unwanted new items.
  20008. (when (boundp 'fill-nobreak-predicate)
  20009. (setq-local
  20010. fill-nobreak-predicate
  20011. (org-uniquify
  20012. (append fill-nobreak-predicate
  20013. '(org-fill-line-break-nobreak-p
  20014. org-fill-n-macro-as-item-nobreak-p
  20015. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20016. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20017. (setq-local paragraph-start paragraph-ending)
  20018. (setq-local paragraph-separate paragraph-ending))
  20019. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20020. (setq-local auto-fill-inhibit-regexp nil)
  20021. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20022. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20023. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20024. (defun org-fill-line-break-nobreak-p ()
  20025. "Non-nil when a new line at point would create an Org line break."
  20026. (save-excursion
  20027. (skip-chars-backward "[ \t]")
  20028. (skip-chars-backward "\\\\")
  20029. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20030. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20031. "Non-nil when a new line at point would split a timestamp."
  20032. (and (org-at-timestamp-p 'lax)
  20033. (not (looking-at org-ts-regexp-both))))
  20034. (defun org-fill-n-macro-as-item-nobreak-p ()
  20035. "Non-nil when a new line at point would create a new list."
  20036. ;; During export, a "n" macro followed by a dot or a closing
  20037. ;; parenthesis can end up being parsed as a new list item.
  20038. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20039. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20040. (defun org-adaptive-fill-function ()
  20041. "Compute a fill prefix for the current line.
  20042. Return fill prefix, as a string, or nil if current line isn't
  20043. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20044. matches in paragraphs or comments, use it."
  20045. (org-with-wide-buffer
  20046. (unless (org-at-heading-p)
  20047. (let* ((p (line-beginning-position))
  20048. (element (save-excursion
  20049. (beginning-of-line)
  20050. (org-element-at-point)))
  20051. (type (org-element-type element))
  20052. (post-affiliated (org-element-property :post-affiliated element)))
  20053. (unless (< p post-affiliated)
  20054. (cl-case type
  20055. (comment
  20056. (save-excursion
  20057. (beginning-of-line)
  20058. (looking-at "[ \t]*")
  20059. (concat (match-string 0) "# ")))
  20060. (footnote-definition "")
  20061. ((item plain-list)
  20062. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20063. (paragraph
  20064. ;; Fill prefix is usually the same as the current line,
  20065. ;; unless the paragraph is at the beginning of an item.
  20066. (let ((parent (org-element-property :parent element)))
  20067. (save-excursion
  20068. (beginning-of-line)
  20069. (cond ((eq (org-element-type parent) 'item)
  20070. (make-string (org-list-item-body-column
  20071. (org-element-property :begin parent))
  20072. ?\s))
  20073. ((and adaptive-fill-regexp
  20074. ;; Locally disable
  20075. ;; `adaptive-fill-function' to let
  20076. ;; `fill-context-prefix' handle
  20077. ;; `adaptive-fill-regexp' variable.
  20078. (let (adaptive-fill-function)
  20079. (fill-context-prefix
  20080. post-affiliated
  20081. (org-element-property :end element)))))
  20082. ((looking-at "[ \t]+") (match-string 0))
  20083. (t "")))))
  20084. (comment-block
  20085. ;; Only fill contents if P is within block boundaries.
  20086. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20087. (forward-line)
  20088. (point)))
  20089. (cend (save-excursion
  20090. (goto-char (org-element-property :end element))
  20091. (skip-chars-backward " \r\t\n")
  20092. (line-beginning-position))))
  20093. (when (and (>= p cbeg) (< p cend))
  20094. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20095. (match-string 0)
  20096. ""))))))))))
  20097. (defun org-fill-element (&optional justify)
  20098. "Fill element at point, when applicable.
  20099. This function only applies to comment blocks, comments, example
  20100. blocks and paragraphs. Also, as a special case, re-align table
  20101. when point is at one.
  20102. If JUSTIFY is non-nil (interactively, with prefix argument),
  20103. justify as well. If `sentence-end-double-space' is non-nil, then
  20104. period followed by one space does not end a sentence, so don't
  20105. break a line there. The variable `fill-column' controls the
  20106. width for filling.
  20107. For convenience, when point is at a plain list, an item or
  20108. a footnote definition, try to fill the first paragraph within."
  20109. (with-syntax-table org-mode-transpose-word-syntax-table
  20110. ;; Move to end of line in order to get the first paragraph within
  20111. ;; a plain list or a footnote definition.
  20112. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20113. ;; First check if point is in a blank line at the beginning of
  20114. ;; the buffer. In that case, ignore filling.
  20115. (cl-case (org-element-type element)
  20116. ;; Use major mode filling function is source blocks.
  20117. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20118. ;; Align Org tables, leave table.el tables as-is.
  20119. (table-row (org-table-align) t)
  20120. (table
  20121. (when (eq (org-element-property :type element) 'org)
  20122. (save-excursion
  20123. (goto-char (org-element-property :post-affiliated element))
  20124. (org-table-align)))
  20125. t)
  20126. (paragraph
  20127. ;; Paragraphs may contain `line-break' type objects.
  20128. (let ((beg (max (point-min)
  20129. (org-element-property :contents-begin element)))
  20130. (end (min (point-max)
  20131. (org-element-property :contents-end element))))
  20132. ;; Do nothing if point is at an affiliated keyword.
  20133. (if (< (line-end-position) beg) t
  20134. ;; Fill paragraph, taking line breaks into account.
  20135. (save-excursion
  20136. (goto-char beg)
  20137. (let ((cuts (list beg)))
  20138. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20139. (when (eq 'line-break
  20140. (org-element-type
  20141. (save-excursion (backward-char)
  20142. (org-element-context))))
  20143. (push (point) cuts)))
  20144. (dolist (c (delq end cuts))
  20145. (fill-region-as-paragraph c end justify)
  20146. (setq end c))))
  20147. t)))
  20148. ;; Contents of `comment-block' type elements should be
  20149. ;; filled as plain text, but only if point is within block
  20150. ;; markers.
  20151. (comment-block
  20152. (let* ((case-fold-search t)
  20153. (beg (save-excursion
  20154. (goto-char (org-element-property :begin element))
  20155. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20156. (forward-line)
  20157. (point)))
  20158. (end (save-excursion
  20159. (goto-char (org-element-property :end element))
  20160. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20161. (line-beginning-position))))
  20162. (if (or (< (point) beg) (> (point) end)) t
  20163. (fill-region-as-paragraph
  20164. (save-excursion (end-of-line)
  20165. (re-search-backward "^[ \t]*$" beg 'move)
  20166. (line-beginning-position))
  20167. (save-excursion (beginning-of-line)
  20168. (re-search-forward "^[ \t]*$" end 'move)
  20169. (line-beginning-position))
  20170. justify))))
  20171. ;; Fill comments.
  20172. (comment
  20173. (let ((begin (org-element-property :post-affiliated element))
  20174. (end (org-element-property :end element)))
  20175. (when (and (>= (point) begin) (<= (point) end))
  20176. (let ((begin (save-excursion
  20177. (end-of-line)
  20178. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20179. (progn (forward-line) (point))
  20180. begin)))
  20181. (end (save-excursion
  20182. (end-of-line)
  20183. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20184. (1- (line-beginning-position))
  20185. (skip-chars-backward " \r\t\n")
  20186. (line-end-position)))))
  20187. ;; Do not fill comments when at a blank line.
  20188. (when (> end begin)
  20189. (let ((fill-prefix
  20190. (save-excursion
  20191. (beginning-of-line)
  20192. (looking-at "[ \t]*#")
  20193. (let ((comment-prefix (match-string 0)))
  20194. (goto-char (match-end 0))
  20195. (if (looking-at adaptive-fill-regexp)
  20196. (concat comment-prefix (match-string 0))
  20197. (concat comment-prefix " "))))))
  20198. (save-excursion
  20199. (fill-region-as-paragraph begin end justify))))))
  20200. t))
  20201. ;; Ignore every other element.
  20202. (otherwise t)))))
  20203. (defun org-fill-paragraph (&optional justify region)
  20204. "Fill element at point, when applicable.
  20205. This function only applies to comment blocks, comments, example
  20206. blocks and paragraphs. Also, as a special case, re-align table
  20207. when point is at one.
  20208. For convenience, when point is at a plain list, an item or
  20209. a footnote definition, try to fill the first paragraph within.
  20210. If JUSTIFY is non-nil (interactively, with prefix argument),
  20211. justify as well. If `sentence-end-double-space' is non-nil, then
  20212. period followed by one space does not end a sentence, so don't
  20213. break a line there. The variable `fill-column' controls the
  20214. width for filling.
  20215. The REGION argument is non-nil if called interactively; in that
  20216. case, if Transient Mark mode is enabled and the mark is active,
  20217. fill each of the elements in the active region, instead of just
  20218. filling the current element."
  20219. (interactive (progn
  20220. (barf-if-buffer-read-only)
  20221. (list (when current-prefix-arg 'full) t)))
  20222. (cond
  20223. ((and region transient-mark-mode mark-active
  20224. (not (eq (region-beginning) (region-end))))
  20225. (let ((origin (point-marker))
  20226. (start (region-beginning)))
  20227. (unwind-protect
  20228. (progn
  20229. (goto-char (region-end))
  20230. (while (> (point) start)
  20231. (org-backward-paragraph)
  20232. (org-fill-element justify)))
  20233. (goto-char origin)
  20234. (set-marker origin nil))))
  20235. (t (org-fill-element justify))))
  20236. (defun org-auto-fill-function ()
  20237. "Auto-fill function."
  20238. ;; Check if auto-filling is meaningful.
  20239. (let ((fc (current-fill-column)))
  20240. (when (and fc (> (current-column) fc))
  20241. (let* ((fill-prefix (org-adaptive-fill-function))
  20242. ;; Enforce empty fill prefix, if required. Otherwise, it
  20243. ;; will be computed again.
  20244. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20245. (when fill-prefix (do-auto-fill))))))
  20246. (defun org-comment-line-break-function (&optional soft)
  20247. "Break line at point and indent, continuing comment if within one.
  20248. The inserted newline is marked hard if variable
  20249. `use-hard-newlines' is true, unless optional argument SOFT is
  20250. non-nil."
  20251. (if soft (insert-and-inherit ?\n) (newline 1))
  20252. (save-excursion (forward-char -1) (delete-horizontal-space))
  20253. (delete-horizontal-space)
  20254. (indent-to-left-margin)
  20255. (insert-before-markers-and-inherit fill-prefix))
  20256. ;;; Fixed Width Areas
  20257. (defun org-toggle-fixed-width ()
  20258. "Toggle fixed-width markup.
  20259. Add or remove fixed-width markup on current line, whenever it
  20260. makes sense. Return an error otherwise.
  20261. If a region is active and if it contains only fixed-width areas
  20262. or blank lines, remove all fixed-width markup in it. If the
  20263. region contains anything else, convert all non-fixed-width lines
  20264. to fixed-width ones.
  20265. Blank lines at the end of the region are ignored unless the
  20266. region only contains such lines."
  20267. (interactive)
  20268. (if (not (org-region-active-p))
  20269. ;; No region:
  20270. ;;
  20271. ;; Remove fixed width marker only in a fixed-with element.
  20272. ;;
  20273. ;; Add fixed width maker in paragraphs, in blank lines after
  20274. ;; elements or at the beginning of a headline or an inlinetask,
  20275. ;; and before any one-line elements (e.g., a clock).
  20276. (progn
  20277. (beginning-of-line)
  20278. (let* ((element (org-element-at-point))
  20279. (type (org-element-type element)))
  20280. (cond
  20281. ((and (eq type 'fixed-width)
  20282. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20283. (replace-match
  20284. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20285. ((and (memq type '(babel-call clock comment diary-sexp headline
  20286. horizontal-rule keyword paragraph
  20287. planning))
  20288. (<= (org-element-property :post-affiliated element) (point)))
  20289. (skip-chars-forward " \t")
  20290. (insert ": "))
  20291. ((and (looking-at-p "[ \t]*$")
  20292. (or (eq type 'inlinetask)
  20293. (save-excursion
  20294. (skip-chars-forward " \r\t\n")
  20295. (<= (org-element-property :end element) (point)))))
  20296. (delete-region (point) (line-end-position))
  20297. (org-indent-line)
  20298. (insert ": "))
  20299. (t (user-error "Cannot insert a fixed-width line here")))))
  20300. ;; Region active.
  20301. (let* ((begin (save-excursion
  20302. (goto-char (region-beginning))
  20303. (line-beginning-position)))
  20304. (end (copy-marker
  20305. (save-excursion
  20306. (goto-char (region-end))
  20307. (unless (eolp) (beginning-of-line))
  20308. (if (save-excursion (re-search-backward "\\S-" begin t))
  20309. (progn (skip-chars-backward " \r\t\n") (point))
  20310. (point)))))
  20311. (all-fixed-width-p
  20312. (catch 'not-all-p
  20313. (save-excursion
  20314. (goto-char begin)
  20315. (skip-chars-forward " \r\t\n")
  20316. (when (eobp) (throw 'not-all-p nil))
  20317. (while (< (point) end)
  20318. (let ((element (org-element-at-point)))
  20319. (if (eq (org-element-type element) 'fixed-width)
  20320. (goto-char (org-element-property :end element))
  20321. (throw 'not-all-p nil))))
  20322. t))))
  20323. (if all-fixed-width-p
  20324. (save-excursion
  20325. (goto-char begin)
  20326. (while (< (point) end)
  20327. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20328. (replace-match
  20329. "" nil nil nil
  20330. (if (= (line-end-position) (match-end 0)) 0 1)))
  20331. (forward-line)))
  20332. (let ((min-ind (point-max)))
  20333. ;; Find minimum indentation across all lines.
  20334. (save-excursion
  20335. (goto-char begin)
  20336. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20337. (setq min-ind 0)
  20338. (catch 'zerop
  20339. (while (< (point) end)
  20340. (unless (looking-at-p "[ \t]*$")
  20341. (let ((ind (current-indentation)))
  20342. (setq min-ind (min min-ind ind))
  20343. (when (zerop ind) (throw 'zerop t))))
  20344. (forward-line)))))
  20345. ;; Loop over all lines and add fixed-width markup everywhere
  20346. ;; but in fixed-width lines.
  20347. (save-excursion
  20348. (goto-char begin)
  20349. (while (< (point) end)
  20350. (cond
  20351. ((org-at-heading-p)
  20352. (insert ": ")
  20353. (forward-line)
  20354. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20355. (insert ":")
  20356. (forward-line)))
  20357. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20358. (let* ((element (org-element-at-point))
  20359. (element-end (org-element-property :end element)))
  20360. (if (eq (org-element-type element) 'fixed-width)
  20361. (progn (goto-char element-end)
  20362. (skip-chars-backward " \r\t\n")
  20363. (forward-line))
  20364. (let ((limit (min end element-end)))
  20365. (while (< (point) limit)
  20366. (org-move-to-column min-ind t)
  20367. (insert ": ")
  20368. (forward-line))))))
  20369. (t
  20370. (org-move-to-column min-ind t)
  20371. (insert ": ")
  20372. (forward-line)))))))
  20373. (set-marker end nil))))
  20374. ;;; Blocks
  20375. (defun org-block-map (function &optional start end)
  20376. "Call FUNCTION at the head of all source blocks in the current buffer.
  20377. Optional arguments START and END can be used to limit the range."
  20378. (let ((start (or start (point-min)))
  20379. (end (or end (point-max))))
  20380. (save-excursion
  20381. (goto-char start)
  20382. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20383. (save-excursion
  20384. (save-match-data
  20385. (goto-char (match-beginning 0))
  20386. (funcall function)))))))
  20387. (defun org-next-block (arg &optional backward block-regexp)
  20388. "Jump to the next block.
  20389. With a prefix argument ARG, jump forward ARG many blocks.
  20390. When BACKWARD is non-nil, jump to the previous block.
  20391. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20392. Match data is set according to this regexp when the function
  20393. returns.
  20394. Return point at beginning of the opening line of found block.
  20395. Throw an error if no block is found."
  20396. (interactive "p")
  20397. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20398. (case-fold-search t)
  20399. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20400. (count (or arg 1))
  20401. (origin (point))
  20402. last-element)
  20403. (if backward (beginning-of-line) (end-of-line))
  20404. (while (and (> count 0) (funcall search-fn re nil t))
  20405. (let ((element (save-excursion
  20406. (goto-char (match-beginning 0))
  20407. (save-match-data (org-element-at-point)))))
  20408. (when (and (memq (org-element-type element)
  20409. '(center-block comment-block dynamic-block
  20410. example-block export-block quote-block
  20411. special-block src-block verse-block))
  20412. (<= (match-beginning 0)
  20413. (org-element-property :post-affiliated element)))
  20414. (setq last-element element)
  20415. (cl-decf count))))
  20416. (if (= count 0)
  20417. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20418. (save-match-data (org-show-context)))
  20419. (goto-char origin)
  20420. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20421. (defun org-previous-block (arg &optional block-regexp)
  20422. "Jump to the previous block.
  20423. With a prefix argument ARG, jump backward ARG many source blocks.
  20424. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20425. (interactive "p")
  20426. (org-next-block arg t block-regexp))
  20427. ;;; Comments
  20428. ;; Org comments syntax is quite complex. It requires the entire line
  20429. ;; to be just a comment. Also, even with the right syntax at the
  20430. ;; beginning of line, some elements (e.g., verse-block or
  20431. ;; example-block) don't accept comments. Usual Emacs comment commands
  20432. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20433. ;; Org still relies on `comment-dwim', but cannot trust
  20434. ;; `comment-only-p'. So, `comment-region-function' and
  20435. ;; `uncomment-region-function' both point
  20436. ;; to`org-comment-or-uncomment-region'. Eventually,
  20437. ;; `org-insert-comment' takes care of insertion of comments at the
  20438. ;; beginning of line.
  20439. ;; `org-setup-comments-handling' install comments related variables
  20440. ;; during `org-mode' initialization.
  20441. (defun org-setup-comments-handling ()
  20442. (interactive)
  20443. (setq-local comment-use-syntax nil)
  20444. (setq-local comment-start "# ")
  20445. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20446. (setq-local comment-insert-comment-function 'org-insert-comment)
  20447. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20448. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20449. (defun org-insert-comment ()
  20450. "Insert an empty comment above current line.
  20451. If the line is empty, insert comment at its beginning. When
  20452. point is within a source block, comment according to the related
  20453. major mode."
  20454. (if (let ((element (org-element-at-point)))
  20455. (and (eq (org-element-type element) 'src-block)
  20456. (< (save-excursion
  20457. (goto-char (org-element-property :post-affiliated element))
  20458. (line-end-position))
  20459. (point))
  20460. (> (save-excursion
  20461. (goto-char (org-element-property :end element))
  20462. (skip-chars-backward " \r\t\n")
  20463. (line-beginning-position))
  20464. (point))))
  20465. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20466. (beginning-of-line)
  20467. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20468. (open-line 1))
  20469. (org-indent-line)
  20470. (insert "# ")))
  20471. (defvar comment-empty-lines) ; From newcomment.el.
  20472. (defun org-comment-or-uncomment-region (beg end &rest _)
  20473. "Comment or uncomment each non-blank line in the region.
  20474. Uncomment each non-blank line between BEG and END if it only
  20475. contains commented lines. Otherwise, comment them. If region is
  20476. strictly within a source block, use appropriate comment syntax."
  20477. (if (let ((element (org-element-at-point)))
  20478. (and (eq (org-element-type element) 'src-block)
  20479. (< (save-excursion
  20480. (goto-char (org-element-property :post-affiliated element))
  20481. (line-end-position))
  20482. beg)
  20483. (>= (save-excursion
  20484. (goto-char (org-element-property :end element))
  20485. (skip-chars-backward " \r\t\n")
  20486. (line-beginning-position))
  20487. end)))
  20488. ;; Translate region boundaries for the Org buffer to the source
  20489. ;; buffer.
  20490. (let ((offset (- end beg)))
  20491. (save-excursion
  20492. (goto-char beg)
  20493. (org-babel-do-in-edit-buffer
  20494. (comment-or-uncomment-region (point) (+ offset (point))))))
  20495. (save-restriction
  20496. ;; Restrict region
  20497. (narrow-to-region (save-excursion (goto-char beg)
  20498. (skip-chars-forward " \r\t\n" end)
  20499. (line-beginning-position))
  20500. (save-excursion (goto-char end)
  20501. (skip-chars-backward " \r\t\n" beg)
  20502. (line-end-position)))
  20503. (let ((uncommentp
  20504. ;; UNCOMMENTP is non-nil when every non blank line between
  20505. ;; BEG and END is a comment.
  20506. (save-excursion
  20507. (goto-char (point-min))
  20508. (while (and (not (eobp))
  20509. (let ((element (org-element-at-point)))
  20510. (and (eq (org-element-type element) 'comment)
  20511. (goto-char (min (point-max)
  20512. (org-element-property
  20513. :end element)))))))
  20514. (eobp))))
  20515. (if uncommentp
  20516. ;; Only blank lines and comments in region: uncomment it.
  20517. (save-excursion
  20518. (goto-char (point-min))
  20519. (while (not (eobp))
  20520. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20521. (replace-match "" nil nil nil 1))
  20522. (forward-line)))
  20523. ;; Comment each line in region.
  20524. (let ((min-indent (point-max)))
  20525. ;; First find the minimum indentation across all lines.
  20526. (save-excursion
  20527. (goto-char (point-min))
  20528. (while (and (not (eobp)) (not (zerop min-indent)))
  20529. (unless (looking-at "[ \t]*$")
  20530. (setq min-indent (min min-indent (current-indentation))))
  20531. (forward-line)))
  20532. ;; Then loop over all lines.
  20533. (save-excursion
  20534. (goto-char (point-min))
  20535. (while (not (eobp))
  20536. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20537. ;; Don't get fooled by invisible text (e.g. link path)
  20538. ;; when moving to column MIN-INDENT.
  20539. (let ((buffer-invisibility-spec nil))
  20540. (org-move-to-column min-indent t))
  20541. (insert comment-start))
  20542. (forward-line)))))))))
  20543. (defun org-comment-dwim (_arg)
  20544. "Call the comment command you mean.
  20545. Call `org-toggle-comment' if on a heading, otherwise call
  20546. `comment-dwim', within a source edit buffer if needed."
  20547. (interactive "*P")
  20548. (cond ((org-at-heading-p)
  20549. (call-interactively #'org-toggle-comment))
  20550. ((org-in-src-block-p)
  20551. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20552. (t (call-interactively #'comment-dwim))))
  20553. ;;; Timestamps API
  20554. ;; This section contains tools to operate on, or create, timestamp
  20555. ;; objects, as returned by, e.g. `org-element-context'.
  20556. (defun org-timestamp-from-string (s)
  20557. "Convert Org timestamp S, as a string, into a timestamp object.
  20558. Return nil if S is not a valid timestamp string."
  20559. (when (org-string-nw-p s)
  20560. (with-temp-buffer
  20561. (save-excursion (insert s))
  20562. (org-element-timestamp-parser))))
  20563. (defun org-timestamp-from-time (time &optional with-time inactive)
  20564. "Convert a time value into a timestamp object.
  20565. TIME is an Emacs internal time representation, as returned, e.g.,
  20566. by `current-time'.
  20567. When optional argument WITH-TIME is non-nil, return a timestamp
  20568. object with a time part, i.e., with hours and minutes.
  20569. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20570. return an active timestamp."
  20571. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20572. (org-element-create 'timestamp
  20573. (list :type (if inactive 'inactive 'active)
  20574. :year-start year
  20575. :month-start month
  20576. :day-start day
  20577. :hour-start (and with-time hour)
  20578. :minute-start (and with-time minute)))))
  20579. (defun org-timestamp-to-time (timestamp &optional end)
  20580. "Convert TIMESTAMP object into an Emacs internal time value.
  20581. Use end of date range or time range when END is non-nil.
  20582. Otherwise, use its start."
  20583. (apply #'encode-time
  20584. (cons 0
  20585. (mapcar
  20586. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20587. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20588. '(:minute-start :hour-start :day-start :month-start
  20589. :year-start))))))
  20590. (defun org-timestamp-has-time-p (timestamp)
  20591. "Non-nil when TIMESTAMP has a time specified."
  20592. (org-element-property :hour-start timestamp))
  20593. (defun org-timestamp-format (timestamp format &optional end utc)
  20594. "Format a TIMESTAMP object into a string.
  20595. FORMAT is a format specifier to be passed to
  20596. `format-time-string'.
  20597. When optional argument END is non-nil, use end of date-range or
  20598. time-range, if possible.
  20599. When optional argument UTC is non-nil, time is be expressed as
  20600. Universal Time."
  20601. (format-time-string format (org-timestamp-to-time timestamp end)
  20602. (and utc t)))
  20603. (defun org-timestamp-split-range (timestamp &optional end)
  20604. "Extract a TIMESTAMP object from a date or time range.
  20605. END, when non-nil, means extract the end of the range.
  20606. Otherwise, extract its start.
  20607. Return a new timestamp object."
  20608. (let ((type (org-element-property :type timestamp)))
  20609. (if (memq type '(active inactive diary)) timestamp
  20610. (let ((split-ts (org-element-copy timestamp)))
  20611. ;; Set new type.
  20612. (org-element-put-property
  20613. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20614. ;; Copy start properties over end properties if END is
  20615. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20616. (let ((p-alist '((:minute-start . :minute-end)
  20617. (:hour-start . :hour-end)
  20618. (:day-start . :day-end)
  20619. (:month-start . :month-end)
  20620. (:year-start . :year-end))))
  20621. (dolist (p-cell p-alist)
  20622. (org-element-put-property
  20623. split-ts
  20624. (funcall (if end #'car #'cdr) p-cell)
  20625. (org-element-property
  20626. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20627. ;; Eventually refresh `:raw-value'.
  20628. (org-element-put-property split-ts :raw-value nil)
  20629. (org-element-put-property
  20630. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20631. (defun org-timestamp-translate (timestamp &optional boundary)
  20632. "Translate TIMESTAMP object to custom format.
  20633. Format string is defined in `org-time-stamp-custom-formats',
  20634. which see.
  20635. When optional argument BOUNDARY is non-nil, it is either the
  20636. symbol `start' or `end'. In this case, only translate the
  20637. starting or ending part of TIMESTAMP if it is a date or time
  20638. range. Otherwise, translate both parts.
  20639. Return timestamp as-is if `org-display-custom-times' is nil or if
  20640. it has a `diary' type."
  20641. (let ((type (org-element-property :type timestamp)))
  20642. (if (or (not org-display-custom-times) (eq type 'diary))
  20643. (org-element-interpret-data timestamp)
  20644. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20645. org-time-stamp-custom-formats)))
  20646. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20647. (concat (org-timestamp-format timestamp fmt)
  20648. "--"
  20649. (org-timestamp-format timestamp fmt t))
  20650. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20651. ;;; Other stuff
  20652. (defvar reftex-docstruct-symbol)
  20653. (defvar org--rds)
  20654. (defun org-reftex-citation ()
  20655. "Use reftex-citation to insert a citation into the buffer.
  20656. This looks for a line like
  20657. #+BIBLIOGRAPHY: foo plain option:-d
  20658. and derives from it that foo.bib is the bibliography file relevant
  20659. for this document. It then installs the necessary environment for RefTeX
  20660. to work in this buffer and calls `reftex-citation' to insert a citation
  20661. into the buffer.
  20662. Export of such citations to both LaTeX and HTML is handled by the contributed
  20663. package ox-bibtex by Taru Karttunen."
  20664. (interactive)
  20665. (let ((reftex-docstruct-symbol 'org--rds)
  20666. org--rds bib)
  20667. (org-with-wide-buffer
  20668. (let ((case-fold-search t)
  20669. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20670. (if (not (save-excursion
  20671. (or (re-search-forward re nil t)
  20672. (re-search-backward re nil t))))
  20673. (user-error "No bibliography defined in file")
  20674. (setq bib (concat (match-string 1) ".bib")
  20675. org--rds (list (list 'bib bib))))))
  20676. (call-interactively 'reftex-citation)))
  20677. ;;;; Functions extending outline functionality
  20678. (defun org-beginning-of-line (&optional n)
  20679. "Go to the beginning of the current visible line.
  20680. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20681. symbol `reversed', on the first attempt move to where the
  20682. headline text starts, and only move to beginning of line when the
  20683. cursor is already before the start of the text of the headline.
  20684. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20685. start of the text on the second attempt.
  20686. With argument N not nil or 1, move forward N - 1 lines first."
  20687. (interactive "^p")
  20688. (let ((origin (point))
  20689. (special (pcase org-special-ctrl-a/e
  20690. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20691. deactivate-mark)
  20692. ;; First move to a visible line.
  20693. (if (bound-and-true-p visual-line-mode)
  20694. (beginning-of-visual-line n)
  20695. (move-beginning-of-line n)
  20696. ;; `move-beginning-of-line' may leave point after invisible
  20697. ;; characters if line starts with such of these (e.g., with
  20698. ;; a link at column 0). Really move to the beginning of the
  20699. ;; current visible line.
  20700. (beginning-of-line))
  20701. (cond
  20702. ;; No special behavior. Point is already at the beginning of
  20703. ;; a line, logical or visual.
  20704. ((not special))
  20705. ;; `beginning-of-visual-line' left point before logical beginning
  20706. ;; of line: point is at the beginning of a visual line. Bail
  20707. ;; out.
  20708. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20709. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20710. ;; At a headline, special position is before the title, but
  20711. ;; after any TODO keyword or priority cookie.
  20712. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20713. (line-end-position)))
  20714. (bol (point)))
  20715. (if (eq special 'reversed)
  20716. (when (and (= origin bol) (eq last-command this-command))
  20717. (goto-char refpos))
  20718. (when (or (> origin refpos) (= origin bol))
  20719. (goto-char refpos)))))
  20720. ((and (looking-at org-list-full-item-re)
  20721. (memq (org-element-type (save-match-data (org-element-at-point)))
  20722. '(item plain-list)))
  20723. ;; Set special position at first white space character after
  20724. ;; bullet, and check-box, if any.
  20725. (let ((after-bullet
  20726. (let ((box (match-end 3)))
  20727. (cond ((not box) (match-end 1))
  20728. ((eq (char-after box) ?\s) (1+ box))
  20729. (t box)))))
  20730. (if (eq special 'reversed)
  20731. (when (and (= (point) origin) (eq last-command this-command))
  20732. (goto-char after-bullet))
  20733. (when (or (> origin after-bullet) (= (point) origin))
  20734. (goto-char after-bullet)))))
  20735. ;; No special context. Point is already at beginning of line.
  20736. (t nil))))
  20737. (defun org-end-of-line (&optional n)
  20738. "Go to the end of the line, but before ellipsis, if any.
  20739. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20740. symbol `reversed', ignore tags on the first attempt, and only
  20741. move to after the tags when the cursor is already beyond the end
  20742. of the headline.
  20743. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20744. on the second attempt.
  20745. With argument N not nil or 1, move forward N - 1 lines first."
  20746. (interactive "^p")
  20747. (let ((origin (point))
  20748. (special (pcase org-special-ctrl-a/e
  20749. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20750. deactivate-mark)
  20751. ;; First move to a visible line.
  20752. (if (bound-and-true-p visual-line-mode)
  20753. (beginning-of-visual-line n)
  20754. (move-beginning-of-line n))
  20755. (cond
  20756. ;; At a headline, with tags.
  20757. ((and special
  20758. (save-excursion
  20759. (beginning-of-line)
  20760. (let ((case-fold-search nil))
  20761. (looking-at org-complex-heading-regexp)))
  20762. (match-end 5))
  20763. (let ((tags (save-excursion
  20764. (goto-char (match-beginning 5))
  20765. (skip-chars-backward " \t")
  20766. (point)))
  20767. (visual-end (and (bound-and-true-p visual-line-mode)
  20768. (save-excursion
  20769. (end-of-visual-line)
  20770. (point)))))
  20771. ;; If `end-of-visual-line' brings us before end of line or
  20772. ;; even tags, i.e., the headline spans over multiple visual
  20773. ;; lines, move there.
  20774. (cond ((and visual-end
  20775. (< visual-end tags)
  20776. (<= origin visual-end))
  20777. (goto-char visual-end))
  20778. ((eq special 'reversed)
  20779. (if (and (= origin (line-end-position))
  20780. (eq this-command last-command))
  20781. (goto-char tags)
  20782. (end-of-line)))
  20783. (t
  20784. (if (or (< origin tags) (= origin (line-end-position)))
  20785. (goto-char tags)
  20786. (end-of-line))))))
  20787. ((bound-and-true-p visual-line-mode)
  20788. (let ((bol (line-beginning-position)))
  20789. (end-of-visual-line)
  20790. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20791. ;; end of a line, backtrack and use `end-of-line' instead.
  20792. (when (/= bol (line-beginning-position))
  20793. (goto-char bol)
  20794. (end-of-line))))
  20795. (t (end-of-line)))))
  20796. (defun org-backward-sentence (&optional _arg)
  20797. "Go to beginning of sentence, or beginning of table field.
  20798. This will call `backward-sentence' or `org-table-beginning-of-field',
  20799. depending on context."
  20800. (interactive)
  20801. (let* ((element (org-element-at-point))
  20802. (contents-begin (org-element-property :contents-begin element))
  20803. (table (org-element-lineage element '(table) t)))
  20804. (if (and table
  20805. (> (point) contents-begin)
  20806. (<= (point) (org-element-property :contents-end table)))
  20807. (call-interactively #'org-table-beginning-of-field)
  20808. (save-restriction
  20809. (when (and contents-begin
  20810. (< (point-min) contents-begin)
  20811. (> (point) contents-begin))
  20812. (narrow-to-region contents-begin
  20813. (org-element-property :contents-end element)))
  20814. (call-interactively #'backward-sentence)))))
  20815. (defun org-forward-sentence (&optional _arg)
  20816. "Go to end of sentence, or end of table field.
  20817. This will call `forward-sentence' or `org-table-end-of-field',
  20818. depending on context."
  20819. (interactive)
  20820. (if (and (org-at-heading-p)
  20821. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20822. (save-restriction
  20823. (narrow-to-region (line-beginning-position) (line-end-position))
  20824. (call-interactively #'forward-sentence))
  20825. (let* ((element (org-element-at-point))
  20826. (contents-end (org-element-property :contents-end element))
  20827. (table (org-element-lineage element '(table) t)))
  20828. (if (and table
  20829. (>= (point) (org-element-property :contents-begin table))
  20830. (< (point) contents-end))
  20831. (call-interactively #'org-table-end-of-field)
  20832. (save-restriction
  20833. (when (and contents-end
  20834. (> (point-max) contents-end)
  20835. ;; Skip blank lines between elements.
  20836. (< (org-element-property :end element)
  20837. (save-excursion (goto-char contents-end)
  20838. (skip-chars-forward " \r\t\n"))))
  20839. (narrow-to-region (org-element-property :contents-begin element)
  20840. contents-end))
  20841. ;; End of heading is considered as the end of a sentence.
  20842. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20843. (call-interactively #'forward-sentence)))))))
  20844. (defun org-kill-line (&optional _arg)
  20845. "Kill line, to tags or end of line."
  20846. (interactive)
  20847. (cond
  20848. ((or (not org-special-ctrl-k)
  20849. (bolp)
  20850. (not (org-at-heading-p)))
  20851. (when (and (get-char-property (line-end-position) 'invisible)
  20852. org-ctrl-k-protect-subtree
  20853. (or (eq org-ctrl-k-protect-subtree 'error)
  20854. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20855. (user-error
  20856. (substitute-command-keys
  20857. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20858. (call-interactively
  20859. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20860. ((org-match-line org-tag-line-re)
  20861. (let ((end (save-excursion
  20862. (goto-char (match-beginning 1))
  20863. (skip-chars-backward " \t")
  20864. (point))))
  20865. (if (<= end (point)) ;on tags part
  20866. (kill-region (point) (line-end-position))
  20867. (kill-region (point) end)))
  20868. (org-align-tags))
  20869. (t (kill-region (point) (line-end-position)))))
  20870. (defun org-yank (&optional arg)
  20871. "Yank. If the kill is a subtree, treat it specially.
  20872. This command will look at the current kill and check if is a single
  20873. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20874. cursor is at the beginning of a line or after the stars of a currently
  20875. empty headline, then the yank is handled specially. How exactly depends
  20876. on the value of the following variables.
  20877. `org-yank-folded-subtrees'
  20878. By default, this variable is non-nil, which results in
  20879. subtree(s) being folded after insertion, except if doing so
  20880. would swallow text after the yanked text.
  20881. `org-yank-adjusted-subtrees'
  20882. When non-nil (the default value is nil), the subtree will be
  20883. promoted or demoted in order to fit into the local outline tree
  20884. structure, which means that the level will be adjusted so that it
  20885. becomes the smaller one of the two *visible* surrounding headings.
  20886. Any prefix to this command will cause `yank' to be called directly with
  20887. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20888. will just
  20889. plainly yank the text as it is.
  20890. \[1] The test checks if the first non-white line is a heading
  20891. and if there are no other headings with fewer stars."
  20892. (interactive "P")
  20893. (org-yank-generic 'yank arg))
  20894. (defun org-yank-generic (command arg)
  20895. "Perform some yank-like command.
  20896. This function implements the behavior described in the `org-yank'
  20897. documentation. However, it has been generalized to work for any
  20898. interactive command with similar behavior."
  20899. ;; pretend to be command COMMAND
  20900. (setq this-command command)
  20901. (if arg
  20902. (call-interactively command)
  20903. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20904. (and (org-kill-is-subtree-p)
  20905. (or (bolp)
  20906. (and (looking-at "[ \t]*$")
  20907. (string-match
  20908. "\\`\\*+\\'"
  20909. (buffer-substring (point-at-bol) (point)))))))
  20910. swallowp)
  20911. (cond
  20912. ((and subtreep org-yank-folded-subtrees)
  20913. (let ((beg (point))
  20914. end)
  20915. (if (and subtreep org-yank-adjusted-subtrees)
  20916. (org-paste-subtree nil nil 'for-yank)
  20917. (call-interactively command))
  20918. (setq end (point))
  20919. (goto-char beg)
  20920. (when (and (bolp) subtreep
  20921. (not (setq swallowp
  20922. (org-yank-folding-would-swallow-text beg end))))
  20923. (org-with-limited-levels
  20924. (or (looking-at org-outline-regexp)
  20925. (re-search-forward org-outline-regexp-bol end t))
  20926. (while (and (< (point) end) (looking-at org-outline-regexp))
  20927. (outline-hide-subtree)
  20928. (org-cycle-show-empty-lines 'folded)
  20929. (condition-case nil
  20930. (outline-forward-same-level 1)
  20931. (error (goto-char end))))))
  20932. (when swallowp
  20933. (message
  20934. "Inserted text not folded because that would swallow text"))
  20935. (goto-char end)
  20936. (skip-chars-forward " \t\n\r")
  20937. (beginning-of-line 1)
  20938. (push-mark beg 'nomsg)))
  20939. ((and subtreep org-yank-adjusted-subtrees)
  20940. (let ((beg (point-at-bol)))
  20941. (org-paste-subtree nil nil 'for-yank)
  20942. (push-mark beg 'nomsg)))
  20943. (t
  20944. (call-interactively command))))))
  20945. (defun org-yank-folding-would-swallow-text (beg end)
  20946. "Would hide-subtree at BEG swallow any text after END?"
  20947. (let (level)
  20948. (org-with-limited-levels
  20949. (save-excursion
  20950. (goto-char beg)
  20951. (when (or (looking-at org-outline-regexp)
  20952. (re-search-forward org-outline-regexp-bol end t))
  20953. (setq level (org-outline-level)))
  20954. (goto-char end)
  20955. (skip-chars-forward " \t\r\n\v\f")
  20956. (not (or (eobp)
  20957. (and (bolp) (looking-at-p org-outline-regexp)
  20958. (<= (org-outline-level) level))))))))
  20959. (defun org-back-to-heading (&optional invisible-ok)
  20960. "Call `outline-back-to-heading', but provide a better error message."
  20961. (condition-case nil
  20962. (outline-back-to-heading invisible-ok)
  20963. (error (error "Before first headline at position %d in buffer %s"
  20964. (point) (current-buffer)))))
  20965. (defun org-before-first-heading-p ()
  20966. "Before first heading?"
  20967. (org-with-limited-levels
  20968. (save-excursion
  20969. (end-of-line)
  20970. (null (re-search-backward org-outline-regexp-bol nil t)))))
  20971. (defun org-at-heading-p (&optional _)
  20972. "Non-nil when on a headline."
  20973. (outline-on-heading-p t))
  20974. (defun org-in-commented-heading-p (&optional no-inheritance)
  20975. "Non-nil if point is under a commented heading.
  20976. This function also checks ancestors of the current headline,
  20977. unless optional argument NO-INHERITANCE is non-nil."
  20978. (cond
  20979. ((org-before-first-heading-p) nil)
  20980. ((let ((headline (nth 4 (org-heading-components))))
  20981. (and headline
  20982. (let ((case-fold-search nil))
  20983. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  20984. headline)))))
  20985. (no-inheritance nil)
  20986. (t
  20987. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  20988. (defun org-at-comment-p nil
  20989. "Is cursor in a commented line?"
  20990. (save-excursion
  20991. (save-match-data
  20992. (beginning-of-line)
  20993. (looking-at "^[ \t]*# "))))
  20994. (defun org-at-drawer-p nil
  20995. "Is cursor at a drawer keyword?"
  20996. (save-excursion
  20997. (move-beginning-of-line 1)
  20998. (looking-at org-drawer-regexp)))
  20999. (defun org-at-block-p nil
  21000. "Is cursor at a block keyword?"
  21001. (save-excursion
  21002. (move-beginning-of-line 1)
  21003. (looking-at org-block-regexp)))
  21004. (defun org-point-at-end-of-empty-headline ()
  21005. "If point is at the end of an empty headline, return t, else nil.
  21006. If the heading only contains a TODO keyword, it is still still considered
  21007. empty."
  21008. (let ((case-fold-search nil))
  21009. (and (looking-at "[ \t]*$")
  21010. org-todo-line-regexp
  21011. (save-excursion
  21012. (beginning-of-line)
  21013. (looking-at org-todo-line-regexp)
  21014. (string= (match-string 3) "")))))
  21015. (defun org-at-heading-or-item-p ()
  21016. (or (org-at-heading-p) (org-at-item-p)))
  21017. (defun org-at-target-p ()
  21018. (or (org-in-regexp org-radio-target-regexp)
  21019. (org-in-regexp org-target-regexp)))
  21020. (defun org-up-heading-all (arg)
  21021. "Move to the heading line of which the present line is a subheading.
  21022. This function considers both visible and invisible heading lines.
  21023. With argument, move up ARG levels."
  21024. (outline-up-heading arg t))
  21025. (defun org-up-heading-safe ()
  21026. "Move to the heading line of which the present line is a subheading.
  21027. This version will not throw an error. It will return the level of the
  21028. headline found, or nil if no higher level is found.
  21029. Also, this function will be a lot faster than `outline-up-heading',
  21030. because it relies on stars being the outline starters. This can really
  21031. make a significant difference in outlines with very many siblings."
  21032. (when (ignore-errors (org-back-to-heading t))
  21033. (let ((level-up (1- (funcall outline-level))))
  21034. (and (> level-up 0)
  21035. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21036. (funcall outline-level)))))
  21037. (defun org-first-sibling-p ()
  21038. "Is this heading the first child of its parents?"
  21039. (interactive)
  21040. (let ((re org-outline-regexp-bol)
  21041. level l)
  21042. (unless (org-at-heading-p t)
  21043. (user-error "Not at a heading"))
  21044. (setq level (funcall outline-level))
  21045. (save-excursion
  21046. (if (not (re-search-backward re nil t))
  21047. t
  21048. (setq l (funcall outline-level))
  21049. (< l level)))))
  21050. (defun org-goto-sibling (&optional previous)
  21051. "Goto the next sibling, even if it is invisible.
  21052. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21053. when a sibling was found. When none is found, return nil and don't
  21054. move point."
  21055. (let ((fun (if previous 're-search-backward 're-search-forward))
  21056. (pos (point))
  21057. (re org-outline-regexp-bol)
  21058. level l)
  21059. (when (ignore-errors (org-back-to-heading t))
  21060. (setq level (funcall outline-level))
  21061. (catch 'exit
  21062. (or previous (forward-char 1))
  21063. (while (funcall fun re nil t)
  21064. (setq l (funcall outline-level))
  21065. (when (< l level) (goto-char pos) (throw 'exit nil))
  21066. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21067. (goto-char pos)
  21068. nil))))
  21069. (defun org-show-siblings ()
  21070. "Show all siblings of the current headline."
  21071. (save-excursion
  21072. (while (org-goto-sibling) (org-flag-heading nil)))
  21073. (save-excursion
  21074. (while (org-goto-sibling 'previous)
  21075. (org-flag-heading nil))))
  21076. (defun org-goto-first-child ()
  21077. "Goto the first child, even if it is invisible.
  21078. Return t when a child was found. Otherwise don't move point and
  21079. return nil."
  21080. (let (level (pos (point)) (re org-outline-regexp-bol))
  21081. (when (ignore-errors (org-back-to-heading t))
  21082. (setq level (outline-level))
  21083. (forward-char 1)
  21084. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21085. (progn (goto-char (match-beginning 0)) t)
  21086. (goto-char pos) nil))))
  21087. (defun org-show-hidden-entry ()
  21088. "Show an entry where even the heading is hidden."
  21089. (save-excursion
  21090. (org-show-entry)))
  21091. (defun org-flag-heading (flag &optional entry)
  21092. "Flag the current heading. FLAG non-nil means make invisible.
  21093. When ENTRY is non-nil, show the entire entry."
  21094. (save-excursion
  21095. (org-back-to-heading t)
  21096. ;; Check if we should show the entire entry
  21097. (if (not entry)
  21098. (org-flag-region
  21099. (line-end-position 0) (line-end-position) flag 'outline)
  21100. (org-show-entry)
  21101. (save-excursion
  21102. (and (outline-next-heading)
  21103. (org-flag-heading nil))))))
  21104. (defun org-get-next-sibling ()
  21105. "Move to next heading of the same level, and return point.
  21106. If there is no such heading, return nil.
  21107. This is like outline-next-sibling, but invisible headings are ok."
  21108. (let ((level (funcall outline-level)))
  21109. (outline-next-heading)
  21110. (while (and (not (eobp)) (> (funcall outline-level) level))
  21111. (outline-next-heading))
  21112. (unless (or (eobp) (< (funcall outline-level) level))
  21113. (point))))
  21114. (defun org-get-last-sibling ()
  21115. "Move to previous heading of the same level, and return point.
  21116. If there is no such heading, return nil."
  21117. (let ((opoint (point))
  21118. (level (funcall outline-level)))
  21119. (outline-previous-heading)
  21120. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21121. (while (and (> (funcall outline-level) level)
  21122. (not (bobp)))
  21123. (outline-previous-heading))
  21124. (unless (< (funcall outline-level) level)
  21125. (point)))))
  21126. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21127. "Goto to the end of a subtree."
  21128. ;; This contains an exact copy of the original function, but it uses
  21129. ;; `org-back-to-heading', to make it work also in invisible
  21130. ;; trees. And is uses an invisible-ok argument.
  21131. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21132. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21133. ;; with many children and grandchildren etc, this can be much faster
  21134. ;; than the outline version.
  21135. (org-back-to-heading invisible-ok)
  21136. (let ((first t)
  21137. (level (funcall outline-level)))
  21138. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21139. ;; A true heading (not a plain list item), in Org
  21140. ;; This means we can easily find the end by looking
  21141. ;; only for the right number of stars. Using a regexp to do
  21142. ;; this is so much faster than using a Lisp loop.
  21143. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21144. (forward-char 1)
  21145. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21146. ;; something else, do it the slow way
  21147. (while (and (not (eobp))
  21148. (or first (> (funcall outline-level) level)))
  21149. (setq first nil)
  21150. (outline-next-heading)))
  21151. (unless to-heading
  21152. (when (memq (preceding-char) '(?\n ?\^M))
  21153. ;; Go to end of line before heading
  21154. (forward-char -1)
  21155. (when (memq (preceding-char) '(?\n ?\^M))
  21156. ;; leave blank line before heading
  21157. (forward-char -1)))))
  21158. (point))
  21159. (defun org-end-of-meta-data (&optional full)
  21160. "Skip planning line and properties drawer in current entry.
  21161. When optional argument FULL is non-nil, also skip empty lines,
  21162. clocking lines and regular drawers at the beginning of the
  21163. entry."
  21164. (org-back-to-heading t)
  21165. (forward-line)
  21166. (when (looking-at-p org-planning-line-re) (forward-line))
  21167. (when (looking-at org-property-drawer-re)
  21168. (goto-char (match-end 0))
  21169. (forward-line))
  21170. (when (and full (not (org-at-heading-p)))
  21171. (catch 'exit
  21172. (let ((end (save-excursion (outline-next-heading) (point)))
  21173. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21174. (while (not (eobp))
  21175. (cond ((looking-at-p org-drawer-regexp)
  21176. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21177. (forward-line)
  21178. (throw 'exit t)))
  21179. ((looking-at-p re) (forward-line))
  21180. (t (throw 'exit t))))))))
  21181. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21182. "Move forward to the ARG'th subheading at same level as this one.
  21183. Stop at the first and last subheadings of a superior heading.
  21184. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21185. non-nil it will also look at invisible ones."
  21186. (interactive "p")
  21187. (let ((backward? (and arg (< arg 0))))
  21188. (if (org-before-first-heading-p)
  21189. (if backward? (goto-char (point-min)) (outline-next-heading))
  21190. (org-back-to-heading invisible-ok)
  21191. (unless backward? (end-of-line)) ;do not match current headline
  21192. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21193. (f (if backward? #'re-search-backward #'re-search-forward))
  21194. (count (if arg (abs arg) 1))
  21195. (result (point)))
  21196. (while (and (> count 0)
  21197. (funcall f org-outline-regexp-bol nil 'move))
  21198. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21199. (cond ((< l level) (setq count 0))
  21200. ((and (= l level)
  21201. (or invisible-ok
  21202. (not (org-invisible-p
  21203. (line-beginning-position)))))
  21204. (cl-decf count)
  21205. (when (= l level) (setq result (point)))))))
  21206. (goto-char result))
  21207. (beginning-of-line))))
  21208. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21209. "Move backward to the ARG'th subheading at same level as this one.
  21210. Stop at the first and last subheadings of a superior heading."
  21211. (interactive "p")
  21212. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21213. (defun org-next-visible-heading (arg)
  21214. "Move to the next visible heading.
  21215. This function wraps `outline-next-visible-heading' with
  21216. `org-with-limited-levels' in order to skip over inline tasks and
  21217. respect customization of `org-odd-levels-only'."
  21218. (interactive "p")
  21219. (org-with-limited-levels
  21220. (outline-next-visible-heading arg)))
  21221. (defun org-previous-visible-heading (arg)
  21222. "Move to the previous visible heading.
  21223. This function wraps `outline-previous-visible-heading' with
  21224. `org-with-limited-levels' in order to skip over inline tasks and
  21225. respect customization of `org-odd-levels-only'."
  21226. (interactive "p")
  21227. (org-with-limited-levels
  21228. (outline-previous-visible-heading arg)))
  21229. (defun org-forward-paragraph ()
  21230. "Move forward to beginning of next paragraph or equivalent.
  21231. The function moves point to the beginning of the next visible
  21232. structural element, which can be a paragraph, a table, a list
  21233. item, etc. It also provides some special moves for convenience:
  21234. - On an affiliated keyword, jump to the beginning of the
  21235. relative element.
  21236. - On an item or a footnote definition, move to the second
  21237. element inside, if any.
  21238. - On a table or a property drawer, jump after it.
  21239. - On a verse or source block, stop after blank lines."
  21240. (interactive)
  21241. (unless (eobp)
  21242. (let* ((deactivate-mark nil)
  21243. (element (org-element-at-point))
  21244. (type (org-element-type element))
  21245. (post-affiliated (org-element-property :post-affiliated element))
  21246. (contents-begin (org-element-property :contents-begin element))
  21247. (contents-end (org-element-property :contents-end element))
  21248. (end (let ((end (org-element-property :end element)) (parent element))
  21249. (while (and (setq parent (org-element-property :parent parent))
  21250. (= (org-element-property :contents-end parent) end))
  21251. (setq end (org-element-property :end parent)))
  21252. end)))
  21253. (cond ((not element)
  21254. (skip-chars-forward " \r\t\n")
  21255. (or (eobp) (beginning-of-line)))
  21256. ;; On affiliated keywords, move to element's beginning.
  21257. ((< (point) post-affiliated)
  21258. (goto-char post-affiliated))
  21259. ;; At a table row, move to the end of the table. Similarly,
  21260. ;; at a node property, move to the end of the property
  21261. ;; drawer.
  21262. ((memq type '(node-property table-row))
  21263. (goto-char (org-element-property
  21264. :end (org-element-property :parent element))))
  21265. ((memq type '(property-drawer table)) (goto-char end))
  21266. ;; Consider blank lines as separators in verse and source
  21267. ;; blocks to ease editing.
  21268. ((memq type '(src-block verse-block))
  21269. (when (eq type 'src-block)
  21270. (setq contents-end
  21271. (save-excursion (goto-char end)
  21272. (skip-chars-backward " \r\t\n")
  21273. (line-beginning-position))))
  21274. (beginning-of-line)
  21275. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21276. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21277. (goto-char end)
  21278. (skip-chars-forward " \r\t\n")
  21279. (if (= (point) contents-end) (goto-char end)
  21280. (beginning-of-line))))
  21281. ;; With no contents, just skip element.
  21282. ((not contents-begin) (goto-char end))
  21283. ;; If contents are invisible, skip the element altogether.
  21284. ((org-invisible-p (line-end-position))
  21285. (cl-case type
  21286. (headline
  21287. (org-with-limited-levels (outline-next-visible-heading 1)))
  21288. ;; At a plain list, make sure we move to the next item
  21289. ;; instead of skipping the whole list.
  21290. (plain-list (forward-char)
  21291. (org-forward-paragraph))
  21292. (otherwise (goto-char end))))
  21293. ((>= (point) contents-end) (goto-char end))
  21294. ((>= (point) contents-begin)
  21295. ;; This can only happen on paragraphs and plain lists.
  21296. (cl-case type
  21297. (paragraph (goto-char end))
  21298. ;; At a plain list, try to move to second element in
  21299. ;; first item, if possible.
  21300. (plain-list (end-of-line)
  21301. (org-forward-paragraph))))
  21302. ;; When contents start on the middle of a line (e.g. in
  21303. ;; items and footnote definitions), try to reach first
  21304. ;; element starting after current line.
  21305. ((> (line-end-position) contents-begin)
  21306. (end-of-line)
  21307. (org-forward-paragraph))
  21308. (t (goto-char contents-begin))))))
  21309. (defun org-backward-paragraph ()
  21310. "Move backward to start of previous paragraph or equivalent.
  21311. The function moves point to the beginning of the current
  21312. structural element, which can be a paragraph, a table, a list
  21313. item, etc., or to the beginning of the previous visible one if
  21314. point is already there. It also provides some special moves for
  21315. convenience:
  21316. - On an affiliated keyword, jump to the first one.
  21317. - On a table or a property drawer, move to its beginning.
  21318. - On comment, example, export, src and verse blocks, stop
  21319. before blank lines."
  21320. (interactive)
  21321. (unless (bobp)
  21322. (let* ((deactivate-mark nil)
  21323. (element (org-element-at-point))
  21324. (type (org-element-type element))
  21325. (contents-end (org-element-property :contents-end element))
  21326. (post-affiliated (org-element-property :post-affiliated element))
  21327. (begin (org-element-property :begin element))
  21328. (special? ;blocks handled specially
  21329. (memq type '(comment-block example-block export-block src-block
  21330. verse-block)))
  21331. (contents-begin
  21332. (if special?
  21333. ;; These types have no proper contents. Fake line
  21334. ;; below the block opening line as contents beginning.
  21335. (save-excursion (goto-char begin) (line-beginning-position 2))
  21336. (org-element-property :contents-begin element))))
  21337. (cond
  21338. ((not element) (goto-char (point-min)))
  21339. ((= (point) begin)
  21340. (backward-char)
  21341. (org-backward-paragraph))
  21342. ((<= (point) post-affiliated) (goto-char begin))
  21343. ;; Special behavior: on a table or a property drawer, move to
  21344. ;; its beginning.
  21345. ((memq type '(node-property table-row))
  21346. (goto-char (org-element-property
  21347. :post-affiliated (org-element-property :parent element))))
  21348. (special?
  21349. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21350. ;; Inside a verse block, see blank lines as paragraph
  21351. ;; separators.
  21352. (let ((origin (point)))
  21353. (skip-chars-backward " \r\t\n" contents-begin)
  21354. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21355. (skip-chars-forward " \r\t\n" origin)
  21356. (if (= (point) origin) (goto-char contents-begin)
  21357. (beginning-of-line))))))
  21358. ((eq type 'paragraph) (goto-char contents-begin)
  21359. ;; When at first paragraph in an item or a footnote definition,
  21360. ;; move directly to beginning of line.
  21361. (let ((parent-contents
  21362. (org-element-property
  21363. :contents-begin (org-element-property :parent element))))
  21364. (when (and parent-contents (= parent-contents contents-begin))
  21365. (beginning-of-line))))
  21366. ;; At the end of a greater element, move to the beginning of
  21367. ;; the last element within.
  21368. ((and contents-end (>= (point) contents-end))
  21369. (goto-char (1- contents-end))
  21370. (org-backward-paragraph))
  21371. (t (goto-char (or post-affiliated begin))))
  21372. ;; Ensure we never leave point invisible.
  21373. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21374. (defun org-forward-element ()
  21375. "Move forward by one element.
  21376. Move to the next element at the same level, when possible."
  21377. (interactive)
  21378. (cond ((eobp) (user-error "Cannot move further down"))
  21379. ((org-with-limited-levels (org-at-heading-p))
  21380. (let ((origin (point)))
  21381. (goto-char (org-end-of-subtree nil t))
  21382. (unless (org-with-limited-levels (org-at-heading-p))
  21383. (goto-char origin)
  21384. (user-error "Cannot move further down"))))
  21385. (t
  21386. (let* ((elem (org-element-at-point))
  21387. (end (org-element-property :end elem))
  21388. (parent (org-element-property :parent elem)))
  21389. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21390. (goto-char (org-element-property :end parent)))
  21391. ((integer-or-marker-p end) (goto-char end))
  21392. (t (message "No element at point")))))))
  21393. (defun org-backward-element ()
  21394. "Move backward by one element.
  21395. Move to the previous element at the same level, when possible."
  21396. (interactive)
  21397. (cond ((bobp) (user-error "Cannot move further up"))
  21398. ((org-with-limited-levels (org-at-heading-p))
  21399. ;; At a headline, move to the previous one, if any, or stay
  21400. ;; here.
  21401. (let ((origin (point)))
  21402. (org-with-limited-levels (org-backward-heading-same-level 1))
  21403. ;; When current headline has no sibling above, move to its
  21404. ;; parent.
  21405. (when (= (point) origin)
  21406. (or (org-with-limited-levels (org-up-heading-safe))
  21407. (progn (goto-char origin)
  21408. (user-error "Cannot move further up"))))))
  21409. (t
  21410. (let* ((elem (org-element-at-point))
  21411. (beg (org-element-property :begin elem)))
  21412. (cond
  21413. ;; Move to beginning of current element if point isn't
  21414. ;; there already.
  21415. ((null beg) (message "No element at point"))
  21416. ((/= (point) beg) (goto-char beg))
  21417. (t (goto-char beg)
  21418. (skip-chars-backward " \r\t\n")
  21419. (unless (bobp)
  21420. (let ((prev (org-element-at-point)))
  21421. (goto-char (org-element-property :begin prev))
  21422. (while (and (setq prev (org-element-property :parent prev))
  21423. (<= (org-element-property :end prev) beg))
  21424. (goto-char (org-element-property :begin prev)))))))))))
  21425. (defun org-up-element ()
  21426. "Move to upper element."
  21427. (interactive)
  21428. (if (org-with-limited-levels (org-at-heading-p))
  21429. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21430. (let* ((elem (org-element-at-point))
  21431. (parent (org-element-property :parent elem)))
  21432. (if parent (goto-char (org-element-property :begin parent))
  21433. (if (org-with-limited-levels (org-before-first-heading-p))
  21434. (user-error "No surrounding element")
  21435. (org-with-limited-levels (org-back-to-heading)))))))
  21436. (defun org-down-element ()
  21437. "Move to inner element."
  21438. (interactive)
  21439. (let ((element (org-element-at-point)))
  21440. (cond
  21441. ((memq (org-element-type element) '(plain-list table))
  21442. (goto-char (org-element-property :contents-begin element))
  21443. (forward-char))
  21444. ((memq (org-element-type element) org-element-greater-elements)
  21445. ;; If contents are hidden, first disclose them.
  21446. (when (org-invisible-p (line-end-position)) (org-cycle))
  21447. (goto-char (or (org-element-property :contents-begin element)
  21448. (user-error "No content for this element"))))
  21449. (t (user-error "No inner element")))))
  21450. (defun org-drag-element-backward ()
  21451. "Move backward element at point."
  21452. (interactive)
  21453. (let ((elem (or (org-element-at-point)
  21454. (user-error "No element at point"))))
  21455. (if (eq (org-element-type elem) 'headline)
  21456. ;; Preserve point when moving a whole tree, even if point was
  21457. ;; on blank lines below the headline.
  21458. (let ((offset (skip-chars-backward " \t\n")))
  21459. (unwind-protect (org-move-subtree-up)
  21460. (forward-char (- offset))))
  21461. (let ((prev-elem
  21462. (save-excursion
  21463. (goto-char (org-element-property :begin elem))
  21464. (skip-chars-backward " \r\t\n")
  21465. (unless (bobp)
  21466. (let* ((beg (org-element-property :begin elem))
  21467. (prev (org-element-at-point))
  21468. (up prev))
  21469. (while (and (setq up (org-element-property :parent up))
  21470. (<= (org-element-property :end up) beg))
  21471. (setq prev up))
  21472. prev)))))
  21473. ;; Error out if no previous element or previous element is
  21474. ;; a parent of the current one.
  21475. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21476. (user-error "Cannot drag element backward")
  21477. (let ((pos (point)))
  21478. (org-element-swap-A-B prev-elem elem)
  21479. (goto-char (+ (org-element-property :begin prev-elem)
  21480. (- pos (org-element-property :begin elem))))))))))
  21481. (defun org-drag-element-forward ()
  21482. "Move forward element at point."
  21483. (interactive)
  21484. (let* ((pos (point))
  21485. (elem (or (org-element-at-point)
  21486. (user-error "No element at point"))))
  21487. (when (= (point-max) (org-element-property :end elem))
  21488. (user-error "Cannot drag element forward"))
  21489. (goto-char (org-element-property :end elem))
  21490. (let ((next-elem (org-element-at-point)))
  21491. (when (or (org-element-nested-p elem next-elem)
  21492. (and (eq (org-element-type next-elem) 'headline)
  21493. (not (eq (org-element-type elem) 'headline))))
  21494. (goto-char pos)
  21495. (user-error "Cannot drag element forward"))
  21496. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21497. ;; body's length (without final blanks) and by the length of
  21498. ;; blanks between ELEM and NEXT-ELEM.
  21499. (let ((size-next (- (save-excursion
  21500. (goto-char (org-element-property :end next-elem))
  21501. (skip-chars-backward " \r\t\n")
  21502. (forward-line)
  21503. ;; Small correction if buffer doesn't end
  21504. ;; with a newline character.
  21505. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21506. (org-element-property :begin next-elem)))
  21507. (size-blank (- (org-element-property :end elem)
  21508. (save-excursion
  21509. (goto-char (org-element-property :end elem))
  21510. (skip-chars-backward " \r\t\n")
  21511. (forward-line)
  21512. (point)))))
  21513. (org-element-swap-A-B elem next-elem)
  21514. (goto-char (+ pos size-next size-blank))))))
  21515. (defun org-drag-line-forward (arg)
  21516. "Drag the line at point ARG lines forward."
  21517. (interactive "p")
  21518. (dotimes (_ (abs arg))
  21519. (let ((c (current-column)))
  21520. (if (< 0 arg)
  21521. (progn
  21522. (beginning-of-line 2)
  21523. (transpose-lines 1)
  21524. (beginning-of-line 0))
  21525. (transpose-lines 1)
  21526. (beginning-of-line -1))
  21527. (org-move-to-column c))))
  21528. (defun org-drag-line-backward (arg)
  21529. "Drag the line at point ARG lines backward."
  21530. (interactive "p")
  21531. (org-drag-line-forward (- arg)))
  21532. (defun org-mark-element ()
  21533. "Put point at beginning of this element, mark at end.
  21534. Interactively, if this command is repeated or (in Transient Mark
  21535. mode) if the mark is active, it marks the next element after the
  21536. ones already marked."
  21537. (interactive)
  21538. (let (deactivate-mark)
  21539. (if (and (called-interactively-p 'any)
  21540. (or (and (eq last-command this-command) (mark t))
  21541. (and transient-mark-mode mark-active)))
  21542. (set-mark
  21543. (save-excursion
  21544. (goto-char (mark))
  21545. (goto-char (org-element-property :end (org-element-at-point)))))
  21546. (let ((element (org-element-at-point)))
  21547. (end-of-line)
  21548. (push-mark (org-element-property :end element) t t)
  21549. (goto-char (org-element-property :begin element))))))
  21550. (defun org-narrow-to-element ()
  21551. "Narrow buffer to current element."
  21552. (interactive)
  21553. (let ((elem (org-element-at-point)))
  21554. (cond
  21555. ((eq (car elem) 'headline)
  21556. (narrow-to-region
  21557. (org-element-property :begin elem)
  21558. (org-element-property :end elem)))
  21559. ((memq (car elem) org-element-greater-elements)
  21560. (narrow-to-region
  21561. (org-element-property :contents-begin elem)
  21562. (org-element-property :contents-end elem)))
  21563. (t
  21564. (narrow-to-region
  21565. (org-element-property :begin elem)
  21566. (org-element-property :end elem))))))
  21567. (defun org-transpose-element ()
  21568. "Transpose current and previous elements, keeping blank lines between.
  21569. Point is moved after both elements."
  21570. (interactive)
  21571. (org-skip-whitespace)
  21572. (let ((end (org-element-property :end (org-element-at-point))))
  21573. (org-drag-element-backward)
  21574. (goto-char end)))
  21575. (defun org-unindent-buffer ()
  21576. "Un-indent the visible part of the buffer.
  21577. Relative indentation (between items, inside blocks, etc.) isn't
  21578. modified."
  21579. (interactive)
  21580. (unless (eq major-mode 'org-mode)
  21581. (user-error "Cannot un-indent a buffer not in Org mode"))
  21582. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21583. (unindent-tree
  21584. (lambda (contents)
  21585. (dolist (element (reverse contents))
  21586. (if (memq (org-element-type element) '(headline section))
  21587. (funcall unindent-tree (org-element-contents element))
  21588. (save-excursion
  21589. (save-restriction
  21590. (narrow-to-region
  21591. (org-element-property :begin element)
  21592. (org-element-property :end element))
  21593. (org-do-remove-indentation))))))))
  21594. (funcall unindent-tree (org-element-contents parse-tree))))
  21595. (defun org-make-options-regexp (kwds &optional extra)
  21596. "Make a regular expression for keyword lines.
  21597. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21598. when non-nil, is a regexp matching keywords names."
  21599. (concat "^[ \t]*#\\+\\("
  21600. (regexp-opt kwds)
  21601. (and extra (concat (and kwds "\\|") extra))
  21602. "\\):[ \t]*\\(.*\\)"))
  21603. ;;; Conveniently switch to Info nodes
  21604. (defun org-info-find-node (&optional nodename)
  21605. "Find Info documentation NODENAME or Org documentation according context.
  21606. Started from `gnus-info-find-node'."
  21607. (interactive)
  21608. (Info-goto-node
  21609. (or nodename
  21610. (let ((default-org-info-node "(org) Top"))
  21611. (cond
  21612. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  21613. ((eq 'org-mode major-mode)
  21614. (let* ((context (org-element-at-point))
  21615. (element-info-nodes ; compare to `org-element-all-elements'.
  21616. `((babel-call . "(org) Evaluating Code Blocks")
  21617. (center-block . "(org) Paragraphs")
  21618. (clock . ,default-org-info-node)
  21619. (comment . "(org) Comment Lines")
  21620. (comment-block . "(org) Comment Lines")
  21621. (diary-sexp . ,default-org-info-node)
  21622. (drawer . "(org) Drawers")
  21623. (dynamic-block . "(org) Dynamic Blocks")
  21624. (example-block . "(org) Literal Examples")
  21625. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  21626. (fixed-width . ,default-org-info-node)
  21627. (footnote-definition . "(org) Creating Footnotes")
  21628. (headline . "(org) Document Structure")
  21629. (horizontal-rule . "(org) Built-in Table Editor")
  21630. (inlinetask . ,default-org-info-node)
  21631. (item . "(org) Plain Lists")
  21632. (keyword . "(org) Per-file keywords")
  21633. (latex-environment . "(org) LaTeX Export")
  21634. (node-property . "(org) Properties and Columns")
  21635. (paragraph . "(org) Paragraphs")
  21636. (plain-list . "(org) Plain Lists")
  21637. (planning . "(org) Deadlines and Scheduling")
  21638. (property-drawer . "(org) Properties and Columns")
  21639. (quote-block . "(org) Paragraphs")
  21640. (section . ,default-org-info-node)
  21641. (special-block . ,default-org-info-node)
  21642. (src-block . "(org) Working with Source Code")
  21643. (table . "(org) Tables")
  21644. (table-row . "(org) Tables")
  21645. (verse-block . "(org) Paragraphs"))))
  21646. (or (cdr (assoc (car context) element-info-nodes))
  21647. default-org-info-node)))
  21648. (t default-org-info-node))))))
  21649. ;;; Finish up
  21650. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21651. (lambda () (add-hook 'change-major-mode-hook
  21652. 'org-show-all 'append 'local)))
  21653. (provide 'org)
  21654. (run-hooks 'org-load-hook)
  21655. ;;; org.el ends here