org.el 896 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655
  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. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; https://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; https://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. (defvar org-inlinetask-min-level)
  66. ;;;; Require other packages
  67. (require 'cl-lib)
  68. (eval-when-compile (require 'gnus-sum))
  69. (require 'calendar)
  70. (require 'find-func)
  71. (require 'format-spec)
  72. (or (eq this-command 'eval-buffer)
  73. (condition-case nil
  74. (load (concat (file-name-directory load-file-name)
  75. "org-loaddefs.el")
  76. nil t t t)
  77. (error
  78. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  79. (sit-for 3)
  80. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  81. (sit-for 3))))
  82. (require 'org-macs)
  83. (require 'org-compat)
  84. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  85. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  86. (defvar org-outline-regexp "\\*+ "
  87. "Regexp to match Org headlines.")
  88. (defvar org-outline-regexp-bol "^\\*+ "
  89. "Regexp to match Org headlines.
  90. This is similar to `org-outline-regexp' but additionally makes
  91. sure that we are at the beginning of the line.")
  92. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  93. "Matches a headline, putting stars and text into groups.
  94. Stars are put in group 1 and the trimmed body in group 2.")
  95. (declare-function calendar-check-holidays "holidays" (date))
  96. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  97. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  98. (declare-function org-add-archive-files "org-archive" (files))
  99. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  100. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  101. (declare-function org-agenda-redo "org-agenda" (&optional all))
  102. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  103. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  104. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  105. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  106. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  107. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  108. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  109. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  110. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  111. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  112. (declare-function org-clock-update-time-maybe "org-clock" ())
  113. (declare-function org-clocking-buffer "org-clock" ())
  114. (declare-function org-clocktable-shift "org-clock" (dir n))
  115. (declare-function
  116. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  117. (declare-function org-element-at-point "org-element" ())
  118. (declare-function org-element-cache-refresh "org-element" (pos))
  119. (declare-function org-element-cache-reset "org-element" (&optional all))
  120. (declare-function org-element-contents "org-element" (element))
  121. (declare-function org-element-context "org-element" (&optional element))
  122. (declare-function org-element-copy "org-element" (datum))
  123. (declare-function org-element-interpret-data "org-element" (data))
  124. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  125. (declare-function org-element-link-parser "org-element" ())
  126. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  127. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  128. (declare-function org-element-property "org-element" (property element))
  129. (declare-function org-element-put-property "org-element" (element property value))
  130. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  131. (declare-function org-element-type "org-element" (element))
  132. (declare-function org-element-update-syntax "org-element" ())
  133. (declare-function org-id-find-id-file "org-id" (id))
  134. (declare-function org-id-get-create "org-id" (&optional force))
  135. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  136. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  137. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  138. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  139. (declare-function org-table-align "org-table" ())
  140. (declare-function org-table-begin "org-table" (&optional table-type))
  141. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  142. (declare-function org-table-blank-field "org-table" ())
  143. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  144. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  145. (declare-function org-table-cut-region "org-table" (beg end))
  146. (declare-function org-table-edit-field "org-table" (arg))
  147. (declare-function org-table-end "org-table" (&optional table-type))
  148. (declare-function org-table-end-of-field "org-table" (&optional n))
  149. (declare-function org-table-insert-row "org-table" (&optional arg))
  150. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  151. (declare-function org-table-maybe-eval-formula "org-table" ())
  152. (declare-function org-table-maybe-recalculate-line "org-table" ())
  153. (declare-function org-table-next-row "org-table" ())
  154. (declare-function org-table-paste-rectangle "org-table" ())
  155. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  156. (declare-function
  157. org-table-sort-lines "org-table"
  158. (&optional with-case sorting-type getkey-func compare-func interactive?))
  159. (declare-function org-table-shrink "org-table" (&optional begin end))
  160. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  161. (declare-function org-table-wrap-region "org-table" (arg))
  162. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  163. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  164. (declare-function orgtbl-mode "org-table" (&optional arg))
  165. (declare-function org-export-get-backend "ox" (name))
  166. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  167. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  168. (defvar ffap-url-regexp)
  169. (defvar org-element-paragraph-separate)
  170. ;; load languages based on value of `org-babel-load-languages'
  171. (defvar org-babel-load-languages)
  172. ;;;###autoload
  173. (defun org-babel-do-load-languages (sym value)
  174. "Load the languages defined in `org-babel-load-languages'."
  175. (set-default sym value)
  176. (dolist (pair org-babel-load-languages)
  177. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  178. (if active
  179. (require (intern (concat "ob-" lang)))
  180. (funcall 'fmakunbound
  181. (intern (concat "org-babel-execute:" lang)))
  182. (funcall 'fmakunbound
  183. (intern (concat "org-babel-expand-body:" lang)))))))
  184. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  185. ;;;###autoload
  186. (defun org-babel-load-file (file &optional compile)
  187. "Load Emacs Lisp source code blocks in the Org FILE.
  188. This function exports the source code using `org-babel-tangle'
  189. and then loads the resulting file using `load-file'. With prefix
  190. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  191. file to byte-code before it is loaded."
  192. (interactive "fFile to load: \nP")
  193. (let* ((age (lambda (file)
  194. (float-time
  195. (time-subtract (current-time)
  196. (nth 5 (or (file-attributes (file-truename file))
  197. (file-attributes file)))))))
  198. (base-name (file-name-sans-extension file))
  199. (exported-file (concat base-name ".el")))
  200. ;; tangle if the Org file is newer than the elisp file
  201. (unless (and (file-exists-p exported-file)
  202. (> (funcall age file) (funcall age exported-file)))
  203. ;; Tangle-file traversal returns reversed list of tangled files
  204. ;; and we want to evaluate the first target.
  205. (setq exported-file
  206. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  207. (message "%s %s"
  208. (if compile
  209. (progn (byte-compile-file exported-file 'load)
  210. "Compiled and loaded")
  211. (progn (load-file exported-file) "Loaded"))
  212. exported-file)))
  213. (defcustom org-babel-load-languages '((emacs-lisp . t))
  214. "Languages which can be evaluated in Org buffers.
  215. This list can be used to load support for any of the languages
  216. below, note that each language will depend on a different set of
  217. system executables and/or Emacs modes. When a language is
  218. \"loaded\", then code blocks in that language can be evaluated
  219. with `org-babel-execute-src-block' bound by default to C-c
  220. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  221. be set to remove code block evaluation from the C-c C-c
  222. keybinding. By default only Emacs Lisp (which has no
  223. requirements) is loaded."
  224. :group 'org-babel
  225. :set 'org-babel-do-load-languages
  226. :version "24.1"
  227. :type '(alist :tag "Babel Languages"
  228. :key-type
  229. (choice
  230. (const :tag "Awk" awk)
  231. (const :tag "C" C)
  232. (const :tag "R" R)
  233. (const :tag "Asymptote" asymptote)
  234. (const :tag "Calc" calc)
  235. (const :tag "Clojure" clojure)
  236. (const :tag "CSS" css)
  237. (const :tag "Ditaa" ditaa)
  238. (const :tag "Dot" dot)
  239. (const :tag "Ebnf2ps" ebnf2ps)
  240. (const :tag "Emacs Lisp" emacs-lisp)
  241. (const :tag "Forth" forth)
  242. (const :tag "Fortran" fortran)
  243. (const :tag "Gnuplot" gnuplot)
  244. (const :tag "Haskell" haskell)
  245. (const :tag "hledger" hledger)
  246. (const :tag "IO" io)
  247. (const :tag "J" J)
  248. (const :tag "Java" java)
  249. (const :tag "Javascript" js)
  250. (const :tag "LaTeX" latex)
  251. (const :tag "Ledger" ledger)
  252. (const :tag "Lilypond" lilypond)
  253. (const :tag "Lisp" lisp)
  254. (const :tag "Makefile" makefile)
  255. (const :tag "Maxima" maxima)
  256. (const :tag "Matlab" matlab)
  257. (const :tag "Mscgen" mscgen)
  258. (const :tag "Ocaml" ocaml)
  259. (const :tag "Octave" octave)
  260. (const :tag "Org" org)
  261. (const :tag "Perl" perl)
  262. (const :tag "Pico Lisp" picolisp)
  263. (const :tag "PlantUML" plantuml)
  264. (const :tag "Python" python)
  265. (const :tag "Ruby" ruby)
  266. (const :tag "Sass" sass)
  267. (const :tag "Scala" scala)
  268. (const :tag "Scheme" scheme)
  269. (const :tag "Screen" screen)
  270. (const :tag "Shell Script" shell)
  271. (const :tag "Shen" shen)
  272. (const :tag "Sql" sql)
  273. (const :tag "Sqlite" sqlite)
  274. (const :tag "Stan" stan)
  275. (const :tag "Vala" vala))
  276. :value-type (boolean :tag "Activate" :value t)))
  277. ;;;; Customization variables
  278. (defcustom org-clone-delete-id nil
  279. "Remove ID property of clones of a subtree.
  280. When non-nil, clones of a subtree don't inherit the ID property.
  281. Otherwise they inherit the ID property with a new unique
  282. identifier."
  283. :type 'boolean
  284. :version "24.1"
  285. :group 'org-id)
  286. ;;; Version
  287. (org-check-version)
  288. ;;;###autoload
  289. (defun org-version (&optional here full message)
  290. "Show the Org version.
  291. Interactively, or when MESSAGE is non-nil, show it in echo area.
  292. With prefix argument, or when HERE is non-nil, insert it at point.
  293. In non-interactive uses, a reduced version string is output unless
  294. FULL is given."
  295. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  296. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  297. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  298. (load-suffixes (list ".el"))
  299. (org-install-dir
  300. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  301. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  302. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  303. (let* ((load-suffixes save-load-suffixes)
  304. (release (org-release))
  305. (git-version (org-git-version))
  306. (version (format "Org mode version %s (%s @ %s)"
  307. release
  308. git-version
  309. (if org-install-dir
  310. (if (string= org-dir org-install-dir)
  311. org-install-dir
  312. (concat "mixed installation! "
  313. org-install-dir
  314. " and "
  315. org-dir))
  316. "org-loaddefs.el can not be found!")))
  317. (version1 (if full version release)))
  318. (when here (insert version1))
  319. (when message (message "%s" version1))
  320. version1)))
  321. (defconst org-version (org-version))
  322. ;;; Syntax Constants
  323. ;;;; Block
  324. (defconst org-block-regexp
  325. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  326. "Regular expression for hiding blocks.")
  327. (defconst org-dblock-start-re
  328. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  329. "Matches the start line of a dynamic block, with parameters.")
  330. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  331. "Matches the end of a dynamic block.")
  332. ;;;; Clock and Planning
  333. (defconst org-clock-string "CLOCK:"
  334. "String used as prefix for timestamps clocking work hours on an item.")
  335. (defvar org-closed-string "CLOSED:"
  336. "String used as the prefix for timestamps logging closing a TODO entry.")
  337. (defvar org-deadline-string "DEADLINE:"
  338. "String to mark deadline entries.
  339. \\<org-mode-map>
  340. A deadline is this string, followed by a time stamp. It must be
  341. a word, terminated by a colon. You can insert a schedule keyword
  342. and a timestamp with `\\[org-deadline]'.")
  343. (defvar org-scheduled-string "SCHEDULED:"
  344. "String to mark scheduled TODO entries.
  345. \\<org-mode-map>
  346. A schedule is this string, followed by a time stamp. It must be
  347. a word, terminated by a colon. You can insert a schedule keyword
  348. and a timestamp with `\\[org-schedule]'.")
  349. (defconst org-ds-keyword-length
  350. (+ 2
  351. (apply #'max
  352. (mapcar #'length
  353. (list org-deadline-string org-scheduled-string
  354. org-clock-string org-closed-string))))
  355. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  356. (defconst org-planning-line-re
  357. (concat "^[ \t]*"
  358. (regexp-opt
  359. (list org-closed-string org-deadline-string org-scheduled-string)
  360. t))
  361. "Matches a line with planning info.
  362. Matched keyword is in group 1.")
  363. (defconst org-clock-line-re
  364. (concat "^[ \t]*" org-clock-string)
  365. "Matches a line with clock info.")
  366. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  367. "Matches the DEADLINE keyword.")
  368. (defconst org-deadline-time-regexp
  369. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  370. "Matches the DEADLINE keyword together with a time stamp.")
  371. (defconst org-deadline-time-hour-regexp
  372. (concat "\\<" org-deadline-string
  373. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  374. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  375. (defconst org-deadline-line-regexp
  376. (concat "\\<\\(" org-deadline-string "\\).*")
  377. "Matches the DEADLINE keyword and the rest of the line.")
  378. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  379. "Matches the SCHEDULED keyword.")
  380. (defconst org-scheduled-time-regexp
  381. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  382. "Matches the SCHEDULED keyword together with a time stamp.")
  383. (defconst org-scheduled-time-hour-regexp
  384. (concat "\\<" org-scheduled-string
  385. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  386. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  387. (defconst org-closed-time-regexp
  388. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  389. "Matches the CLOSED keyword together with a time stamp.")
  390. (defconst org-keyword-time-regexp
  391. (concat "\\<"
  392. (regexp-opt
  393. (list org-scheduled-string org-deadline-string org-closed-string
  394. org-clock-string)
  395. t)
  396. " *[[<]\\([^]>]+\\)[]>]")
  397. "Matches any of the 4 keywords, together with the time stamp.")
  398. (defconst org-keyword-time-not-clock-regexp
  399. (concat
  400. "\\<"
  401. (regexp-opt
  402. (list org-scheduled-string org-deadline-string org-closed-string) t)
  403. " *[[<]\\([^]>]+\\)[]>]")
  404. "Matches any of the 3 keywords, together with the time stamp.")
  405. (defconst org-maybe-keyword-time-regexp
  406. (concat "\\(\\<"
  407. (regexp-opt
  408. (list org-scheduled-string org-deadline-string org-closed-string
  409. org-clock-string)
  410. t)
  411. "\\)?"
  412. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  413. "\\|"
  414. "<%%([^\r\n>]*>\\)")
  415. "Matches a timestamp, possibly preceded by a keyword.")
  416. (defconst org-all-time-keywords
  417. (mapcar (lambda (w) (substring w 0 -1))
  418. (list org-scheduled-string org-deadline-string
  419. org-clock-string org-closed-string))
  420. "List of time keywords.")
  421. ;;;; Drawer
  422. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  423. "Matches first or last line of a hidden block.
  424. Group 1 contains drawer's name or \"END\".")
  425. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  426. "Regular expression matching the first line of a property drawer.")
  427. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  428. "Regular expression matching the last line of a property drawer.")
  429. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  430. "Regular expression matching the first line of a clock drawer.")
  431. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  432. "Regular expression matching the last line of a clock drawer.")
  433. (defconst org-property-drawer-re
  434. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  435. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  436. "[ \t]*:END:[ \t]*$")
  437. "Matches an entire property drawer.")
  438. (defconst org-clock-drawer-re
  439. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  440. org-clock-drawer-end-re "\\)\n?")
  441. "Matches an entire clock drawer.")
  442. ;;;; Headline
  443. (defconst org-heading-keyword-regexp-format
  444. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  445. "Printf format for a regexp matching a headline with some keyword.
  446. This regexp will match the headline of any node which has the
  447. exact keyword that is put into the format. The keyword isn't in
  448. any group by default, but the stars and the body are.")
  449. (defconst org-heading-keyword-maybe-regexp-format
  450. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  451. "Printf format for a regexp matching a headline, possibly with some keyword.
  452. This regexp can match any headline with the specified keyword, or
  453. without a keyword. The keyword isn't in any group by default,
  454. but the stars and the body are.")
  455. (defconst org-archive-tag "ARCHIVE"
  456. "The tag that marks a subtree as archived.
  457. An archived subtree does not open during visibility cycling, and does
  458. not contribute to the agenda listings.")
  459. (eval-and-compile
  460. (defconst org-comment-string "COMMENT"
  461. "Entries starting with this keyword will never be exported.
  462. \\<org-mode-map>
  463. An entry can be toggled between COMMENT and normal with
  464. `\\[org-toggle-comment]'."))
  465. ;;;; LaTeX Environments and Fragments
  466. (defconst org-latex-regexps
  467. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  468. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  469. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  470. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  471. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  472. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  473. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  474. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  475. "Regular expressions for matching embedded LaTeX.")
  476. ;;;; Node Property
  477. (defconst org-effort-property "Effort"
  478. "The property that is being used to keep track of effort estimates.
  479. Effort estimates given in this property need to have the format H:MM.")
  480. ;;;; Table
  481. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  482. "Detect an org-type or table-type table.")
  483. (defconst org-table-line-regexp "^[ \t]*|"
  484. "Detect an org-type table line.")
  485. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  486. "Detect an org-type table line.")
  487. (defconst org-table-hline-regexp "^[ \t]*|-"
  488. "Detect an org-type table hline.")
  489. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  490. "Detect a table-type table hline.")
  491. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  492. "Detect the first line outside a table when searching from within it.
  493. This works for both table types.")
  494. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  495. "Detect a #+TBLFM line.")
  496. ;;;; Timestamp
  497. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  498. "Regular expression for fast time stamp matching.")
  499. (defconst org-ts-regexp-inactive
  500. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  501. "Regular expression for fast inactive time stamp matching.")
  502. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  503. "Regular expression for fast time stamp matching.")
  504. (defconst org-ts-regexp0
  505. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  506. "Regular expression matching time strings for analysis.
  507. This one does not require the space after the date, so it can be used
  508. on a string that terminates immediately after the date.")
  509. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  510. "Regular expression matching time strings for analysis.")
  511. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  512. "Regular expression matching time stamps, with groups.")
  513. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  514. "Regular expression matching time stamps (also [..]), with groups.")
  515. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  516. "Regular expression matching a time stamp range.")
  517. (defconst org-tr-regexp-both
  518. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  519. "Regular expression matching a time stamp range.")
  520. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  521. org-ts-regexp "\\)?")
  522. "Regular expression matching a time stamp or time stamp range.")
  523. (defconst org-tsr-regexp-both
  524. (concat org-ts-regexp-both "\\(--?-?"
  525. org-ts-regexp-both "\\)?")
  526. "Regular expression matching a time stamp or time stamp range.
  527. The time stamps may be either active or inactive.")
  528. (defconst org-repeat-re
  529. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  530. "Regular expression for specifying repeated events.
  531. After a match, group 1 contains the repeat expression.")
  532. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  533. "Formats for `format-time-string' which are used for time stamps.")
  534. ;;; The custom variables
  535. (defgroup org nil
  536. "Outline-based notes management and organizer."
  537. :tag "Org"
  538. :group 'outlines
  539. :group 'calendar)
  540. (defcustom org-mode-hook nil
  541. "Mode hook for Org mode, run after the mode was turned on."
  542. :group 'org
  543. :type 'hook)
  544. (defcustom org-load-hook nil
  545. "Hook that is run after org.el has been loaded."
  546. :group 'org
  547. :type 'hook)
  548. (defcustom org-log-buffer-setup-hook nil
  549. "Hook that is run after an Org log buffer is created."
  550. :group 'org
  551. :version "24.1"
  552. :type 'hook)
  553. (defvar org-modules) ; defined below
  554. (defvar org-modules-loaded nil
  555. "Have the modules been loaded already?")
  556. (defun org-load-modules-maybe (&optional force)
  557. "Load all extensions listed in `org-modules'."
  558. (when (or force (not org-modules-loaded))
  559. (dolist (ext org-modules)
  560. (condition-case nil (require ext)
  561. (error (message "Problems while trying to load feature `%s'" ext))))
  562. (setq org-modules-loaded t)))
  563. (defun org-set-modules (var value)
  564. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  565. (set var value)
  566. (when (featurep 'org)
  567. (org-load-modules-maybe 'force)
  568. (org-element-cache-reset 'all)))
  569. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  570. "Modules that should always be loaded together with org.el.
  571. If a description starts with <C>, the file is not part of Emacs
  572. and loading it will require that you have downloaded and properly
  573. installed the Org mode distribution.
  574. You can also use this system to load external packages (i.e. neither Org
  575. core modules, nor modules from the CONTRIB directory). Just add symbols
  576. to the end of the list. If the package is called org-xyz.el, then you need
  577. to add the symbol `xyz', and the package must have a call to:
  578. (provide \\='org-xyz)
  579. For export specific modules, see also `org-export-backends'."
  580. :group 'org
  581. :set 'org-set-modules
  582. :version "24.4"
  583. :package-version '(Org . "8.0")
  584. :type
  585. '(set :greedy t
  586. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  587. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  588. (const :tag " crypt: Encryption of subtrees" org-crypt)
  589. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  590. (const :tag " docview: Links to doc-view buffers" org-docview)
  591. (const :tag " eww: Store link to url of eww" org-eww)
  592. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  593. (const :tag " habit: Track your consistency with habits" org-habit)
  594. (const :tag " id: Global IDs for identifying entries" org-id)
  595. (const :tag " info: Links to Info nodes" org-info)
  596. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  597. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  598. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  599. (const :tag " mouse: Additional mouse support" org-mouse)
  600. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  601. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  602. (const :tag " tempo: Fast completion for structures" org-tempo)
  603. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  604. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  605. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  606. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  607. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  608. (const :tag "C collector: Collect properties into tables" org-collector)
  609. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  610. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  611. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  612. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  613. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  614. (const :tag "C eval: Include command output as text" org-eval)
  615. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  616. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  617. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  618. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  619. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  620. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  621. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  622. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  623. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  624. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  625. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  626. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  627. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  628. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  629. (const :tag "C registry: A registry for Org links" org-registry)
  630. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  631. (const :tag "C secretary: Team management with Org" org-secretary)
  632. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  633. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  634. (const :tag "C track: Keep up with Org mode development" org-track)
  635. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  636. (const :tag "C vm: Links to VM folders/messages" org-vm)
  637. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  638. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  639. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  640. (defvar org-export-registered-backends) ; From ox.el.
  641. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  642. (declare-function org-export-backend-name "ox" (backend) t)
  643. (defcustom org-export-backends '(ascii html icalendar latex odt)
  644. "List of export back-ends that should be always available.
  645. If a description starts with <C>, the file is not part of Emacs
  646. and loading it will require that you have downloaded and properly
  647. installed the Org mode distribution.
  648. Unlike to `org-modules', libraries in this list will not be
  649. loaded along with Org, but only once the export framework is
  650. needed.
  651. This variable needs to be set before org.el is loaded. If you
  652. need to make a change while Emacs is running, use the customize
  653. interface or run the following code, where VAL stands for the new
  654. value of the variable, after updating it:
  655. (progn
  656. (setq org-export-registered-backends
  657. (cl-remove-if-not
  658. (lambda (backend)
  659. (let ((name (org-export-backend-name backend)))
  660. (or (memq name val)
  661. (catch \\='parentp
  662. (dolist (b val)
  663. (and (org-export-derived-backend-p b name)
  664. (throw \\='parentp t)))))))
  665. org-export-registered-backends))
  666. (let ((new-list (mapcar #\\='org-export-backend-name
  667. org-export-registered-backends)))
  668. (dolist (backend val)
  669. (cond
  670. ((not (load (format \"ox-%s\" backend) t t))
  671. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  672. backend))
  673. ((not (memq backend new-list)) (push backend new-list))))
  674. (set-default \\='org-export-backends new-list)))
  675. Adding a back-end to this list will also pull the back-end it
  676. depends on, if any."
  677. :group 'org
  678. :group 'org-export
  679. :version "26.1"
  680. :package-version '(Org . "9.0")
  681. :initialize 'custom-initialize-set
  682. :set (lambda (var val)
  683. (if (not (featurep 'ox)) (set-default var val)
  684. ;; Any back-end not required anymore (not present in VAL and not
  685. ;; a parent of any back-end in the new value) is removed from the
  686. ;; list of registered back-ends.
  687. (setq org-export-registered-backends
  688. (cl-remove-if-not
  689. (lambda (backend)
  690. (let ((name (org-export-backend-name backend)))
  691. (or (memq name val)
  692. (catch 'parentp
  693. (dolist (b val)
  694. (and (org-export-derived-backend-p b name)
  695. (throw 'parentp t)))))))
  696. org-export-registered-backends))
  697. ;; Now build NEW-LIST of both new back-ends and required
  698. ;; parents.
  699. (let ((new-list (mapcar #'org-export-backend-name
  700. org-export-registered-backends)))
  701. (dolist (backend val)
  702. (cond
  703. ((not (load (format "ox-%s" backend) t t))
  704. (message "Problems while trying to load export back-end `%s'"
  705. backend))
  706. ((not (memq backend new-list)) (push backend new-list))))
  707. ;; Set VAR to that list with fixed dependencies.
  708. (set-default var new-list))))
  709. :type '(set :greedy t
  710. (const :tag " ascii Export buffer to ASCII format" ascii)
  711. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  712. (const :tag " html Export buffer to HTML format" html)
  713. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  714. (const :tag " latex Export buffer to LaTeX format" latex)
  715. (const :tag " man Export buffer to MAN format" man)
  716. (const :tag " md Export buffer to Markdown format" md)
  717. (const :tag " odt Export buffer to ODT format" odt)
  718. (const :tag " org Export buffer to Org format" org)
  719. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  720. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  721. (const :tag "C deck Export buffer to deck.js presentations" deck)
  722. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  723. (const :tag "C groff Export buffer to Groff format" groff)
  724. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  725. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  726. (const :tag "C s5 Export buffer to s5 presentations" s5)
  727. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  728. (eval-after-load 'ox
  729. '(dolist (backend org-export-backends)
  730. (condition-case nil (require (intern (format "ox-%s" backend)))
  731. (error (message "Problems while trying to load export back-end `%s'"
  732. backend)))))
  733. (defcustom org-support-shift-select nil
  734. "Non-nil means make shift-cursor commands select text when possible.
  735. \\<org-mode-map>\
  736. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  737. start selecting a region, or enlarge regions started in this way.
  738. In Org mode, in special contexts, these same keys are used for
  739. other purposes, important enough to compete with shift selection.
  740. Org tries to balance these needs by supporting `shift-select-mode'
  741. outside these special contexts, under control of this variable.
  742. The default of this variable is nil, to avoid confusing behavior. Shifted
  743. cursor keys will then execute Org commands in the following contexts:
  744. - on a headline, changing TODO state (left/right) and priority (up/down)
  745. - on a time stamp, changing the time
  746. - in a plain list item, changing the bullet type
  747. - in a property definition line, switching between allowed values
  748. - in the BEGIN line of a clock table (changing the time block).
  749. Outside these contexts, the commands will throw an error.
  750. When this variable is t and the cursor is not in a special
  751. context, Org mode will support shift-selection for making and
  752. enlarging regions. To make this more effective, the bullet
  753. cycling will no longer happen anywhere in an item line, but only
  754. if the cursor is exactly on the bullet.
  755. If you set this variable to the symbol `always', then the keys
  756. will not be special in headlines, property lines, and item lines,
  757. to make shift selection work there as well. If this is what you
  758. want, you can use the following alternative commands:
  759. `\\[org-todo]' and `\\[org-priority]' \
  760. to change TODO state and priority,
  761. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  762. can be used to switch TODO sets,
  763. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  764. and properties can be edited by hand or in column view.
  765. However, when the cursor is on a timestamp, shift-cursor commands
  766. will still edit the time stamp - this is just too good to give up."
  767. :group 'org
  768. :type '(choice
  769. (const :tag "Never" nil)
  770. (const :tag "When outside special context" t)
  771. (const :tag "Everywhere except timestamps" always)))
  772. (defcustom org-loop-over-headlines-in-active-region nil
  773. "Shall some commands act upon headlines in the active region?
  774. When set to t, some commands will be performed in all headlines
  775. within the active region.
  776. When set to `start-level', some commands will be performed in all
  777. headlines within the active region, provided that these headlines
  778. are of the same level than the first one.
  779. When set to a string, those commands will be performed on the
  780. matching headlines within the active region. Such string must be
  781. a tags/property/todo match as it is used in the agenda tags view.
  782. The list of commands is: `org-schedule', `org-deadline',
  783. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  784. `org-archive-to-archive-sibling'. The archiving commands skip
  785. already archived entries."
  786. :type '(choice (const :tag "Don't loop" nil)
  787. (const :tag "All headlines in active region" t)
  788. (const :tag "In active region, headlines at the same level than the first one" start-level)
  789. (string :tag "Tags/Property/Todo matcher"))
  790. :version "24.1"
  791. :group 'org-todo
  792. :group 'org-archive)
  793. (defcustom org-startup-folded t
  794. "Non-nil means entering Org mode will switch to OVERVIEW.
  795. This can also be configured on a per-file basis by adding one of
  796. the following lines anywhere in the buffer:
  797. #+STARTUP: fold (or `overview', this is equivalent)
  798. #+STARTUP: nofold (or `showall', this is equivalent)
  799. #+STARTUP: content
  800. #+STARTUP: showeverything
  801. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  802. to ignore this option when Org opens agenda files for the first
  803. time."
  804. :group 'org-startup
  805. :type '(choice
  806. (const :tag "nofold: show all" nil)
  807. (const :tag "fold: overview" t)
  808. (const :tag "content: all headlines" content)
  809. (const :tag "show everything, even drawers" showeverything)))
  810. (defcustom org-startup-truncated t
  811. "Non-nil means entering Org mode will set `truncate-lines'.
  812. This is useful since some lines containing links can be very long and
  813. uninteresting. Also tables look terrible when wrapped.
  814. The variable `org-startup-truncated' allows to configure
  815. truncation for Org mode different to the other modes that use the
  816. variable `truncate-lines' and as a shortcut instead of putting
  817. the variable `truncate-lines' into the `org-mode-hook'. If one
  818. wants to configure truncation for Org mode not statically but
  819. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  820. the variable `truncate-lines' has to be used because in such a
  821. case it is too late to set the variable `org-startup-truncated'."
  822. :group 'org-startup
  823. :type 'boolean)
  824. (defcustom org-startup-indented nil
  825. "Non-nil means turn on `org-indent-mode' on startup.
  826. This can also be configured on a per-file basis by adding one of
  827. the following lines anywhere in the buffer:
  828. #+STARTUP: indent
  829. #+STARTUP: noindent"
  830. :group 'org-structure
  831. :type '(choice
  832. (const :tag "Not" nil)
  833. (const :tag "Globally (slow on startup in large files)" t)))
  834. (defcustom org-use-sub-superscripts t
  835. "Non-nil means interpret \"_\" and \"^\" for display.
  836. If you want to control how Org exports those characters, see
  837. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  838. used to be an alias for `org-export-with-sub-superscripts' in
  839. Org <8.0, it is not anymore.
  840. When this option is turned on, you can use TeX-like syntax for
  841. sub- and superscripts within the buffer. Several characters after
  842. \"_\" or \"^\" will be considered as a single item - so grouping
  843. with {} is normally not needed. For example, the following things
  844. will be parsed as single sub- or superscripts:
  845. 10^24 or 10^tau several digits will be considered 1 item.
  846. 10^-12 or 10^-tau a leading sign with digits or a word
  847. x^2-y^3 will be read as x^2 - y^3, because items are
  848. terminated by almost any nonword/nondigit char.
  849. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  850. Still, ambiguity is possible. So when in doubt, use {} to enclose
  851. the sub/superscript. If you set this variable to the symbol `{}',
  852. the braces are *required* in order to trigger interpretations as
  853. sub/superscript. This can be helpful in documents that need \"_\"
  854. frequently in plain text."
  855. :group 'org-startup
  856. :version "24.4"
  857. :package-version '(Org . "8.0")
  858. :type '(choice
  859. (const :tag "Always interpret" t)
  860. (const :tag "Only with braces" {})
  861. (const :tag "Never interpret" nil)))
  862. (defcustom org-startup-with-beamer-mode nil
  863. "Non-nil means turn on `org-beamer-mode' on startup.
  864. This can also be configured on a per-file basis by adding one of
  865. the following lines anywhere in the buffer:
  866. #+STARTUP: beamer"
  867. :group 'org-startup
  868. :version "24.1"
  869. :type 'boolean)
  870. (defcustom org-startup-align-all-tables nil
  871. "Non-nil means align all tables when visiting a file.
  872. This can also be configured on a per-file basis by adding one of
  873. the following lines anywhere in the buffer:
  874. #+STARTUP: align
  875. #+STARTUP: noalign"
  876. :group 'org-startup
  877. :type 'boolean)
  878. (defcustom org-startup-shrink-all-tables nil
  879. "Non-nil means shrink all table columns with a width cookie.
  880. This can also be configured on a per-file basis by adding one of
  881. the following lines anywhere in the buffer:
  882. #+STARTUP: shrink"
  883. :group 'org-startup
  884. :type 'boolean
  885. :version "27.1"
  886. :package-version '(Org . "9.2")
  887. :safe #'booleanp)
  888. (defcustom org-startup-with-inline-images nil
  889. "Non-nil means show inline images when loading a new Org file.
  890. This can also be configured on a per-file basis by adding one of
  891. the following lines anywhere in the buffer:
  892. #+STARTUP: inlineimages
  893. #+STARTUP: noinlineimages"
  894. :group 'org-startup
  895. :version "24.1"
  896. :type 'boolean)
  897. (defcustom org-startup-with-latex-preview nil
  898. "Non-nil means preview LaTeX fragments when loading a new Org file.
  899. This can also be configured on a per-file basis by adding one of
  900. the following lines anywhere in the buffer:
  901. #+STARTUP: latexpreview
  902. #+STARTUP: nolatexpreview"
  903. :group 'org-startup
  904. :version "24.4"
  905. :package-version '(Org . "8.0")
  906. :type 'boolean)
  907. (defcustom org-insert-mode-line-in-empty-file nil
  908. "Non-nil means insert the first line setting Org mode in empty files.
  909. When the function `org-mode' is called interactively in an empty file, this
  910. normally means that the file name does not automatically trigger Org mode.
  911. To ensure that the file will always be in Org mode in the future, a
  912. line enforcing Org mode will be inserted into the buffer, if this option
  913. has been set."
  914. :group 'org-startup
  915. :type 'boolean)
  916. (defcustom org-replace-disputed-keys nil
  917. "Non-nil means use alternative key bindings for some keys.
  918. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  919. These keys are also used by other packages like Shift Select mode,
  920. CUA mode or Windmove. If you want to use Org mode together with
  921. one of these other modes, or more generally if you would like to
  922. move some Org mode commands to other keys, set this variable and
  923. configure the keys with the variable `org-disputed-keys'.
  924. This option is only relevant at load-time of Org mode, and must be set
  925. *before* org.el is loaded. Changing it requires a restart of Emacs to
  926. become effective."
  927. :group 'org-startup
  928. :type 'boolean)
  929. (defcustom org-use-extra-keys nil
  930. "Non-nil means use extra key sequence definitions for certain commands.
  931. This happens automatically if `window-system' is nil. This
  932. variable lets you do the same manually. You must set it before
  933. loading Org."
  934. :group 'org-startup
  935. :type 'boolean)
  936. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  937. (defcustom org-disputed-keys
  938. '(([(shift up)] . [(meta p)])
  939. ([(shift down)] . [(meta n)])
  940. ([(shift left)] . [(meta -)])
  941. ([(shift right)] . [(meta +)])
  942. ([(control shift right)] . [(meta shift +)])
  943. ([(control shift left)] . [(meta shift -)]))
  944. "Keys for which Org mode and other modes compete.
  945. This is an alist, cars are the default keys, second element specifies
  946. the alternative to use when `org-replace-disputed-keys' is t.
  947. Keys can be specified in any syntax supported by `define-key'.
  948. The value of this option takes effect only at Org mode startup,
  949. therefore you'll have to restart Emacs to apply it after changing."
  950. :group 'org-startup
  951. :type 'alist)
  952. (defun org-key (key)
  953. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  954. Or return the original if not disputed."
  955. (when org-replace-disputed-keys
  956. (let* ((nkey (key-description key))
  957. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  958. org-disputed-keys)))
  959. (setq key (if x (cdr x) key))))
  960. key)
  961. (defun org-defkey (keymap key def)
  962. "Define a key, possibly translated, as returned by `org-key'."
  963. (define-key keymap (org-key key) def))
  964. (defcustom org-ellipsis nil
  965. "The ellipsis to use in the Org mode outline.
  966. When nil, just use the standard three dots. When a non-empty string,
  967. use that string instead.
  968. The change affects only Org mode (which will then use its own display table).
  969. Changing this requires executing `\\[org-mode]' in a buffer to become
  970. effective."
  971. :group 'org-startup
  972. :type '(choice (const :tag "Default" nil)
  973. (string :tag "String" :value "...#"))
  974. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  975. (defvar org-display-table nil
  976. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  977. (defgroup org-keywords nil
  978. "Keywords in Org mode."
  979. :tag "Org Keywords"
  980. :group 'org)
  981. (defcustom org-closed-keep-when-no-todo nil
  982. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  983. :group 'org-todo
  984. :group 'org-keywords
  985. :version "24.4"
  986. :package-version '(Org . "8.0")
  987. :type 'boolean)
  988. (defgroup org-structure nil
  989. "Options concerning the general structure of Org files."
  990. :tag "Org Structure"
  991. :group 'org)
  992. (defgroup org-reveal-location nil
  993. "Options about how to make context of a location visible."
  994. :tag "Org Reveal Location"
  995. :group 'org-structure)
  996. (defcustom org-show-context-detail '((agenda . local)
  997. (bookmark-jump . lineage)
  998. (isearch . lineage)
  999. (default . ancestors))
  1000. "Alist between context and visibility span when revealing a location.
  1001. \\<org-mode-map>Some actions may move point into invisible
  1002. locations. As a consequence, Org always expose a neighborhood
  1003. around point. How much is shown depends on the initial action,
  1004. or context. Valid contexts are
  1005. agenda when exposing an entry from the agenda
  1006. org-goto when using the command `org-goto' (`\\[org-goto]')
  1007. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1008. tags-tree when constructing a sparse tree based on tags matches
  1009. link-search when exposing search matches associated with a link
  1010. mark-goto when exposing the jump goal of a mark
  1011. bookmark-jump when exposing a bookmark location
  1012. isearch when exiting from an incremental search
  1013. default default for all contexts not set explicitly
  1014. Allowed visibility spans are
  1015. minimal show current headline; if point is not on headline,
  1016. also show entry
  1017. local show current headline, entry and next headline
  1018. ancestors show current headline and its direct ancestors; if
  1019. point is not on headline, also show entry
  1020. lineage show current headline, its direct ancestors and all
  1021. their children; if point is not on headline, also show
  1022. entry and first child
  1023. tree show current headline, its direct ancestors and all
  1024. their children; if point is not on headline, also show
  1025. entry and all children
  1026. canonical show current headline, its direct ancestors along with
  1027. their entries and children; if point is not located on
  1028. the headline, also show current entry and all children
  1029. As special cases, a nil or t value means show all contexts in
  1030. `minimal' or `canonical' view, respectively.
  1031. Some views can make displayed information very compact, but also
  1032. make it harder to edit the location of the match. In such
  1033. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1034. more context."
  1035. :group 'org-reveal-location
  1036. :version "26.1"
  1037. :package-version '(Org . "9.0")
  1038. :type '(choice
  1039. (const :tag "Canonical" t)
  1040. (const :tag "Minimal" nil)
  1041. (repeat :greedy t :tag "Individual contexts"
  1042. (cons
  1043. (choice :tag "Context"
  1044. (const agenda)
  1045. (const org-goto)
  1046. (const occur-tree)
  1047. (const tags-tree)
  1048. (const link-search)
  1049. (const mark-goto)
  1050. (const bookmark-jump)
  1051. (const isearch)
  1052. (const default))
  1053. (choice :tag "Detail level"
  1054. (const minimal)
  1055. (const local)
  1056. (const ancestors)
  1057. (const lineage)
  1058. (const tree)
  1059. (const canonical))))))
  1060. (defcustom org-indirect-buffer-display 'other-window
  1061. "How should indirect tree buffers be displayed?
  1062. This applies to indirect buffers created with the commands
  1063. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1064. Valid values are:
  1065. current-window Display in the current window
  1066. other-window Just display in another window.
  1067. dedicated-frame Create one new frame, and re-use it each time.
  1068. new-frame Make a new frame each time. Note that in this case
  1069. previously-made indirect buffers are kept, and you need to
  1070. kill these buffers yourself."
  1071. :group 'org-structure
  1072. :group 'org-agenda-windows
  1073. :type '(choice
  1074. (const :tag "In current window" current-window)
  1075. (const :tag "In current frame, other window" other-window)
  1076. (const :tag "Each time a new frame" new-frame)
  1077. (const :tag "One dedicated frame" dedicated-frame)))
  1078. (defcustom org-use-speed-commands nil
  1079. "Non-nil means activate single letter commands at beginning of a headline.
  1080. This may also be a function to test for appropriate locations where speed
  1081. commands should be active.
  1082. For example, to activate speed commands when the point is on any
  1083. star at the beginning of the headline, you can do this:
  1084. (setq org-use-speed-commands
  1085. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1086. :group 'org-structure
  1087. :type '(choice
  1088. (const :tag "Never" nil)
  1089. (const :tag "At beginning of headline stars" t)
  1090. (function)))
  1091. (defcustom org-speed-commands-user nil
  1092. "Alist of additional speed commands.
  1093. This list will be checked before `org-speed-commands-default'
  1094. when the variable `org-use-speed-commands' is non-nil
  1095. and when the cursor is at the beginning of a headline.
  1096. The car of each entry is a string with a single letter, which must
  1097. be assigned to `self-insert-command' in the global map.
  1098. The cdr is either a command to be called interactively, a function
  1099. to be called, or a form to be evaluated.
  1100. An entry that is just a list with a single string will be interpreted
  1101. as a descriptive headline that will be added when listing the speed
  1102. commands in the Help buffer using the `?' speed command."
  1103. :group 'org-structure
  1104. :type '(repeat :value ("k" . ignore)
  1105. (choice :value ("k" . ignore)
  1106. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1107. (cons :tag "Letter and Command"
  1108. (string :tag "Command letter")
  1109. (choice
  1110. (function)
  1111. (sexp))))))
  1112. (defcustom org-bookmark-names-plist
  1113. '(:last-capture "org-capture-last-stored"
  1114. :last-refile "org-refile-last-stored"
  1115. :last-capture-marker "org-capture-last-stored-marker")
  1116. "Names for bookmarks automatically set by some Org commands.
  1117. This can provide strings as names for a number of bookmarks Org sets
  1118. automatically. The following keys are currently implemented:
  1119. :last-capture
  1120. :last-capture-marker
  1121. :last-refile
  1122. When a key does not show up in the property list, the corresponding bookmark
  1123. is not set."
  1124. :group 'org-structure
  1125. :type 'plist)
  1126. (defgroup org-cycle nil
  1127. "Options concerning visibility cycling in Org mode."
  1128. :tag "Org Cycle"
  1129. :group 'org-structure)
  1130. (defcustom org-cycle-skip-children-state-if-no-children t
  1131. "Non-nil means skip CHILDREN state in entries that don't have any."
  1132. :group 'org-cycle
  1133. :type 'boolean)
  1134. (defcustom org-cycle-max-level nil
  1135. "Maximum level which should still be subject to visibility cycling.
  1136. Levels higher than this will, for cycling, be treated as text, not a headline.
  1137. When `org-odd-levels-only' is set, a value of N in this variable actually
  1138. means 2N-1 stars as the limiting headline.
  1139. When nil, cycle all levels.
  1140. Note that the limiting level of cycling is also influenced by
  1141. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1142. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1143. than its value."
  1144. :group 'org-cycle
  1145. :type '(choice
  1146. (const :tag "No limit" nil)
  1147. (integer :tag "Maximum level")))
  1148. (defcustom org-hide-block-startup nil
  1149. "Non-nil means entering Org mode will fold all blocks.
  1150. This can also be set in on a per-file basis with
  1151. #+STARTUP: hideblocks
  1152. #+STARTUP: showblocks"
  1153. :group 'org-startup
  1154. :group 'org-cycle
  1155. :type 'boolean)
  1156. (defcustom org-cycle-global-at-bob nil
  1157. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1158. This makes it possible to do global cycling without having to use `S-TAB'
  1159. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1160. line of the buffer
  1161. must not be a headline -- it may be empty or some other text.
  1162. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1163. sure the cursor stays at the beginning of the buffer.
  1164. When this option is nil, don't do anything special at the beginning of
  1165. the buffer."
  1166. :group 'org-cycle
  1167. :type 'boolean)
  1168. (defcustom org-cycle-level-after-item/entry-creation t
  1169. "Non-nil means cycle entry level or item indentation in new empty entries.
  1170. When the cursor is at the end of an empty headline, i.e., with only stars
  1171. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1172. and then all possible ancestor states, before returning to the original state.
  1173. This makes data entry extremely fast: M-RET to create a new headline,
  1174. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1175. When the cursor is at the end of an empty plain list item, one TAB will
  1176. make it a subitem, two or more tabs will back up to make this an item
  1177. higher up in the item hierarchy."
  1178. :group 'org-cycle
  1179. :type 'boolean)
  1180. (defcustom org-cycle-emulate-tab t
  1181. "Where should `org-cycle' emulate TAB.
  1182. nil Never
  1183. white Only in completely white lines
  1184. whitestart Only at the beginning of lines, before the first non-white char
  1185. t Everywhere except in headlines
  1186. exc-hl-bol Everywhere except at the start of a headline
  1187. If TAB is used in a place where it does not emulate TAB, the current subtree
  1188. visibility is cycled."
  1189. :group 'org-cycle
  1190. :type '(choice (const :tag "Never" nil)
  1191. (const :tag "Only in completely white lines" white)
  1192. (const :tag "Before first char in a line" whitestart)
  1193. (const :tag "Everywhere except in headlines" t)
  1194. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1195. (defcustom org-cycle-separator-lines 2
  1196. "Number of empty lines needed to keep an empty line between collapsed trees.
  1197. If you leave an empty line between the end of a subtree and the following
  1198. headline, this empty line is hidden when the subtree is folded.
  1199. Org mode will leave (exactly) one empty line visible if the number of
  1200. empty lines is equal or larger to the number given in this variable.
  1201. So the default 2 means at least 2 empty lines after the end of a subtree
  1202. are needed to produce free space between a collapsed subtree and the
  1203. following headline.
  1204. If the number is negative, and the number of empty lines is at least -N,
  1205. all empty lines are shown.
  1206. Special case: when 0, never leave empty lines in collapsed view."
  1207. :group 'org-cycle
  1208. :type 'integer)
  1209. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1210. (defcustom org-pre-cycle-hook nil
  1211. "Hook that is run before visibility cycling is happening.
  1212. The function(s) in this hook must accept a single argument which indicates
  1213. the new state that will be set right after running this hook. The
  1214. argument is a symbol. Before a global state change, it can have the values
  1215. `overview', `content', or `all'. Before a local state change, it can have
  1216. the values `folded', `children', or `subtree'."
  1217. :group 'org-cycle
  1218. :type 'hook)
  1219. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1220. org-cycle-show-empty-lines
  1221. org-optimize-window-after-visibility-change)
  1222. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1223. The function(s) in this hook must accept a single argument which indicates
  1224. the new state that was set by the most recent `org-cycle' command. The
  1225. argument is a symbol. After a global state change, it can have the values
  1226. `overview', `contents', or `all'. After a local state change, it can have
  1227. the values `folded', `children', or `subtree'."
  1228. :group 'org-cycle
  1229. :type 'hook
  1230. :version "26.1"
  1231. :package-version '(Org . "8.3"))
  1232. (defgroup org-edit-structure nil
  1233. "Options concerning structure editing in Org mode."
  1234. :tag "Org Edit Structure"
  1235. :group 'org-structure)
  1236. (defcustom org-odd-levels-only nil
  1237. "Non-nil means skip even levels and only use odd levels for the outline.
  1238. This has the effect that two stars are being added/taken away in
  1239. promotion/demotion commands. It also influences how levels are
  1240. handled by the exporters.
  1241. Changing it requires restart of `font-lock-mode' to become effective
  1242. for fontification also in regions already fontified.
  1243. You may also set this on a per-file basis by adding one of the following
  1244. lines to the buffer:
  1245. #+STARTUP: odd
  1246. #+STARTUP: oddeven"
  1247. :group 'org-edit-structure
  1248. :group 'org-appearance
  1249. :type 'boolean)
  1250. (defcustom org-adapt-indentation t
  1251. "Non-nil means adapt indentation to outline node level.
  1252. When this variable is set, Org assumes that you write outlines by
  1253. indenting text in each node to align with the headline (after the
  1254. stars). The following issues are influenced by this variable:
  1255. - The indentation is increased by one space in a demotion
  1256. command, and decreased by one in a promotion command. However,
  1257. in the latter case, if shifting some line in the entry body
  1258. would alter document structure (e.g., insert a new headline),
  1259. indentation is not changed at all.
  1260. - Property drawers and planning information is inserted indented
  1261. when this variable is set. When nil, they will not be indented.
  1262. - TAB indents a line relative to current level. The lines below
  1263. a headline will be indented when this variable is set.
  1264. Note that this is all about true indentation, by adding and
  1265. removing space characters. See also \"org-indent.el\" which does
  1266. level-dependent indentation in a virtual way, i.e. at display
  1267. time in Emacs."
  1268. :group 'org-edit-structure
  1269. :type 'boolean
  1270. :safe #'booleanp)
  1271. (defcustom org-special-ctrl-a/e nil
  1272. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1273. When t, `C-a' will bring back the cursor to the beginning of the
  1274. headline text, i.e. after the stars and after a possible TODO
  1275. keyword. In an item, this will be the position after bullet and
  1276. check-box, if any. When the cursor is already at that position,
  1277. another `C-a' will bring it to the beginning of the line.
  1278. `C-e' will jump to the end of the headline, ignoring the presence
  1279. of tags in the headline. A second `C-e' will then jump to the
  1280. true end of the line, after any tags. This also means that, when
  1281. this variable is non-nil, `C-e' also will never jump beyond the
  1282. end of the heading of a folded section, i.e. not after the
  1283. ellipses.
  1284. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1285. normally, going to the true line boundary first. Only a directly
  1286. following, identical keypress will bring the cursor to the
  1287. special positions.
  1288. This may also be a cons cell where the behavior for `C-a' and
  1289. `C-e' is set separately."
  1290. :group 'org-edit-structure
  1291. :type '(choice
  1292. (const :tag "off" nil)
  1293. (const :tag "on: after stars/bullet and before tags first" t)
  1294. (const :tag "reversed: true line boundary first" reversed)
  1295. (cons :tag "Set C-a and C-e separately"
  1296. (choice :tag "Special C-a"
  1297. (const :tag "off" nil)
  1298. (const :tag "on: after stars/bullet first" t)
  1299. (const :tag "reversed: before stars/bullet first" reversed))
  1300. (choice :tag "Special C-e"
  1301. (const :tag "off" nil)
  1302. (const :tag "on: before tags first" t)
  1303. (const :tag "reversed: after tags first" reversed)))))
  1304. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1305. (defcustom org-special-ctrl-k nil
  1306. "Non-nil means `C-k' will behave specially in headlines.
  1307. When nil, `C-k' will call the default `kill-line' command.
  1308. When t, the following will happen while the cursor is in the headline:
  1309. - When the cursor is at the beginning of a headline, kill the entire
  1310. line and possible the folded subtree below the line.
  1311. - When in the middle of the headline text, kill the headline up to the tags.
  1312. - When after the headline text, kill the tags."
  1313. :group 'org-edit-structure
  1314. :type 'boolean)
  1315. (defcustom org-ctrl-k-protect-subtree nil
  1316. "Non-nil means, do not delete a hidden subtree with C-k.
  1317. When set to the symbol `error', simply throw an error when C-k is
  1318. used to kill (part-of) a headline that has hidden text behind it.
  1319. Any other non-nil value will result in a query to the user, if it is
  1320. OK to kill that hidden subtree. When nil, kill without remorse."
  1321. :group 'org-edit-structure
  1322. :version "24.1"
  1323. :type '(choice
  1324. (const :tag "Do not protect hidden subtrees" nil)
  1325. (const :tag "Protect hidden subtrees with a security query" t)
  1326. (const :tag "Never kill a hidden subtree with C-k" error)))
  1327. (defcustom org-special-ctrl-o t
  1328. "Non-nil means, make `C-o' insert a row in tables."
  1329. :group 'org-edit-structure
  1330. :type 'boolean)
  1331. (defcustom org-catch-invisible-edits nil
  1332. "Check if in invisible region before inserting or deleting a character.
  1333. Valid values are:
  1334. nil Do not check, so just do invisible edits.
  1335. error Throw an error and do nothing.
  1336. show Make point visible, and do the requested edit.
  1337. show-and-error Make point visible, then throw an error and abort the edit.
  1338. smart Make point visible, and do insertion/deletion if it is
  1339. adjacent to visible text and the change feels predictable.
  1340. Never delete a previously invisible character or add in the
  1341. middle or right after an invisible region. Basically, this
  1342. allows insertion and backward-delete right before ellipses.
  1343. FIXME: maybe in this case we should not even show?"
  1344. :group 'org-edit-structure
  1345. :version "24.1"
  1346. :type '(choice
  1347. (const :tag "Do not check" nil)
  1348. (const :tag "Throw error when trying to edit" error)
  1349. (const :tag "Unhide, but do not do the edit" show-and-error)
  1350. (const :tag "Show invisible part and do the edit" show)
  1351. (const :tag "Be smart and do the right thing" smart)))
  1352. (defcustom org-yank-folded-subtrees t
  1353. "Non-nil means when yanking subtrees, fold them.
  1354. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1355. it starts with a heading and all other headings in it are either children
  1356. or siblings, then fold all the subtrees. However, do this only if no
  1357. text after the yank would be swallowed into a folded tree by this action."
  1358. :group 'org-edit-structure
  1359. :type 'boolean)
  1360. (defcustom org-yank-adjusted-subtrees nil
  1361. "Non-nil means when yanking subtrees, adjust the level.
  1362. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1363. this function for details."
  1364. :group 'org-edit-structure
  1365. :type 'boolean)
  1366. (defcustom org-M-RET-may-split-line '((default . t))
  1367. "Non-nil means M-RET will split the line at the cursor position.
  1368. When nil, it will go to the end of the line before making a
  1369. new line.
  1370. You may also set this option in a different way for different
  1371. contexts. Valid contexts are:
  1372. headline when creating a new headline
  1373. item when creating a new item
  1374. table in a table field
  1375. default the value to be used for all contexts not explicitly
  1376. customized"
  1377. :group 'org-structure
  1378. :group 'org-table
  1379. :type '(choice
  1380. (const :tag "Always" t)
  1381. (const :tag "Never" nil)
  1382. (repeat :greedy t :tag "Individual contexts"
  1383. (cons
  1384. (choice :tag "Context"
  1385. (const headline)
  1386. (const item)
  1387. (const table)
  1388. (const default))
  1389. (boolean)))))
  1390. (defcustom org-insert-heading-respect-content nil
  1391. "Non-nil means insert new headings after the current subtree.
  1392. \\<org-mode-map>
  1393. When nil, the new heading is created directly after the current line.
  1394. The commands `\\[org-insert-heading-respect-content]' and \
  1395. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1396. for the duration of the command."
  1397. :group 'org-structure
  1398. :type 'boolean)
  1399. (defcustom org-blank-before-new-entry '((heading . auto)
  1400. (plain-list-item . auto))
  1401. "Should `org-insert-heading' leave a blank line before new heading/item?
  1402. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1403. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1404. which case Org will look at the surrounding headings/items and try to
  1405. make an intelligent decision whether to insert a blank line or not."
  1406. :group 'org-edit-structure
  1407. :type '(list
  1408. (cons (const heading)
  1409. (choice (const :tag "Never" nil)
  1410. (const :tag "Always" t)
  1411. (const :tag "Auto" auto)))
  1412. (cons (const plain-list-item)
  1413. (choice (const :tag "Never" nil)
  1414. (const :tag "Always" t)
  1415. (const :tag "Auto" auto)))))
  1416. (defcustom org-insert-heading-hook nil
  1417. "Hook being run after inserting a new heading."
  1418. :group 'org-edit-structure
  1419. :type 'hook)
  1420. (defcustom org-enable-fixed-width-editor t
  1421. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1422. This currently only means they are never auto-wrapped.
  1423. When nil, such lines will be treated like ordinary lines."
  1424. :group 'org-edit-structure
  1425. :type 'boolean)
  1426. (defgroup org-sparse-trees nil
  1427. "Options concerning sparse trees in Org mode."
  1428. :tag "Org Sparse Trees"
  1429. :group 'org-structure)
  1430. (defcustom org-highlight-sparse-tree-matches t
  1431. "Non-nil means highlight all matches that define a sparse tree.
  1432. The highlights will automatically disappear the next time the buffer is
  1433. changed by an edit command."
  1434. :group 'org-sparse-trees
  1435. :type 'boolean)
  1436. (defcustom org-remove-highlights-with-change t
  1437. "Non-nil means any change to the buffer will remove temporary highlights.
  1438. \\<org-mode-map>\
  1439. Such highlights are created by `org-occur' and `org-clock-display'.
  1440. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1441. to get rid of the highlights.
  1442. The highlights created by `org-toggle-latex-fragment' always need
  1443. `\\[org-toggle-latex-fragment]' to be removed."
  1444. :group 'org-sparse-trees
  1445. :group 'org-time
  1446. :type 'boolean)
  1447. (defcustom org-occur-case-fold-search t
  1448. "Non-nil means `org-occur' should be case-insensitive.
  1449. If set to `smart' the search will be case-insensitive only if it
  1450. doesn't specify any upper case character."
  1451. :group 'org-sparse-trees
  1452. :version "26.1"
  1453. :type '(choice
  1454. (const :tag "Case-sensitive" nil)
  1455. (const :tag "Case-insensitive" t)
  1456. (const :tag "Case-insensitive for lower case searches only" smart)))
  1457. (defcustom org-occur-hook '(org-first-headline-recenter)
  1458. "Hook that is run after `org-occur' has constructed a sparse tree.
  1459. This can be used to recenter the window to show as much of the structure
  1460. as possible."
  1461. :group 'org-sparse-trees
  1462. :type 'hook)
  1463. (defgroup org-table nil
  1464. "Options concerning tables in Org mode."
  1465. :tag "Org Table"
  1466. :group 'org)
  1467. (defcustom org-self-insert-cluster-for-undo nil
  1468. "Non-nil means cluster self-insert commands for undo when possible.
  1469. If this is set, then, like in the Emacs command loop, 20 consecutive
  1470. characters will be undone together.
  1471. This is configurable, because there is some impact on typing performance."
  1472. :group 'org-table
  1473. :type 'boolean)
  1474. (defcustom org-table-tab-recognizes-table.el t
  1475. "Non-nil means TAB will automatically notice a table.el table.
  1476. When it sees such a table, it moves point into it and - if necessary -
  1477. calls `table-recognize-table'."
  1478. :group 'org-table-editing
  1479. :type 'boolean)
  1480. (defgroup org-link nil
  1481. "Options concerning links in Org mode."
  1482. :tag "Org Link"
  1483. :group 'org)
  1484. (defvar-local org-link-abbrev-alist-local nil
  1485. "Buffer-local version of `org-link-abbrev-alist', which see.
  1486. The value of this is taken from the #+LINK lines.")
  1487. (defcustom org-link-parameters
  1488. '(("doi" :follow org--open-doi-link)
  1489. ("elisp" :follow org--open-elisp-link)
  1490. ("file" :complete org-file-complete-link)
  1491. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1492. ("help" :follow org--open-help-link)
  1493. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1494. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1495. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1496. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1497. ("shell" :follow org--open-shell-link))
  1498. "An alist of properties that defines all the links in Org mode.
  1499. The key in each association is a string of the link type.
  1500. Subsequent optional elements make up a p-list of link properties.
  1501. :follow - A function that takes the link path as an argument.
  1502. :export - A function that takes the link path, description and
  1503. export-backend as arguments.
  1504. :store - A function responsible for storing the link. See the
  1505. function `org-store-link-functions'.
  1506. :complete - A function that inserts a link with completion. The
  1507. function takes one optional prefix arg.
  1508. :face - A face for the link, or a function that returns a face.
  1509. The function takes one argument which is the link path. The
  1510. default face is `org-link'.
  1511. :mouse-face - The mouse-face. The default is `highlight'.
  1512. :display - `full' will not fold the link in descriptive
  1513. display. Default is `org-link'.
  1514. :help-echo - A string or function that takes (window object position)
  1515. as arguments and returns a string.
  1516. :keymap - A keymap that is active on the link. The default is
  1517. `org-mouse-map'.
  1518. :htmlize-link - A function for the htmlize-link. Defaults
  1519. to (list :uri \"type:path\")
  1520. :activate-func - A function to run at the end of font-lock
  1521. activation. The function must accept (link-start link-end path bracketp)
  1522. as arguments."
  1523. :group 'org-link
  1524. :type '(alist :tag "Link display parameters"
  1525. :value-type plist)
  1526. :version "26.1"
  1527. :package-version '(Org . "9.1"))
  1528. (defun org-link-get-parameter (type key)
  1529. "Get TYPE link property for KEY.
  1530. TYPE is a string and KEY is a plist keyword."
  1531. (plist-get
  1532. (cdr (assoc type org-link-parameters))
  1533. key))
  1534. (defun org-link-set-parameters (type &rest parameters)
  1535. "Set link TYPE properties to PARAMETERS.
  1536. PARAMETERS should be :key val pairs."
  1537. (let ((data (assoc type org-link-parameters)))
  1538. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1539. (push (cons type parameters) org-link-parameters)
  1540. (org-make-link-regexps)
  1541. (org-element-update-syntax))))
  1542. (defun org-link-types ()
  1543. "Return a list of known link types."
  1544. (mapcar #'car org-link-parameters))
  1545. (defcustom org-link-abbrev-alist nil
  1546. "Alist of link abbreviations.
  1547. The car of each element is a string, to be replaced at the start of a link.
  1548. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1549. links in Org buffers can have an optional tag after a double colon, e.g.,
  1550. [[linkkey:tag][description]]
  1551. The `linkkey' must be a single word, starting with a letter, followed
  1552. by letters, numbers, `-' or `_'.
  1553. If REPLACE is a string, the tag will simply be appended to create the link.
  1554. If the string contains \"%s\", the tag will be inserted there. If the string
  1555. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1556. at that point (see the function `url-hexify-string'). If the string contains
  1557. the specifier \"%(my-function)\", then the custom function `my-function' will
  1558. be invoked: this function takes the tag as its only argument and must return
  1559. a string.
  1560. REPLACE may also be a function that will be called with the tag as the
  1561. only argument to create the link, which should be returned as a string.
  1562. See the manual for examples."
  1563. :group 'org-link
  1564. :type '(repeat
  1565. (cons
  1566. (string :tag "Protocol")
  1567. (choice
  1568. (string :tag "Format")
  1569. (function)))))
  1570. (defcustom org-descriptive-links t
  1571. "Non-nil means Org will display descriptive links.
  1572. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1573. \"Org Website\", hiding the link itself and just displaying its
  1574. description. When set to nil, Org will display the full links
  1575. literally.
  1576. You can interactively set the value of this variable by calling
  1577. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1578. :group 'org-link
  1579. :type 'boolean)
  1580. (defcustom org-link-file-path-type 'adaptive
  1581. "How the path name in file links should be stored.
  1582. Valid values are:
  1583. relative Relative to the current directory, i.e. the directory of the file
  1584. into which the link is being inserted.
  1585. absolute Absolute path, if possible with ~ for home directory.
  1586. noabbrev Absolute path, no abbreviation of home directory.
  1587. adaptive Use relative path for files in the current directory and sub-
  1588. directories of it. For other files, use an absolute path."
  1589. :group 'org-link
  1590. :type '(choice
  1591. (const relative)
  1592. (const absolute)
  1593. (const noabbrev)
  1594. (const adaptive)))
  1595. (defvaralias 'org-activate-links 'org-highlight-links)
  1596. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1597. "Types of links that should be highlighted in Org files.
  1598. This is a list of symbols, each one of them leading to the
  1599. highlighting of a certain link type.
  1600. You can still open links that are not highlighted.
  1601. In principle, it does not hurt to turn on highlighting for all
  1602. link types. There may be a small gain when turning off unused
  1603. link types. The types are:
  1604. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1605. angle Links in angular brackets that may contain whitespace like
  1606. <bbdb:Carsten Dominik>.
  1607. plain Plain links in normal text, no whitespace, like http://google.com.
  1608. radio Text that is matched by a radio target, see manual for details.
  1609. tag Tag settings in a headline (link to tag search).
  1610. date Time stamps (link to calendar).
  1611. footnote Footnote labels.
  1612. If you set this variable during an Emacs session, use `org-mode-restart'
  1613. in the Org buffer so that the change takes effect."
  1614. :group 'org-link
  1615. :group 'org-appearance
  1616. :type '(set :greedy t
  1617. (const :tag "Double bracket links" bracket)
  1618. (const :tag "Angular bracket links" angle)
  1619. (const :tag "Plain text links" plain)
  1620. (const :tag "Radio target matches" radio)
  1621. (const :tag "Tags" tag)
  1622. (const :tag "Timestamps" date)
  1623. (const :tag "Footnotes" footnote)))
  1624. (defcustom org-make-link-description-function nil
  1625. "Function to use for generating link descriptions from links.
  1626. This function must take two parameters: the first one is the
  1627. link, the second one is the description generated by
  1628. `org-insert-link'. The function should return the description to
  1629. use."
  1630. :group 'org-link
  1631. :type '(choice (const nil) (function)))
  1632. (defgroup org-link-store nil
  1633. "Options concerning storing links in Org mode."
  1634. :tag "Org Store Link"
  1635. :group 'org-link)
  1636. (defcustom org-url-hexify-p t
  1637. "When non-nil, hexify URL when creating a link."
  1638. :type 'boolean
  1639. :version "24.3"
  1640. :group 'org-link-store)
  1641. (defcustom org-email-link-description-format "Email %c: %.30s"
  1642. "Format of the description part of a link to an email or usenet message.
  1643. The following %-escapes will be replaced by corresponding information:
  1644. %F full \"From\" field
  1645. %f name, taken from \"From\" field, address if no name
  1646. %T full \"To\" field
  1647. %t first name in \"To\" field, address if no name
  1648. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1649. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1650. %s subject
  1651. %d date
  1652. %m message-id.
  1653. You may use normal field width specification between the % and the letter.
  1654. This is for example useful to limit the length of the subject.
  1655. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1656. :group 'org-link-store
  1657. :type 'string)
  1658. (defcustom org-from-is-user-regexp
  1659. (let (r1 r2)
  1660. (when (and user-mail-address (not (string= user-mail-address "")))
  1661. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1662. (when (and user-full-name (not (string= user-full-name "")))
  1663. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1664. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1665. "Regexp matched against the \"From:\" header of an email or usenet message.
  1666. It should match if the message is from the user him/herself."
  1667. :group 'org-link-store
  1668. :type 'regexp)
  1669. (defcustom org-context-in-file-links t
  1670. "Non-nil means file links from `org-store-link' contain context.
  1671. \\<org-mode-map>
  1672. A search string will be added to the file name with :: as separator
  1673. and used to find the context when the link is activated by the command
  1674. `org-open-at-point'. When this option is t, the entire active region
  1675. will be placed in the search string of the file link. If set to a
  1676. positive integer, only the first n lines of context will be stored.
  1677. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1678. \\[org-store-link]')
  1679. negates this setting for the duration of the command."
  1680. :group 'org-link-store
  1681. :type '(choice boolean integer))
  1682. (defcustom org-keep-stored-link-after-insertion nil
  1683. "Non-nil means keep link in list for entire session.
  1684. \\<org-mode-map>
  1685. The command `org-store-link' adds a link pointing to the current
  1686. location to an internal list. These links accumulate during a session.
  1687. The command `org-insert-link' can be used to insert links into any
  1688. Org file (offering completion for all stored links).
  1689. When this option is nil, every link which has been inserted once using
  1690. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1691. unused
  1692. links more efficient."
  1693. :group 'org-link-store
  1694. :type 'boolean)
  1695. (defgroup org-link-follow nil
  1696. "Options concerning following links in Org mode."
  1697. :tag "Org Follow Link"
  1698. :group 'org-link)
  1699. (defcustom org-link-translation-function nil
  1700. "Function to translate links with different syntax to Org syntax.
  1701. This can be used to translate links created for example by the Planner
  1702. or emacs-wiki packages to Org syntax.
  1703. The function must accept two parameters, a TYPE containing the link
  1704. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1705. which is everything after the link protocol. It should return a cons
  1706. with possibly modified values of type and path.
  1707. Org contains a function for this, so if you set this variable to
  1708. `org-translate-link-from-planner', you should be able follow many
  1709. links created by planner."
  1710. :group 'org-link-follow
  1711. :type '(choice (const nil) (function)))
  1712. (defcustom org-follow-link-hook nil
  1713. "Hook that is run after a link has been followed."
  1714. :group 'org-link-follow
  1715. :type 'hook)
  1716. (defcustom org-tab-follows-link nil
  1717. "Non-nil means on links TAB will follow the link.
  1718. Needs to be set before org.el is loaded.
  1719. This really should not be used, it does not make sense, and the
  1720. implementation is bad."
  1721. :group 'org-link-follow
  1722. :type 'boolean)
  1723. (defcustom org-return-follows-link nil
  1724. "Non-nil means on links RET will follow the link.
  1725. In tables, the special behavior of RET has precedence."
  1726. :group 'org-link-follow
  1727. :type 'boolean)
  1728. (defcustom org-mouse-1-follows-link
  1729. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1730. "Non-nil means mouse-1 on a link will follow the link.
  1731. A longer mouse click will still set point. Needs to be set
  1732. before org.el is loaded."
  1733. :group 'org-link-follow
  1734. :version "26.1"
  1735. :package-version '(Org . "8.3")
  1736. :type '(choice
  1737. (const :tag "A double click follows the link" double)
  1738. (const :tag "Unconditionally follow the link with mouse-1" t)
  1739. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1740. (defcustom org-mark-ring-length 4
  1741. "Number of different positions to be recorded in the ring.
  1742. Changing this requires a restart of Emacs to work correctly."
  1743. :group 'org-link-follow
  1744. :type 'integer)
  1745. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1746. "Non-nil means internal fuzzy links can only match headlines.
  1747. When nil, the a fuzzy link may point to a target or a named
  1748. construct in the document. When set to the special value
  1749. `query-to-create', offer to create a new headline when none
  1750. matched.
  1751. Spaces and statistics cookies are ignored during heading searches."
  1752. :group 'org-link-follow
  1753. :version "24.1"
  1754. :type '(choice
  1755. (const :tag "Use fuzzy text search" nil)
  1756. (const :tag "Match only exact headline" t)
  1757. (const :tag "Match exact headline or query to create it"
  1758. query-to-create))
  1759. :safe #'symbolp)
  1760. (defcustom org-link-frame-setup
  1761. '((vm . vm-visit-folder-other-frame)
  1762. (vm-imap . vm-visit-imap-folder-other-frame)
  1763. (gnus . org-gnus-no-new-news)
  1764. (file . find-file-other-window)
  1765. (wl . wl-other-frame))
  1766. "Setup the frame configuration for following links.
  1767. When following a link with Emacs, it may often be useful to display
  1768. this link in another window or frame. This variable can be used to
  1769. set this up for the different types of links.
  1770. For VM, use any of
  1771. `vm-visit-folder'
  1772. `vm-visit-folder-other-window'
  1773. `vm-visit-folder-other-frame'
  1774. For Gnus, use any of
  1775. `gnus'
  1776. `gnus-other-frame'
  1777. `org-gnus-no-new-news'
  1778. For FILE, use any of
  1779. `find-file'
  1780. `find-file-other-window'
  1781. `find-file-other-frame'
  1782. For Wanderlust use any of
  1783. `wl'
  1784. `wl-other-frame'
  1785. For the calendar, use the variable `calendar-setup'.
  1786. For BBDB, it is currently only possible to display the matches in
  1787. another window."
  1788. :group 'org-link-follow
  1789. :type '(list
  1790. (cons (const vm)
  1791. (choice
  1792. (const vm-visit-folder)
  1793. (const vm-visit-folder-other-window)
  1794. (const vm-visit-folder-other-frame)))
  1795. (cons (const vm-imap)
  1796. (choice
  1797. (const vm-visit-imap-folder)
  1798. (const vm-visit-imap-folder-other-window)
  1799. (const vm-visit-imap-folder-other-frame)))
  1800. (cons (const gnus)
  1801. (choice
  1802. (const gnus)
  1803. (const gnus-other-frame)
  1804. (const org-gnus-no-new-news)))
  1805. (cons (const file)
  1806. (choice
  1807. (const find-file)
  1808. (const find-file-other-window)
  1809. (const find-file-other-frame)))
  1810. (cons (const wl)
  1811. (choice
  1812. (const wl)
  1813. (const wl-other-frame)))))
  1814. (defcustom org-display-internal-link-with-indirect-buffer nil
  1815. "Non-nil means use indirect buffer to display infile links.
  1816. Activating internal links (from one location in a file to another location
  1817. in the same file) normally just jumps to the location. When the link is
  1818. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1819. is displayed in
  1820. another window. When this option is set, the other window actually displays
  1821. an indirect buffer clone of the current buffer, to avoid any visibility
  1822. changes to the current buffer."
  1823. :group 'org-link-follow
  1824. :type 'boolean)
  1825. (defcustom org-open-non-existing-files nil
  1826. "Non-nil means `org-open-file' will open non-existing files.
  1827. When nil, an error will be generated.
  1828. This variable applies only to external applications because they
  1829. might choke on non-existing files. If the link is to a file that
  1830. will be opened in Emacs, the variable is ignored."
  1831. :group 'org-link-follow
  1832. :type 'boolean)
  1833. (defcustom org-open-directory-means-index-dot-org nil
  1834. "Non-nil means a link to a directory really means to index.org.
  1835. When nil, following a directory link will run dired or open a finder/explorer
  1836. window on that directory."
  1837. :group 'org-link-follow
  1838. :type 'boolean)
  1839. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1840. "Non-nil means ask for confirmation before executing shell links.
  1841. Shell links can be dangerous: just think about a link
  1842. [[shell:rm -rf ~/*][Google Search]]
  1843. This link would show up in your Org document as \"Google Search\",
  1844. but really it would remove your entire home directory.
  1845. Therefore we advise against setting this variable to nil.
  1846. Just change it to `y-or-n-p' if you want to confirm with a
  1847. single keystroke rather than having to type \"yes\"."
  1848. :group 'org-link-follow
  1849. :type '(choice
  1850. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1851. (const :tag "with y-or-n (faster)" y-or-n-p)
  1852. (const :tag "no confirmation (dangerous)" nil)))
  1853. (put 'org-confirm-shell-link-function
  1854. 'safe-local-variable
  1855. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1856. (defcustom org-confirm-shell-link-not-regexp ""
  1857. "A regexp to skip confirmation for shell links."
  1858. :group 'org-link-follow
  1859. :version "24.1"
  1860. :type 'regexp)
  1861. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1862. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1863. Elisp links can be dangerous: just think about a link
  1864. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1865. This link would show up in your Org document as \"Google Search\",
  1866. but really it would remove your entire home directory.
  1867. Therefore we advise against setting this variable to nil.
  1868. Just change it to `y-or-n-p' if you want to confirm with a
  1869. single keystroke rather than having to type \"yes\"."
  1870. :group 'org-link-follow
  1871. :type '(choice
  1872. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1873. (const :tag "with y-or-n (faster)" y-or-n-p)
  1874. (const :tag "no confirmation (dangerous)" nil)))
  1875. (put 'org-confirm-shell-link-function
  1876. 'safe-local-variable
  1877. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1878. (defcustom org-confirm-elisp-link-not-regexp ""
  1879. "A regexp to skip confirmation for Elisp links."
  1880. :group 'org-link-follow
  1881. :version "24.1"
  1882. :type 'regexp)
  1883. (defconst org-file-apps-defaults-gnu
  1884. '((remote . emacs)
  1885. (system . mailcap)
  1886. (t . mailcap))
  1887. "Default file applications on a UNIX or GNU/Linux system.
  1888. See `org-file-apps'.")
  1889. (defconst org-file-apps-defaults-macosx
  1890. '((remote . emacs)
  1891. (system . "open %s")
  1892. ("ps.gz" . "gv %s")
  1893. ("eps.gz" . "gv %s")
  1894. ("dvi" . "xdvi %s")
  1895. ("fig" . "xfig %s")
  1896. (t . "open %s"))
  1897. "Default file applications on a macOS system.
  1898. The system \"open\" is known as a default, but we use X11 applications
  1899. for some files for which the OS does not have a good default.
  1900. See `org-file-apps'.")
  1901. (defconst org-file-apps-defaults-windowsnt
  1902. (list '(remote . emacs)
  1903. (cons 'system (lambda (file _path)
  1904. (with-no-warnings (w32-shell-execute "open" file))))
  1905. (cons t (lambda (file _path)
  1906. (with-no-warnings (w32-shell-execute "open" file)))))
  1907. "Default file applications on a Windows NT system.
  1908. The system \"open\" is used for most files.
  1909. See `org-file-apps'.")
  1910. (defcustom org-file-apps
  1911. '((auto-mode . emacs)
  1912. ("\\.mm\\'" . default)
  1913. ("\\.x?html?\\'" . default)
  1914. ("\\.pdf\\'" . default))
  1915. "External applications for opening `file:path' items in a document.
  1916. \\<org-mode-map>\
  1917. Org mode uses system defaults for different file types, but
  1918. you can use this variable to set the application for a given file
  1919. extension. The entries in this list are cons cells where the car identifies
  1920. files and the cdr the corresponding command.
  1921. Possible values for the file identifier are:
  1922. \"string\" A string as a file identifier can be interpreted in different
  1923. ways, depending on its contents:
  1924. - Alphanumeric characters only:
  1925. Match links with this file extension.
  1926. Example: (\"pdf\" . \"evince %s\")
  1927. to open PDFs with evince.
  1928. - Regular expression: Match links where the
  1929. filename matches the regexp. If you want to
  1930. use groups here, use shy groups.
  1931. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1932. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1933. to open *.html and *.xhtml with firefox.
  1934. - Regular expression which contains (non-shy) groups:
  1935. Match links where the whole link, including \"::\", and
  1936. anything after that, matches the regexp.
  1937. In a custom command string, %1, %2, etc. are replaced with
  1938. the parts of the link that were matched by the groups.
  1939. For backwards compatibility, if a command string is given
  1940. that does not use any of the group matches, this case is
  1941. handled identically to the second one (i.e. match against
  1942. file name only).
  1943. In a custom function, you can access the group matches with
  1944. (match-string n link).
  1945. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1946. \"evince -p %1 %s\")
  1947. to open [[file:document.pdf::5]] with evince at page 5.
  1948. `directory' Matches a directory
  1949. `remote' Matches a remote file, accessible through tramp or efs.
  1950. Remote files most likely should be visited through Emacs
  1951. because external applications cannot handle such paths.
  1952. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1953. so all files Emacs knows how to handle. Using this with
  1954. command `emacs' will open most files in Emacs. Beware that this
  1955. will also open html files inside Emacs, unless you add
  1956. (\"html\" . default) to the list as well.
  1957. `system' The system command to open files, like `open' on Windows
  1958. and macOS, and mailcap under GNU/Linux. This is the command
  1959. that will be selected if you call `org-open-at-point' with a
  1960. double prefix argument (`\\[universal-argument] \
  1961. \\[universal-argument] \\[org-open-at-point]').
  1962. t Default for files not matched by any of the other options.
  1963. Possible values for the command are:
  1964. `emacs' The file will be visited by the current Emacs process.
  1965. `default' Use the default application for this file type, which is the
  1966. association for t in the list, most likely in the system-specific
  1967. part. This can be used to overrule an unwanted setting in the
  1968. system-specific variable.
  1969. `system' Use the system command for opening files, like \"open\".
  1970. This command is specified by the entry whose car is `system'.
  1971. Most likely, the system-specific version of this variable
  1972. does define this command, but you can overrule/replace it
  1973. here.
  1974. `mailcap' Use command specified in the mailcaps.
  1975. string A command to be executed by a shell; %s will be replaced
  1976. by the path to the file.
  1977. function A Lisp function, which will be called with two arguments:
  1978. the file path and the original link string, without the
  1979. \"file:\" prefix.
  1980. For more examples, see the system specific constants
  1981. `org-file-apps-defaults-macosx'
  1982. `org-file-apps-defaults-windowsnt'
  1983. `org-file-apps-defaults-gnu'."
  1984. :group 'org-link-follow
  1985. :type '(repeat
  1986. (cons (choice :value ""
  1987. (string :tag "Extension")
  1988. (const :tag "System command to open files" system)
  1989. (const :tag "Default for unrecognized files" t)
  1990. (const :tag "Remote file" remote)
  1991. (const :tag "Links to a directory" directory)
  1992. (const :tag "Any files that have Emacs modes"
  1993. auto-mode))
  1994. (choice :value ""
  1995. (const :tag "Visit with Emacs" emacs)
  1996. (const :tag "Use default" default)
  1997. (const :tag "Use the system command" system)
  1998. (string :tag "Command")
  1999. (function :tag "Function")))))
  2000. (defcustom org-doi-server-url "http://dx.doi.org/"
  2001. "The URL of the DOI server."
  2002. :type 'string
  2003. :version "24.3"
  2004. :group 'org-link-follow)
  2005. (defgroup org-refile nil
  2006. "Options concerning refiling entries in Org mode."
  2007. :tag "Org Refile"
  2008. :group 'org)
  2009. (defcustom org-directory "~/org"
  2010. "Directory with Org files.
  2011. This is just a default location to look for Org files. There is no need
  2012. at all to put your files into this directory. It is used in the
  2013. following situations:
  2014. 1. When a capture template specifies a target file that is not an
  2015. absolute path. The path will then be interpreted relative to
  2016. `org-directory'
  2017. 2. When the value of variable `org-agenda-files' is a single file, any
  2018. relative paths in this file will be taken as relative to
  2019. `org-directory'."
  2020. :group 'org-refile
  2021. :group 'org-capture
  2022. :type 'directory)
  2023. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2024. "Default target for storing notes.
  2025. Used as a fall back file for org-capture.el, for templates that
  2026. do not specify a target file."
  2027. :group 'org-refile
  2028. :group 'org-capture
  2029. :type 'file)
  2030. (defcustom org-reverse-note-order nil
  2031. "Non-nil means store new notes at the beginning of a file or entry.
  2032. When nil, new notes will be filed to the end of a file or entry.
  2033. This can also be a list with cons cells of regular expressions that
  2034. are matched against file names, and values."
  2035. :group 'org-capture
  2036. :group 'org-refile
  2037. :type '(choice
  2038. (const :tag "Reverse always" t)
  2039. (const :tag "Reverse never" nil)
  2040. (repeat :tag "By file name regexp"
  2041. (cons regexp boolean))))
  2042. (defcustom org-log-refile nil
  2043. "Information to record when a task is refiled.
  2044. Possible values are:
  2045. nil Don't add anything
  2046. time Add a time stamp to the task
  2047. note Prompt for a note and add it with template `org-log-note-headings'
  2048. This option can also be set with on a per-file-basis with
  2049. #+STARTUP: nologrefile
  2050. #+STARTUP: logrefile
  2051. #+STARTUP: lognoterefile
  2052. You can have local logging settings for a subtree by setting the LOGGING
  2053. property to one or more of these keywords.
  2054. When bulk-refiling from the agenda, the value `note' is forbidden and
  2055. will temporarily be changed to `time'."
  2056. :group 'org-refile
  2057. :group 'org-progress
  2058. :version "24.1"
  2059. :type '(choice
  2060. (const :tag "No logging" nil)
  2061. (const :tag "Record timestamp" time)
  2062. (const :tag "Record timestamp with note." note)))
  2063. (defcustom org-refile-targets nil
  2064. "Targets for refiling entries with `\\[org-refile]'.
  2065. This is a list of cons cells. Each cell contains:
  2066. - a specification of the files to be considered, either a list of files,
  2067. or a symbol whose function or variable value will be used to retrieve
  2068. a file name or a list of file names. If you use `org-agenda-files' for
  2069. that, all agenda files will be scanned for targets. Nil means consider
  2070. headings in the current buffer.
  2071. - A specification of how to find candidate refile targets. This may be
  2072. any of:
  2073. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2074. This tag has to be present in all target headlines, inheritance will
  2075. not be considered.
  2076. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2077. todo keyword.
  2078. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2079. headlines that are refiling targets.
  2080. - a cons cell (:level . N). Any headline of level N is considered a target.
  2081. Note that, when `org-odd-levels-only' is set, level corresponds to
  2082. order in hierarchy, not to the number of stars.
  2083. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2084. Note that, when `org-odd-levels-only' is set, level corresponds to
  2085. order in hierarchy, not to the number of stars.
  2086. Each element of this list generates a set of possible targets.
  2087. The union of these sets is presented (with completion) to
  2088. the user by `org-refile'.
  2089. You can set the variable `org-refile-target-verify-function' to a function
  2090. to verify each headline found by the simple criteria above.
  2091. When this variable is nil, all top-level headlines in the current buffer
  2092. are used, equivalent to the value `((nil . (:level . 1))'."
  2093. :group 'org-refile
  2094. :type '(repeat
  2095. (cons
  2096. (choice :value org-agenda-files
  2097. (const :tag "All agenda files" org-agenda-files)
  2098. (const :tag "Current buffer" nil)
  2099. (function) (variable) (file))
  2100. (choice :tag "Identify target headline by"
  2101. (cons :tag "Specific tag" (const :value :tag) (string))
  2102. (cons :tag "TODO keyword" (const :value :todo) (string))
  2103. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2104. (cons :tag "Level number" (const :value :level) (integer))
  2105. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2106. (defcustom org-refile-target-verify-function nil
  2107. "Function to verify if the headline at point should be a refile target.
  2108. The function will be called without arguments, with point at the
  2109. beginning of the headline. It should return t and leave point
  2110. where it is if the headline is a valid target for refiling.
  2111. If the target should not be selected, the function must return nil.
  2112. In addition to this, it may move point to a place from where the search
  2113. should be continued. For example, the function may decide that the entire
  2114. subtree of the current entry should be excluded and move point to the end
  2115. of the subtree."
  2116. :group 'org-refile
  2117. :type '(choice
  2118. (const nil)
  2119. (function)))
  2120. (defcustom org-refile-use-cache nil
  2121. "Non-nil means cache refile targets to speed up the process.
  2122. \\<org-mode-map>\
  2123. The cache for a particular file will be updated automatically when
  2124. the buffer has been killed, or when any of the marker used for flagging
  2125. refile targets no longer points at a live buffer.
  2126. If you have added new entries to a buffer that might themselves be targets,
  2127. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2128. if you find that easier, \
  2129. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2130. \\[org-refile]'."
  2131. :group 'org-refile
  2132. :version "24.1"
  2133. :type 'boolean)
  2134. (defcustom org-refile-use-outline-path nil
  2135. "Non-nil means provide refile targets as paths.
  2136. So a level 3 headline will be available as level1/level2/level3.
  2137. When the value is `file', also include the file name (without directory)
  2138. into the path. In this case, you can also stop the completion after
  2139. the file name, to get entries inserted as top level in the file.
  2140. When `full-file-path', include the full file path.
  2141. When `buffer-name', use the buffer name."
  2142. :group 'org-refile
  2143. :type '(choice
  2144. (const :tag "Not" nil)
  2145. (const :tag "Yes" t)
  2146. (const :tag "Start with file name" file)
  2147. (const :tag "Start with full file path" full-file-path)
  2148. (const :tag "Start with buffer name" buffer-name)))
  2149. (defcustom org-outline-path-complete-in-steps t
  2150. "Non-nil means complete the outline path in hierarchical steps.
  2151. When Org uses the refile interface to select an outline path (see
  2152. `org-refile-use-outline-path'), the completion of the path can be
  2153. done in a single go, or it can be done in steps down the headline
  2154. hierarchy. Going in steps is probably the best if you do not use
  2155. a special completion package like `ido' or `icicles'. However,
  2156. when using these packages, going in one step can be very fast,
  2157. while still showing the whole path to the entry."
  2158. :group 'org-refile
  2159. :type 'boolean)
  2160. (defcustom org-refile-allow-creating-parent-nodes nil
  2161. "Non-nil means allow the creation of new nodes as refile targets.
  2162. New nodes are then created by adding \"/new node name\" to the completion
  2163. of an existing node. When the value of this variable is `confirm',
  2164. new node creation must be confirmed by the user (recommended).
  2165. When nil, the completion must match an existing entry.
  2166. Note that, if the new heading is not seen by the criteria
  2167. listed in `org-refile-targets', multiple instances of the same
  2168. heading would be created by trying again to file under the new
  2169. heading."
  2170. :group 'org-refile
  2171. :type '(choice
  2172. (const :tag "Never" nil)
  2173. (const :tag "Always" t)
  2174. (const :tag "Prompt for confirmation" confirm)))
  2175. (defcustom org-refile-active-region-within-subtree nil
  2176. "Non-nil means also refile active region within a subtree.
  2177. By default `org-refile' doesn't allow refiling regions if they
  2178. don't contain a set of subtrees, but it might be convenient to
  2179. do so sometimes: in that case, the first line of the region is
  2180. converted to a headline before refiling."
  2181. :group 'org-refile
  2182. :version "24.1"
  2183. :type 'boolean)
  2184. (defgroup org-todo nil
  2185. "Options concerning TODO items in Org mode."
  2186. :tag "Org TODO"
  2187. :group 'org)
  2188. (defgroup org-progress nil
  2189. "Options concerning Progress logging in Org mode."
  2190. :tag "Org Progress"
  2191. :group 'org-time)
  2192. (defvar org-todo-interpretation-widgets
  2193. '((:tag "Sequence (cycling hits every state)" sequence)
  2194. (:tag "Type (cycling directly to DONE)" type))
  2195. "The available interpretation symbols for customizing `org-todo-keywords'.
  2196. Interested libraries should add to this list.")
  2197. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2198. "List of TODO entry keyword sequences and their interpretation.
  2199. \\<org-mode-map>This is a list of sequences.
  2200. Each sequence starts with a symbol, either `sequence' or `type',
  2201. indicating if the keywords should be interpreted as a sequence of
  2202. action steps, or as different types of TODO items. The first
  2203. keywords are states requiring action - these states will select a headline
  2204. for inclusion into the global TODO list Org produces. If one of the
  2205. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2206. signify that no further action is necessary. If \"|\" is not found,
  2207. the last keyword is treated as the only DONE state of the sequence.
  2208. The command `\\[org-todo]' cycles an entry through these states, and one
  2209. additional state where no keyword is present. For details about this
  2210. cycling, see the manual.
  2211. TODO keywords and interpretation can also be set on a per-file basis with
  2212. the special #+SEQ_TODO and #+TYP_TODO lines.
  2213. Each keyword can optionally specify a character for fast state selection
  2214. \(in combination with the variable `org-use-fast-todo-selection')
  2215. and specifiers for state change logging, using the same syntax that
  2216. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2217. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2218. indicates to record a time stamp each time this state is selected.
  2219. Each keyword may also specify if a timestamp or a note should be
  2220. recorded when entering or leaving the state, by adding additional
  2221. characters in the parenthesis after the keyword. This looks like this:
  2222. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2223. record only the time of the state change. With X and Y being either
  2224. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2225. Y when leaving the state if and only if the *target* state does not
  2226. define X. You may omit any of the fast-selection key or X or /Y,
  2227. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2228. For backward compatibility, this variable may also be just a list
  2229. of keywords. In this case the interpretation (sequence or type) will be
  2230. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2231. :group 'org-todo
  2232. :group 'org-keywords
  2233. :type '(choice
  2234. (repeat :tag "Old syntax, just keywords"
  2235. (string :tag "Keyword"))
  2236. (repeat :tag "New syntax"
  2237. (cons
  2238. (choice
  2239. :tag "Interpretation"
  2240. ;;Quick and dirty way to see
  2241. ;;`org-todo-interpretations'. This takes the
  2242. ;;place of item arguments
  2243. :convert-widget
  2244. (lambda (widget)
  2245. (widget-put widget
  2246. :args (mapcar
  2247. (lambda (x)
  2248. (widget-convert
  2249. (cons 'const x)))
  2250. org-todo-interpretation-widgets))
  2251. widget))
  2252. (repeat
  2253. (string :tag "Keyword"))))))
  2254. (defvar-local org-todo-keywords-1 nil
  2255. "All TODO and DONE keywords active in a buffer.")
  2256. (defvar org-todo-keywords-for-agenda nil)
  2257. (defvar org-done-keywords-for-agenda nil)
  2258. (defvar org-todo-keyword-alist-for-agenda nil)
  2259. (defvar org-tag-alist-for-agenda nil
  2260. "Alist of all tags from all agenda files.")
  2261. (defvar org-tag-groups-alist-for-agenda nil
  2262. "Alist of all groups tags from all current agenda files.")
  2263. (defvar-local org-tag-groups-alist nil)
  2264. (defvar org-agenda-contributing-files nil)
  2265. (defvar-local org-current-tag-alist nil
  2266. "Alist of all tag groups in current buffer.
  2267. This variable takes into consideration `org-tag-alist',
  2268. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2269. (defvar-local org-not-done-keywords nil)
  2270. (defvar-local org-done-keywords nil)
  2271. (defvar-local org-todo-heads nil)
  2272. (defvar-local org-todo-sets nil)
  2273. (defvar-local org-todo-log-states nil)
  2274. (defvar-local org-todo-kwd-alist nil)
  2275. (defvar-local org-todo-key-alist nil)
  2276. (defvar-local org-todo-key-trigger nil)
  2277. (defcustom org-todo-interpretation 'sequence
  2278. "Controls how TODO keywords are interpreted.
  2279. This variable is in principle obsolete and is only used for
  2280. backward compatibility, if the interpretation of todo keywords is
  2281. not given already in `org-todo-keywords'. See that variable for
  2282. more information."
  2283. :group 'org-todo
  2284. :group 'org-keywords
  2285. :type '(choice (const sequence)
  2286. (const type)))
  2287. (defcustom org-use-fast-todo-selection t
  2288. "\\<org-mode-map>\
  2289. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2290. This variable describes if and under what circumstances the cycling
  2291. mechanism for TODO keywords will be replaced by a single-key, direct
  2292. selection scheme.
  2293. When nil, fast selection is never used.
  2294. When the symbol `prefix', it will be used when `org-todo' is called
  2295. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2296. in an Org buffer, and
  2297. `\\[universal-argument] t' in an agenda buffer.
  2298. When t, fast selection is used by default. In this case, the prefix
  2299. argument forces cycling instead.
  2300. In all cases, the special interface is only used if access keys have
  2301. actually been assigned by the user, i.e. if keywords in the configuration
  2302. are followed by a letter in parenthesis, like TODO(t)."
  2303. :group 'org-todo
  2304. :type '(choice
  2305. (const :tag "Never" nil)
  2306. (const :tag "By default" t)
  2307. (const :tag "Only with C-u C-c C-t" prefix)))
  2308. (defcustom org-provide-todo-statistics t
  2309. "Non-nil means update todo statistics after insert and toggle.
  2310. ALL-HEADLINES means update todo statistics by including headlines
  2311. with no TODO keyword as well, counting them as not done.
  2312. A list of TODO keywords means the same, but skip keywords that are
  2313. not in this list.
  2314. When set to a list of two lists, the first list contains keywords
  2315. to consider as TODO keywords, the second list contains keywords
  2316. to consider as DONE keywords.
  2317. When this is set, todo statistics is updated in the parent of the
  2318. current entry each time a todo state is changed."
  2319. :group 'org-todo
  2320. :type '(choice
  2321. (const :tag "Yes, only for TODO entries" t)
  2322. (const :tag "Yes, including all entries" all-headlines)
  2323. (repeat :tag "Yes, for TODOs in this list"
  2324. (string :tag "TODO keyword"))
  2325. (list :tag "Yes, for TODOs and DONEs in these lists"
  2326. (repeat (string :tag "TODO keyword"))
  2327. (repeat (string :tag "DONE keyword")))
  2328. (other :tag "No TODO statistics" nil)))
  2329. (defcustom org-hierarchical-todo-statistics t
  2330. "Non-nil means TODO statistics covers just direct children.
  2331. When nil, all entries in the subtree are considered.
  2332. This has only an effect if `org-provide-todo-statistics' is set.
  2333. To set this to nil for only a single subtree, use a COOKIE_DATA
  2334. property and include the word \"recursive\" into the value."
  2335. :group 'org-todo
  2336. :type 'boolean)
  2337. (defcustom org-after-todo-state-change-hook nil
  2338. "Hook which is run after the state of a TODO item was changed.
  2339. The new state (a string with a TODO keyword, or nil) is available in the
  2340. Lisp variable `org-state'."
  2341. :group 'org-todo
  2342. :type 'hook)
  2343. (defvar org-blocker-hook nil
  2344. "Hook for functions that are allowed to block a state change.
  2345. Functions in this hook should not modify the buffer.
  2346. Each function gets as its single argument a property list,
  2347. see `org-trigger-hook' for more information about this list.
  2348. If any of the functions in this hook returns nil, the state change
  2349. is blocked.")
  2350. (defvar org-trigger-hook nil
  2351. "Hook for functions that are triggered by a state change.
  2352. Each function gets as its single argument a property list with at
  2353. least the following elements:
  2354. (:type type-of-change :position pos-at-entry-start
  2355. :from old-state :to new-state)
  2356. Depending on the type, more properties may be present.
  2357. This mechanism is currently implemented for:
  2358. TODO state changes
  2359. ------------------
  2360. :type todo-state-change
  2361. :from previous state (keyword as a string), or nil, or a symbol
  2362. `todo' or `done', to indicate the general type of state.
  2363. :to new state, like in :from")
  2364. (defcustom org-enforce-todo-dependencies nil
  2365. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2366. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2367. be blocked if any prior sibling is not yet done.
  2368. Finally, if the parent is blocked because of ordered siblings of its own,
  2369. the child will also be blocked."
  2370. :set (lambda (var val)
  2371. (set var val)
  2372. (if val
  2373. (add-hook 'org-blocker-hook
  2374. 'org-block-todo-from-children-or-siblings-or-parent)
  2375. (remove-hook 'org-blocker-hook
  2376. 'org-block-todo-from-children-or-siblings-or-parent)))
  2377. :group 'org-todo
  2378. :type 'boolean)
  2379. (defcustom org-enforce-todo-checkbox-dependencies nil
  2380. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2381. When this is nil, checkboxes have no influence on switching TODO states.
  2382. When non-nil, you first need to check off all check boxes before the TODO
  2383. entry can be switched to DONE.
  2384. This variable needs to be set before org.el is loaded, and you need to
  2385. restart Emacs after a change to make the change effective. The only way
  2386. to change is while Emacs is running is through the customize interface."
  2387. :set (lambda (var val)
  2388. (set var val)
  2389. (if val
  2390. (add-hook 'org-blocker-hook
  2391. 'org-block-todo-from-checkboxes)
  2392. (remove-hook 'org-blocker-hook
  2393. 'org-block-todo-from-checkboxes)))
  2394. :group 'org-todo
  2395. :type 'boolean)
  2396. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2397. "Non-nil means inserting a TODO heading is treated as state change.
  2398. So when the command `\\[org-insert-todo-heading]' is used, state change
  2399. logging will apply if appropriate. When nil, the new TODO item will
  2400. be inserted directly, and no logging will take place."
  2401. :group 'org-todo
  2402. :type 'boolean)
  2403. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2404. "Non-nil means switching TODO states with S-cursor counts as state change.
  2405. This is the default behavior. However, setting this to nil allows a
  2406. convenient way to select a TODO state and bypass any logging associated
  2407. with that."
  2408. :group 'org-todo
  2409. :type 'boolean)
  2410. (defcustom org-todo-state-tags-triggers nil
  2411. "Tag changes that should be triggered by TODO state changes.
  2412. This is a list. Each entry is
  2413. (state-change (tag . flag) .......)
  2414. State-change can be a string with a state, and empty string to indicate the
  2415. state that has no TODO keyword, or it can be one of the symbols `todo'
  2416. or `done', meaning any not-done or done state, respectively."
  2417. :group 'org-todo
  2418. :group 'org-tags
  2419. :type '(repeat
  2420. (cons (choice :tag "When changing to"
  2421. (const :tag "Not-done state" todo)
  2422. (const :tag "Done state" done)
  2423. (string :tag "State"))
  2424. (repeat
  2425. (cons :tag "Tag action"
  2426. (string :tag "Tag")
  2427. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2428. (defcustom org-log-done nil
  2429. "Information to record when a task moves to the DONE state.
  2430. Possible values are:
  2431. nil Don't add anything, just change the keyword
  2432. time Add a time stamp to the task
  2433. note Prompt for a note and add it with template `org-log-note-headings'
  2434. This option can also be set with on a per-file-basis with
  2435. #+STARTUP: nologdone
  2436. #+STARTUP: logdone
  2437. #+STARTUP: lognotedone
  2438. You can have local logging settings for a subtree by setting the LOGGING
  2439. property to one or more of these keywords."
  2440. :group 'org-todo
  2441. :group 'org-progress
  2442. :type '(choice
  2443. (const :tag "No logging" nil)
  2444. (const :tag "Record CLOSED timestamp" time)
  2445. (const :tag "Record CLOSED timestamp with note." note)))
  2446. ;; Normalize old uses of org-log-done.
  2447. (cond
  2448. ((eq org-log-done t) (setq org-log-done 'time))
  2449. ((and (listp org-log-done) (memq 'done org-log-done))
  2450. (setq org-log-done 'note)))
  2451. (defcustom org-log-reschedule nil
  2452. "Information to record when the scheduling date of a tasks is modified.
  2453. Possible values are:
  2454. nil Don't add anything, just change the date
  2455. time Add a time stamp to the task
  2456. note Prompt for a note and add it with template `org-log-note-headings'
  2457. This option can also be set with on a per-file-basis with
  2458. #+STARTUP: nologreschedule
  2459. #+STARTUP: logreschedule
  2460. #+STARTUP: lognotereschedule"
  2461. :group 'org-todo
  2462. :group 'org-progress
  2463. :type '(choice
  2464. (const :tag "No logging" nil)
  2465. (const :tag "Record timestamp" time)
  2466. (const :tag "Record timestamp with note." note)))
  2467. (defcustom org-log-redeadline nil
  2468. "Information to record when the deadline date of a tasks is modified.
  2469. Possible values are:
  2470. nil Don't add anything, just change the date
  2471. time Add a time stamp to the task
  2472. note Prompt for a note and add it with template `org-log-note-headings'
  2473. This option can also be set with on a per-file-basis with
  2474. #+STARTUP: nologredeadline
  2475. #+STARTUP: logredeadline
  2476. #+STARTUP: lognoteredeadline
  2477. You can have local logging settings for a subtree by setting the LOGGING
  2478. property to one or more of these keywords."
  2479. :group 'org-todo
  2480. :group 'org-progress
  2481. :type '(choice
  2482. (const :tag "No logging" nil)
  2483. (const :tag "Record timestamp" time)
  2484. (const :tag "Record timestamp with note." note)))
  2485. (defcustom org-log-note-clock-out nil
  2486. "Non-nil means record a note when clocking out of an item.
  2487. This can also be configured on a per-file basis by adding one of
  2488. the following lines anywhere in the buffer:
  2489. #+STARTUP: lognoteclock-out
  2490. #+STARTUP: nolognoteclock-out"
  2491. :group 'org-todo
  2492. :group 'org-progress
  2493. :type 'boolean)
  2494. (defcustom org-log-done-with-time t
  2495. "Non-nil means the CLOSED time stamp will contain date and time.
  2496. When nil, only the date will be recorded."
  2497. :group 'org-progress
  2498. :type 'boolean)
  2499. (defcustom org-log-note-headings
  2500. '((done . "CLOSING NOTE %t")
  2501. (state . "State %-12s from %-12S %t")
  2502. (note . "Note taken on %t")
  2503. (reschedule . "Rescheduled from %S on %t")
  2504. (delschedule . "Not scheduled, was %S on %t")
  2505. (redeadline . "New deadline from %S on %t")
  2506. (deldeadline . "Removed deadline, was %S on %t")
  2507. (refile . "Refiled on %t")
  2508. (clock-out . ""))
  2509. "Headings for notes added to entries.
  2510. The value is an alist, with the car being a symbol indicating the
  2511. note context, and the cdr is the heading to be used. The heading
  2512. may also be the empty string. The following placeholders can be
  2513. used:
  2514. %t a time stamp.
  2515. %T an active time stamp instead the default inactive one
  2516. %d a short-format time stamp.
  2517. %D an active short-format time stamp.
  2518. %s the new TODO state or time stamp (inactive), in double quotes.
  2519. %S the old TODO state or time stamp (inactive), in double quotes.
  2520. %u the user name.
  2521. %U full user name.
  2522. In fact, it is not a good idea to change the `state' entry,
  2523. because Agenda Log mode depends on the format of these entries."
  2524. :group 'org-todo
  2525. :group 'org-progress
  2526. :type '(list :greedy t
  2527. (cons (const :tag "Heading when closing an item" done) string)
  2528. (cons (const :tag
  2529. "Heading when changing todo state (todo sequence only)"
  2530. state) string)
  2531. (cons (const :tag "Heading when just taking a note" note) string)
  2532. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2533. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2534. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2535. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2536. (cons (const :tag "Heading when refiling" refile) string)
  2537. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2538. (unless (assq 'note org-log-note-headings)
  2539. (push '(note . "%t") org-log-note-headings))
  2540. (defcustom org-log-into-drawer nil
  2541. "Non-nil means insert state change notes and time stamps into a drawer.
  2542. When nil, state changes notes will be inserted after the headline and
  2543. any scheduling and clock lines, but not inside a drawer.
  2544. The value of this variable should be the name of the drawer to use.
  2545. LOGBOOK is proposed as the default drawer for this purpose, you can
  2546. also set this to a string to define the drawer of your choice.
  2547. A value of t is also allowed, representing \"LOGBOOK\".
  2548. A value of t or nil can also be set with on a per-file-basis with
  2549. #+STARTUP: logdrawer
  2550. #+STARTUP: nologdrawer
  2551. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2552. will be ignored.
  2553. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2554. a subtree.
  2555. Do not check directly this variable in a Lisp program. Call
  2556. function `org-log-into-drawer' instead."
  2557. :group 'org-todo
  2558. :group 'org-progress
  2559. :type '(choice
  2560. (const :tag "Not into a drawer" nil)
  2561. (const :tag "LOGBOOK" t)
  2562. (string :tag "Other")))
  2563. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2564. (defun org-log-into-drawer ()
  2565. "Name of the log drawer, as a string, or nil.
  2566. This is the value of `org-log-into-drawer'. However, if the
  2567. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2568. be used instead of the default value."
  2569. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2570. (cond ((equal p "nil") nil)
  2571. ((equal p "t") "LOGBOOK")
  2572. ((stringp p) p)
  2573. (p "LOGBOOK")
  2574. ((stringp org-log-into-drawer) org-log-into-drawer)
  2575. (org-log-into-drawer "LOGBOOK"))))
  2576. (defcustom org-log-state-notes-insert-after-drawers nil
  2577. "Non-nil means insert state change notes after any drawers in entry.
  2578. Only the drawers that *immediately* follow the headline and the
  2579. deadline/scheduled line are skipped.
  2580. When nil, insert notes right after the heading and perhaps the line
  2581. with deadline/scheduling if present.
  2582. This variable will have no effect if `org-log-into-drawer' is
  2583. set."
  2584. :group 'org-todo
  2585. :group 'org-progress
  2586. :type 'boolean)
  2587. (defcustom org-log-states-order-reversed t
  2588. "Non-nil means the latest state note will be directly after heading.
  2589. When nil, the state change notes will be ordered according to time.
  2590. This option can also be set with on a per-file-basis with
  2591. #+STARTUP: logstatesreversed
  2592. #+STARTUP: nologstatesreversed"
  2593. :group 'org-todo
  2594. :group 'org-progress
  2595. :type 'boolean)
  2596. (defcustom org-todo-repeat-to-state nil
  2597. "The TODO state to which a repeater should return the repeating task.
  2598. By default this is the first task of a TODO sequence or the
  2599. previous state of a TYPE_TODO set. But you can specify to use
  2600. the previous state in a TODO sequence or a string.
  2601. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2602. entry, which has precedence over this option."
  2603. :group 'org-todo
  2604. :version "24.1"
  2605. :type '(choice (const :tag "Use the previous TODO state" t)
  2606. (const :tag "Use the head of the TODO sequence" nil)
  2607. (string :tag "Use a specific TODO state")))
  2608. (defcustom org-log-repeat 'time
  2609. "Non-nil means record moving through the DONE state when triggering repeat.
  2610. An auto-repeating task is immediately switched back to TODO when
  2611. marked DONE. If you are not logging state changes (by adding \"@\"
  2612. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2613. record a closing note, there will be no record of the task moving
  2614. through DONE. This variable forces taking a note anyway.
  2615. nil Don't force a record
  2616. time Record a time stamp
  2617. note Prompt for a note and add it with template `org-log-note-headings'
  2618. This option can also be set with on a per-file-basis with
  2619. #+STARTUP: nologrepeat
  2620. #+STARTUP: logrepeat
  2621. #+STARTUP: lognoterepeat
  2622. You can have local logging settings for a subtree by setting the LOGGING
  2623. property to one or more of these keywords."
  2624. :group 'org-todo
  2625. :group 'org-progress
  2626. :type '(choice
  2627. (const :tag "Don't force a record" nil)
  2628. (const :tag "Force recording the DONE state" time)
  2629. (const :tag "Force recording a note with the DONE state" note)))
  2630. (defgroup org-priorities nil
  2631. "Priorities in Org mode."
  2632. :tag "Org Priorities"
  2633. :group 'org-todo)
  2634. (defcustom org-enable-priority-commands t
  2635. "Non-nil means priority commands are active.
  2636. When nil, these commands will be disabled, so that you never accidentally
  2637. set a priority."
  2638. :group 'org-priorities
  2639. :type 'boolean)
  2640. (defcustom org-highest-priority ?A
  2641. "The highest priority of TODO items. A character like ?A, ?B etc.
  2642. Must have a smaller ASCII number than `org-lowest-priority'."
  2643. :group 'org-priorities
  2644. :type 'character)
  2645. (defcustom org-lowest-priority ?C
  2646. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2647. Must have a larger ASCII number than `org-highest-priority'."
  2648. :group 'org-priorities
  2649. :type 'character)
  2650. (defcustom org-default-priority ?B
  2651. "The default priority of TODO items.
  2652. This is the priority an item gets if no explicit priority is given.
  2653. When starting to cycle on an empty priority the first step in the cycle
  2654. depends on `org-priority-start-cycle-with-default'. The resulting first
  2655. step priority must not exceed the range from `org-highest-priority' to
  2656. `org-lowest-priority' which means that `org-default-priority' has to be
  2657. in this range exclusive or inclusive the range boundaries. Else the
  2658. first step refuses to set the default and the second will fall back
  2659. to (depending on the command used) the highest or lowest priority."
  2660. :group 'org-priorities
  2661. :type 'character)
  2662. (defcustom org-priority-start-cycle-with-default t
  2663. "Non-nil means start with default priority when starting to cycle.
  2664. When this is nil, the first step in the cycle will be (depending on the
  2665. command used) one higher or lower than the default priority.
  2666. See also `org-default-priority'."
  2667. :group 'org-priorities
  2668. :type 'boolean)
  2669. (defcustom org-get-priority-function nil
  2670. "Function to extract the priority from a string.
  2671. The string is normally the headline. If this is nil Org computes the
  2672. priority from the priority cookie like [#A] in the headline. It returns
  2673. an integer, increasing by 1000 for each priority level.
  2674. The user can set a different function here, which should take a string
  2675. as an argument and return the numeric priority."
  2676. :group 'org-priorities
  2677. :version "24.1"
  2678. :type '(choice
  2679. (const nil)
  2680. (function)))
  2681. (defgroup org-time nil
  2682. "Options concerning time stamps and deadlines in Org mode."
  2683. :tag "Org Time"
  2684. :group 'org)
  2685. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2686. "Number of minutes to round time stamps to.
  2687. \\<org-mode-map>\
  2688. These are two values, the first applies when first creating a time stamp.
  2689. The second applies when changing it with the commands `S-up' and `S-down'.
  2690. When changing the time stamp, this means that it will change in steps
  2691. of N minutes, as given by the second value.
  2692. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2693. numbers should be factors of 60, so for example 5, 10, 15.
  2694. When this is larger than 1, you can still force an exact time stamp by using
  2695. a double prefix argument to a time stamp command like \
  2696. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2697. and by using a prefix arg to `S-up/down' to specify the exact number
  2698. of minutes to shift."
  2699. :group 'org-time
  2700. :get (lambda (var) ; Make sure both elements are there
  2701. (if (integerp (default-value var))
  2702. (list (default-value var) 5)
  2703. (default-value var)))
  2704. :type '(list
  2705. (integer :tag "when inserting times")
  2706. (integer :tag "when modifying times")))
  2707. ;; Normalize old customizations of this variable.
  2708. (when (integerp org-time-stamp-rounding-minutes)
  2709. (setq org-time-stamp-rounding-minutes
  2710. (list org-time-stamp-rounding-minutes
  2711. org-time-stamp-rounding-minutes)))
  2712. (defcustom org-display-custom-times nil
  2713. "Non-nil means overlay custom formats over all time stamps.
  2714. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2715. To turn this on on a per-file basis, insert anywhere in the file:
  2716. #+STARTUP: customtime"
  2717. :group 'org-time
  2718. :set 'set-default
  2719. :type 'sexp)
  2720. (make-variable-buffer-local 'org-display-custom-times)
  2721. (defcustom org-time-stamp-custom-formats
  2722. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2723. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2724. These are overlaid over the default ISO format if the variable
  2725. `org-display-custom-times' is set. Time like %H:%M should be at the
  2726. end of the second format. The custom formats are also honored by export
  2727. commands, if custom time display is turned on at the time of export."
  2728. :group 'org-time
  2729. :type 'sexp)
  2730. (defun org-time-stamp-format (&optional long inactive)
  2731. "Get the right format for a time string."
  2732. (let ((f (if long (cdr org-time-stamp-formats)
  2733. (car org-time-stamp-formats))))
  2734. (if inactive
  2735. (concat "[" (substring f 1 -1) "]")
  2736. f)))
  2737. (defcustom org-deadline-warning-days 14
  2738. "Number of days before expiration during which a deadline becomes active.
  2739. This variable governs the display in sparse trees and in the agenda.
  2740. When 0 or negative, it means use this number (the absolute value of it)
  2741. even if a deadline has a different individual lead time specified.
  2742. Custom commands can set this variable in the options section."
  2743. :group 'org-time
  2744. :group 'org-agenda-daily/weekly
  2745. :type 'integer)
  2746. (defcustom org-scheduled-delay-days 0
  2747. "Number of days before a scheduled item becomes active.
  2748. This variable governs the display in sparse trees and in the agenda.
  2749. The default value (i.e. 0) means: don't delay scheduled item.
  2750. When negative, it means use this number (the absolute value of it)
  2751. even if a scheduled item has a different individual delay time
  2752. specified.
  2753. Custom commands can set this variable in the options section."
  2754. :group 'org-time
  2755. :group 'org-agenda-daily/weekly
  2756. :version "24.4"
  2757. :package-version '(Org . "8.0")
  2758. :type 'integer)
  2759. (defcustom org-read-date-prefer-future t
  2760. "Non-nil means assume future for incomplete date input from user.
  2761. This affects the following situations:
  2762. 1. The user gives a month but not a year.
  2763. For example, if it is April and you enter \"feb 2\", this will be read
  2764. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2765. 2. The user gives a day, but no month.
  2766. For example, if today is the 15th, and you enter \"3\", Org will read
  2767. this as the third of *next* month. However, if you enter \"17\",
  2768. it will be considered as *this* month.
  2769. If you set this variable to the symbol `time', then also the following
  2770. will work:
  2771. 3. If the user gives a time.
  2772. If the time is before now, it will be interpreted as tomorrow.
  2773. Currently none of this works for ISO week specifications.
  2774. When this option is nil, the current day, month and year will always be
  2775. used as defaults.
  2776. See also `org-agenda-jump-prefer-future'."
  2777. :group 'org-time
  2778. :type '(choice
  2779. (const :tag "Never" nil)
  2780. (const :tag "Check month and day" t)
  2781. (const :tag "Check month, day, and time" time)))
  2782. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2783. "Should the agenda jump command prefer the future for incomplete dates?
  2784. The default is to do the same as configured in `org-read-date-prefer-future'.
  2785. But you can also set a deviating value here.
  2786. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2787. :group 'org-agenda
  2788. :group 'org-time
  2789. :version "24.1"
  2790. :type '(choice
  2791. (const :tag "Use org-read-date-prefer-future"
  2792. org-read-date-prefer-future)
  2793. (const :tag "Never" nil)
  2794. (const :tag "Always" t)))
  2795. (defcustom org-read-date-force-compatible-dates t
  2796. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2797. Depending on the system Emacs is running on, certain dates cannot
  2798. be represented with the type used internally to represent time.
  2799. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2800. correctly. Some systems allow for earlier dates, some for later,
  2801. some for both. One way to find out it to insert any date into an
  2802. Org buffer, putting the cursor on the year and hitting S-up and
  2803. S-down to test the range.
  2804. When this variable is set to t, the date/time prompt will not let
  2805. you specify dates outside the 1970-2037 range, so it is certain that
  2806. these dates will work in whatever version of Emacs you are
  2807. running, and also that you can move a file from one Emacs implementation
  2808. to another. WHenever Org is forcing the year for you, it will display
  2809. a message and beep.
  2810. When this variable is nil, Org will check if the date is
  2811. representable in the specific Emacs implementation you are using.
  2812. If not, it will force a year, usually the current year, and beep
  2813. to remind you. Currently this setting is not recommended because
  2814. the likelihood that you will open your Org files in an Emacs that
  2815. has limited date range is not negligible.
  2816. A workaround for this problem is to use diary sexp dates for time
  2817. stamps outside of this range."
  2818. :group 'org-time
  2819. :version "24.1"
  2820. :type 'boolean)
  2821. (defcustom org-read-date-display-live t
  2822. "Non-nil means display current interpretation of date prompt live.
  2823. This display will be in an overlay, in the minibuffer."
  2824. :group 'org-time
  2825. :type 'boolean)
  2826. (defcustom org-read-date-popup-calendar t
  2827. "Non-nil means pop up a calendar when prompting for a date.
  2828. In the calendar, the date can be selected with mouse-1. However, the
  2829. minibuffer will also be active, and you can simply enter the date as well.
  2830. When nil, only the minibuffer will be available."
  2831. :group 'org-time
  2832. :type 'boolean)
  2833. (defvaralias 'org-popup-calendar-for-date-prompt
  2834. 'org-read-date-popup-calendar)
  2835. (defcustom org-extend-today-until 0
  2836. "The hour when your day really ends. Must be an integer.
  2837. This has influence for the following applications:
  2838. - When switching the agenda to \"today\". It it is still earlier than
  2839. the time given here, the day recognized as TODAY is actually yesterday.
  2840. - When a date is read from the user and it is still before the time given
  2841. here, the current date and time will be assumed to be yesterday, 23:59.
  2842. Also, timestamps inserted in capture templates follow this rule.
  2843. IMPORTANT: This is a feature whose implementation is and likely will
  2844. remain incomplete. Really, it is only here because past midnight seems to
  2845. be the favorite working time of John Wiegley :-)"
  2846. :group 'org-time
  2847. :type 'integer)
  2848. (defcustom org-use-effective-time nil
  2849. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2850. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2851. \"effective time\" of any timestamps between midnight and 8am will be
  2852. 23:59 of the previous day."
  2853. :group 'org-time
  2854. :version "24.1"
  2855. :type 'boolean)
  2856. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2857. "When non-nil, use the last clock out time for `org-todo'.
  2858. Note that this option has precedence over the combined use of
  2859. `org-use-effective-time' and `org-extend-today-until'."
  2860. :group 'org-time
  2861. :version "24.4"
  2862. :package-version '(Org . "8.0")
  2863. :type 'boolean)
  2864. (defcustom org-edit-timestamp-down-means-later nil
  2865. "Non-nil means S-down will increase the time in a time stamp.
  2866. When nil, S-up will increase."
  2867. :group 'org-time
  2868. :type 'boolean)
  2869. (defcustom org-calendar-follow-timestamp-change t
  2870. "Non-nil means make the calendar window follow timestamp changes.
  2871. When a timestamp is modified and the calendar window is visible, it will be
  2872. moved to the new date."
  2873. :group 'org-time
  2874. :type 'boolean)
  2875. (defgroup org-tags nil
  2876. "Options concerning tags in Org mode."
  2877. :tag "Org Tags"
  2878. :group 'org)
  2879. (defcustom org-tag-alist nil
  2880. "Default tags available in Org files.
  2881. The value of this variable is an alist. Associations either:
  2882. (TAG)
  2883. (TAG . SELECT)
  2884. (SPECIAL)
  2885. where TAG is a tag as a string, SELECT is character, used to
  2886. select that tag through the fast tag selection interface, and
  2887. SPECIAL is one of the following keywords: `:startgroup',
  2888. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2889. `:newline'. These keywords are used to define a hierarchy of
  2890. tags. See manual for details.
  2891. When this variable is nil, Org mode bases tag input on what is
  2892. already in the buffer. The value can be overridden locally by
  2893. using a TAGS keyword, e.g.,
  2894. #+TAGS: tag1 tag2
  2895. See also `org-tag-persistent-alist' to sidestep this behavior."
  2896. :group 'org-tags
  2897. :type '(repeat
  2898. (choice
  2899. (cons :tag "Tag with key"
  2900. (string :tag "Tag name")
  2901. (character :tag "Access char"))
  2902. (list :tag "Tag" (string :tag "Tag name"))
  2903. (const :tag "Start radio group" (:startgroup))
  2904. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2905. (const :tag "Group tags delimiter" (:grouptags))
  2906. (const :tag "End radio group" (:endgroup))
  2907. (const :tag "End tag group, non distinct" (:endgrouptag))
  2908. (const :tag "New line" (:newline)))))
  2909. (defcustom org-tag-persistent-alist nil
  2910. "Tags always available in Org files.
  2911. The value of this variable is an alist. Associations either:
  2912. (TAG)
  2913. (TAG . SELECT)
  2914. (SPECIAL)
  2915. where TAG is a tag as a string, SELECT is a character, used to
  2916. select that tag through the fast tag selection interface, and
  2917. SPECIAL is one of the following keywords: `:startgroup',
  2918. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2919. `:newline'. These keywords are used to define a hierarchy of
  2920. tags. See manual for details.
  2921. Unlike to `org-tag-alist', tags defined in this variable do not
  2922. depend on a local TAGS keyword. Instead, to disable these tags
  2923. on a per-file basis, insert anywhere in the file:
  2924. #+STARTUP: noptag"
  2925. :group 'org-tags
  2926. :type '(repeat
  2927. (choice
  2928. (cons :tag "Tag with key"
  2929. (string :tag "Tag name")
  2930. (character :tag "Access char"))
  2931. (list :tag "Tag" (string :tag "Tag name"))
  2932. (const :tag "Start radio group" (:startgroup))
  2933. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2934. (const :tag "Group tags delimiter" (:grouptags))
  2935. (const :tag "End radio group" (:endgroup))
  2936. (const :tag "End tag group, non distinct" (:endgrouptag))
  2937. (const :tag "New line" (:newline)))))
  2938. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2939. "If non-nil, always offer completion for all tags of all agenda files.
  2940. Instead of customizing this variable directly, you might want to
  2941. set it locally for capture buffers, because there no list of
  2942. tags in that file can be created dynamically (there are none).
  2943. (add-hook \\='org-capture-mode-hook
  2944. (lambda ()
  2945. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2946. :group 'org-tags
  2947. :version "24.1"
  2948. :type 'boolean)
  2949. (defvar org-file-tags nil
  2950. "List of tags that can be inherited by all entries in the file.
  2951. The tags will be inherited if the variable `org-use-tag-inheritance'
  2952. says they should be.
  2953. This variable is populated from #+FILETAGS lines.")
  2954. (defcustom org-use-fast-tag-selection 'auto
  2955. "Non-nil means use fast tag selection scheme.
  2956. This is a special interface to select and deselect tags with single keys.
  2957. When nil, fast selection is never used.
  2958. When the symbol `auto', fast selection is used if and only if selection
  2959. characters for tags have been configured, either through the variable
  2960. `org-tag-alist' or through a #+TAGS line in the buffer.
  2961. When t, fast selection is always used and selection keys are assigned
  2962. automatically if necessary."
  2963. :group 'org-tags
  2964. :type '(choice
  2965. (const :tag "Always" t)
  2966. (const :tag "Never" nil)
  2967. (const :tag "When selection characters are configured" auto)))
  2968. (defcustom org-fast-tag-selection-single-key nil
  2969. "Non-nil means fast tag selection exits after first change.
  2970. When nil, you have to press RET to exit it.
  2971. During fast tag selection, you can toggle this flag with `C-c'.
  2972. This variable can also have the value `expert'. In this case, the window
  2973. displaying the tags menu is not even shown, until you press C-c again."
  2974. :group 'org-tags
  2975. :type '(choice
  2976. (const :tag "No" nil)
  2977. (const :tag "Yes" t)
  2978. (const :tag "Expert" expert)))
  2979. (defvar org-fast-tag-selection-include-todo nil
  2980. "Non-nil means fast tags selection interface will also offer TODO states.
  2981. This is an undocumented feature, you should not rely on it.")
  2982. (defcustom org-tags-column -77
  2983. "The column to which tags should be indented in a headline.
  2984. If this number is positive, it specifies the column. If it is negative,
  2985. it means that the tags should be flushright to that column. For example,
  2986. -80 works well for a normal 80 character screen.
  2987. When 0, place tags directly after headline text, with only one space in
  2988. between."
  2989. :group 'org-tags
  2990. :type 'integer)
  2991. (defcustom org-auto-align-tags t
  2992. "Non-nil keeps tags aligned when modifying headlines.
  2993. Some operations (i.e. demoting) change the length of a headline and
  2994. therefore shift the tags around. With this option turned on, after
  2995. each such operation the tags are again aligned to `org-tags-column'."
  2996. :group 'org-tags
  2997. :type 'boolean)
  2998. (defcustom org-use-tag-inheritance t
  2999. "Non-nil means tags in levels apply also for sublevels.
  3000. When nil, only the tags directly given in a specific line apply there.
  3001. This may also be a list of tags that should be inherited, or a regexp that
  3002. matches tags that should be inherited. Additional control is possible
  3003. with the variable `org-tags-exclude-from-inheritance' which gives an
  3004. explicit list of tags to be excluded from inheritance, even if the value of
  3005. `org-use-tag-inheritance' would select it for inheritance.
  3006. If this option is t, a match early-on in a tree can lead to a large
  3007. number of matches in the subtree when constructing the agenda or creating
  3008. a sparse tree. If you only want to see the first match in a tree during
  3009. a search, check out the variable `org-tags-match-list-sublevels'."
  3010. :group 'org-tags
  3011. :type '(choice
  3012. (const :tag "Not" nil)
  3013. (const :tag "Always" t)
  3014. (repeat :tag "Specific tags" (string :tag "Tag"))
  3015. (regexp :tag "Tags matched by regexp")))
  3016. (defcustom org-tags-exclude-from-inheritance nil
  3017. "List of tags that should never be inherited.
  3018. This is a way to exclude a few tags from inheritance. For way to do
  3019. the opposite, to actively allow inheritance for selected tags,
  3020. see the variable `org-use-tag-inheritance'."
  3021. :group 'org-tags
  3022. :type '(repeat (string :tag "Tag")))
  3023. (defun org-tag-inherit-p (tag)
  3024. "Check if TAG is one that should be inherited."
  3025. (cond
  3026. ((member tag org-tags-exclude-from-inheritance) nil)
  3027. ((eq org-use-tag-inheritance t) t)
  3028. ((not org-use-tag-inheritance) nil)
  3029. ((stringp org-use-tag-inheritance)
  3030. (string-match org-use-tag-inheritance tag))
  3031. ((listp org-use-tag-inheritance)
  3032. (member tag org-use-tag-inheritance))
  3033. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3034. (defcustom org-tags-match-list-sublevels t
  3035. "Non-nil means list also sublevels of headlines matching a search.
  3036. This variable applies to tags/property searches, and also to stuck
  3037. projects because this search is based on a tags match as well.
  3038. When set to the symbol `indented', sublevels are indented with
  3039. leading dots.
  3040. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3041. the sublevels of a headline matching a tag search often also match
  3042. the same search. Listing all of them can create very long lists.
  3043. Setting this variable to nil causes subtrees of a match to be skipped.
  3044. This variable is semi-obsolete and probably should always be true. It
  3045. is better to limit inheritance to certain tags using the variables
  3046. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3047. :group 'org-tags
  3048. :type '(choice
  3049. (const :tag "No, don't list them" nil)
  3050. (const :tag "Yes, do list them" t)
  3051. (const :tag "List them, indented with leading dots" indented)))
  3052. (defcustom org-tags-sort-function nil
  3053. "When set, tags are sorted using this function as a comparator."
  3054. :group 'org-tags
  3055. :type '(choice
  3056. (const :tag "No sorting" nil)
  3057. (const :tag "Alphabetical" string<)
  3058. (const :tag "Reverse alphabetical" string>)
  3059. (function :tag "Custom function" nil)))
  3060. (defvar org-tags-history nil
  3061. "History of minibuffer reads for tags.")
  3062. (defvar org-last-tags-completion-table nil
  3063. "The last used completion table for tags.")
  3064. (defvar org-after-tags-change-hook nil
  3065. "Hook that is run after the tags in a line have changed.")
  3066. (defgroup org-properties nil
  3067. "Options concerning properties in Org mode."
  3068. :tag "Org Properties"
  3069. :group 'org)
  3070. (defcustom org-property-format "%-10s %s"
  3071. "How property key/value pairs should be formatted by `indent-line'.
  3072. When `indent-line' hits a property definition, it will format the line
  3073. according to this format, mainly to make sure that the values are
  3074. lined-up with respect to each other."
  3075. :group 'org-properties
  3076. :type 'string)
  3077. (defcustom org-properties-postprocess-alist nil
  3078. "Alist of properties and functions to adjust inserted values.
  3079. Elements of this alist must be of the form
  3080. ([string] [function])
  3081. where [string] must be a property name and [function] must be a
  3082. lambda expression: this lambda expression must take one argument,
  3083. the value to adjust, and return the new value as a string.
  3084. For example, this element will allow the property \"Remaining\"
  3085. to be updated wrt the relation between the \"Effort\" property
  3086. and the clock summary:
  3087. ((\"Remaining\" (lambda(value)
  3088. (let ((clocksum (org-clock-sum-current-item))
  3089. (effort (org-duration-to-minutes
  3090. (org-entry-get (point) \"Effort\"))))
  3091. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3092. :group 'org-properties
  3093. :version "24.1"
  3094. :type '(alist :key-type (string :tag "Property")
  3095. :value-type (function :tag "Function")))
  3096. (defcustom org-use-property-inheritance nil
  3097. "Non-nil means properties apply also for sublevels.
  3098. This setting is chiefly used during property searches. Turning it on can
  3099. cause significant overhead when doing a search, which is why it is not
  3100. on by default.
  3101. When nil, only the properties directly given in the current entry count.
  3102. When t, every property is inherited. The value may also be a list of
  3103. properties that should have inheritance, or a regular expression matching
  3104. properties that should be inherited.
  3105. However, note that some special properties use inheritance under special
  3106. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3107. and the properties ending in \"_ALL\" when they are used as descriptor
  3108. for valid values of a property.
  3109. Note for programmers:
  3110. When querying an entry with `org-entry-get', you can control if inheritance
  3111. should be used. By default, `org-entry-get' looks only at the local
  3112. properties. You can request inheritance by setting the inherit argument
  3113. to t (to force inheritance) or to `selective' (to respect the setting
  3114. in this variable)."
  3115. :group 'org-properties
  3116. :type '(choice
  3117. (const :tag "Not" nil)
  3118. (const :tag "Always" t)
  3119. (repeat :tag "Specific properties" (string :tag "Property"))
  3120. (regexp :tag "Properties matched by regexp")))
  3121. (defun org-property-inherit-p (property)
  3122. "Return a non-nil value if PROPERTY should be inherited."
  3123. (cond
  3124. ((eq org-use-property-inheritance t) t)
  3125. ((not org-use-property-inheritance) nil)
  3126. ((stringp org-use-property-inheritance)
  3127. (string-match org-use-property-inheritance property))
  3128. ((listp org-use-property-inheritance)
  3129. (member-ignore-case property org-use-property-inheritance))
  3130. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3131. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3132. "The default column format, if no other format has been defined.
  3133. This variable can be set on the per-file basis by inserting a line
  3134. #+COLUMNS: %25ITEM ....."
  3135. :group 'org-properties
  3136. :type 'string)
  3137. (defcustom org-columns-ellipses ".."
  3138. "The ellipses to be used when a field in column view is truncated.
  3139. When this is the empty string, as many characters as possible are shown,
  3140. but then there will be no visual indication that the field has been truncated.
  3141. When this is a string of length N, the last N characters of a truncated
  3142. field are replaced by this string. If the column is narrower than the
  3143. ellipses string, only part of the ellipses string will be shown."
  3144. :group 'org-properties
  3145. :type 'string)
  3146. (defconst org-global-properties-fixed
  3147. '(("VISIBILITY_ALL" . "folded children content all")
  3148. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3149. "List of property/value pairs that can be inherited by any entry.
  3150. These are fixed values, for the preset properties. The user variable
  3151. that can be used to add to this list is `org-global-properties'.
  3152. The entries in this list are cons cells where the car is a property
  3153. name and cdr is a string with the value. If the value represents
  3154. multiple items like an \"_ALL\" property, separate the items by
  3155. spaces.")
  3156. (defcustom org-global-properties nil
  3157. "List of property/value pairs that can be inherited by any entry.
  3158. This list will be combined with the constant `org-global-properties-fixed'.
  3159. The entries in this list are cons cells where the car is a property
  3160. name and cdr is a string with the value.
  3161. You can set buffer-local values for the same purpose in the variable
  3162. `org-file-properties' this by adding lines like
  3163. #+PROPERTY: NAME VALUE"
  3164. :group 'org-properties
  3165. :type '(repeat
  3166. (cons (string :tag "Property")
  3167. (string :tag "Value"))))
  3168. (defvar-local org-file-properties nil
  3169. "List of property/value pairs that can be inherited by any entry.
  3170. Valid for the current buffer.
  3171. This variable is populated from #+PROPERTY lines.")
  3172. (defgroup org-agenda nil
  3173. "Options concerning agenda views in Org mode."
  3174. :tag "Org Agenda"
  3175. :group 'org)
  3176. (defvar-local org-category nil
  3177. "Variable used by Org files to set a category for agenda display.
  3178. Such files should use a file variable to set it, for example
  3179. # -*- mode: org; org-category: \"ELisp\"
  3180. or contain a special line
  3181. #+CATEGORY: ELisp
  3182. If the file does not specify a category, then file's base name
  3183. is used instead.")
  3184. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3185. (defcustom org-agenda-files nil
  3186. "The files to be used for agenda display.
  3187. If an entry is a directory, all files in that directory that are matched
  3188. by `org-agenda-file-regexp' will be part of the file list.
  3189. If the value of the variable is not a list but a single file name, then
  3190. the list of agenda files is actually stored and maintained in that file,
  3191. one agenda file per line. In this file paths can be given relative to
  3192. `org-directory'. Tilde expansion and environment variable substitution
  3193. are also made.
  3194. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3195. and removed with `\\[org-remove-file]'."
  3196. :group 'org-agenda
  3197. :type '(choice
  3198. (repeat :tag "List of files and directories" file)
  3199. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3200. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3201. "Regular expression to match files for `org-agenda-files'.
  3202. If any element in the list in that variable contains a directory instead
  3203. of a normal file, all files in that directory that are matched by this
  3204. regular expression will be included."
  3205. :group 'org-agenda
  3206. :type 'regexp)
  3207. (defcustom org-agenda-text-search-extra-files nil
  3208. "List of extra files to be searched by text search commands.
  3209. These files will be searched in addition to the agenda files by the
  3210. commands `org-search-view' (`\\[org-agenda] s') \
  3211. and `org-occur-in-agenda-files'.
  3212. Note that these files will only be searched for text search commands,
  3213. not for the other agenda views like todo lists, tag searches or the weekly
  3214. agenda. This variable is intended to list notes and possibly archive files
  3215. that should also be searched by these two commands.
  3216. In fact, if the first element in the list is the symbol `agenda-archives',
  3217. then all archive files of all agenda files will be added to the search
  3218. scope."
  3219. :group 'org-agenda
  3220. :type '(set :greedy t
  3221. (const :tag "Agenda Archives" agenda-archives)
  3222. (repeat :inline t (file))))
  3223. (defvaralias 'org-agenda-multi-occur-extra-files
  3224. 'org-agenda-text-search-extra-files)
  3225. (defcustom org-agenda-skip-unavailable-files nil
  3226. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3227. A nil value means to remove them, after a query, from the list."
  3228. :group 'org-agenda
  3229. :type 'boolean)
  3230. (defcustom org-agenda-diary-file 'diary-file
  3231. "File to which to add new entries with the `i' key in agenda and calendar.
  3232. When this is the symbol `diary-file', the functionality in the Emacs
  3233. calendar will be used to add entries to the `diary-file'. But when this
  3234. points to a file, `org-agenda-diary-entry' will be used instead."
  3235. :group 'org-agenda
  3236. :type '(choice
  3237. (const :tag "The standard Emacs diary file" diary-file)
  3238. (file :tag "Special Org file diary entries")))
  3239. (defgroup org-latex nil
  3240. "Options for embedding LaTeX code into Org mode."
  3241. :tag "Org LaTeX"
  3242. :group 'org)
  3243. (defcustom org-format-latex-options
  3244. '(:foreground default :background default :scale 1.0
  3245. :html-foreground "Black" :html-background "Transparent"
  3246. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3247. "Options for creating images from LaTeX fragments.
  3248. This is a property list with the following properties:
  3249. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3250. `default' means use the foreground of the default face.
  3251. `auto' means use the foreground from the text face.
  3252. :background the background color, or \"Transparent\".
  3253. `default' means use the background of the default face.
  3254. `auto' means use the background from the text face.
  3255. :scale a scaling factor for the size of the images, to get more pixels
  3256. :html-foreground, :html-background, :html-scale
  3257. the same numbers for HTML export.
  3258. :matchers a list indicating which matchers should be used to
  3259. find LaTeX fragments. Valid members of this list are:
  3260. \"begin\" find environments
  3261. \"$1\" find single characters surrounded by $.$
  3262. \"$\" find math expressions surrounded by $...$
  3263. \"$$\" find math expressions surrounded by $$....$$
  3264. \"\\(\" find math expressions surrounded by \\(...\\)
  3265. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3266. :group 'org-latex
  3267. :type 'plist)
  3268. (defcustom org-format-latex-signal-error t
  3269. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3270. When nil, just push out a message."
  3271. :group 'org-latex
  3272. :version "24.1"
  3273. :type 'boolean)
  3274. (defcustom org-latex-to-mathml-jar-file nil
  3275. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3276. Use this to specify additional executable file say a jar file.
  3277. When using MathToWeb as the converter, specify the full-path to
  3278. your mathtoweb.jar file."
  3279. :group 'org-latex
  3280. :version "24.1"
  3281. :type '(choice
  3282. (const :tag "None" nil)
  3283. (file :tag "JAR file" :must-match t)))
  3284. (defcustom org-latex-to-mathml-convert-command nil
  3285. "Command to convert LaTeX fragments to MathML.
  3286. Replace format-specifiers in the command as noted below and use
  3287. `shell-command' to convert LaTeX to MathML.
  3288. %j: Executable file in fully expanded form as specified by
  3289. `org-latex-to-mathml-jar-file'.
  3290. %I: Input LaTeX file in fully expanded form.
  3291. %i: The latex fragment to be converted.
  3292. %o: Output MathML file.
  3293. This command is used by `org-create-math-formula'.
  3294. When using MathToWeb as the converter, set this option to
  3295. \"java -jar %j -unicode -force -df %o %I\".
  3296. When using LaTeXML set this option to
  3297. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3298. :group 'org-latex
  3299. :version "24.1"
  3300. :type '(choice
  3301. (const :tag "None" nil)
  3302. (string :tag "\nShell command")))
  3303. (defcustom org-preview-latex-default-process 'dvipng
  3304. "The default process to convert LaTeX fragments to image files.
  3305. All available processes and theirs documents can be found in
  3306. `org-preview-latex-process-alist', which see."
  3307. :group 'org-latex
  3308. :version "26.1"
  3309. :package-version '(Org . "9.0")
  3310. :type 'symbol)
  3311. (defcustom org-preview-latex-process-alist
  3312. '((dvipng
  3313. :programs ("latex" "dvipng")
  3314. :description "dvi > png"
  3315. :message "you need to install the programs: latex and dvipng."
  3316. :image-input-type "dvi"
  3317. :image-output-type "png"
  3318. :image-size-adjust (1.0 . 1.0)
  3319. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3320. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3321. (dvisvgm
  3322. :programs ("latex" "dvisvgm")
  3323. :description "dvi > svg"
  3324. :message "you need to install the programs: latex and dvisvgm."
  3325. :use-xcolor t
  3326. :image-input-type "dvi"
  3327. :image-output-type "svg"
  3328. :image-size-adjust (1.7 . 1.5)
  3329. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3330. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3331. (imagemagick
  3332. :programs ("latex" "convert")
  3333. :description "pdf > png"
  3334. :message "you need to install the programs: latex and imagemagick."
  3335. :use-xcolor t
  3336. :image-input-type "pdf"
  3337. :image-output-type "png"
  3338. :image-size-adjust (1.0 . 1.0)
  3339. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3340. :image-converter
  3341. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3342. "Definitions of external processes for LaTeX previewing.
  3343. Org mode can use some external commands to generate TeX snippet's images for
  3344. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3345. `org-create-formula-image' how to call them.
  3346. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3347. PROPERTIES accepts the following attributes:
  3348. :programs list of strings, required programs.
  3349. :description string, describe the process.
  3350. :message string, message it when required programs cannot be found.
  3351. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3352. :image-output-type string, output file type of image converter (e.g., \"png\").
  3353. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3354. deal with background and foreground color of image.
  3355. Otherwise, dvipng style background and foreground color
  3356. format are generated. You may then refer to them in
  3357. command options with \"%F\" and \"%B\".
  3358. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3359. image size showed in buffer and the cdr element is for
  3360. HTML file. This option is only useful for process
  3361. developers, users should use variable
  3362. `org-format-latex-options' instead.
  3363. :post-clean list of strings, files matched are to be cleaned up once
  3364. the image is generated. When nil, the files with \".dvi\",
  3365. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3366. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3367. be cleaned up.
  3368. :latex-header list of strings, the LaTeX header of the snippet file.
  3369. When nil, the fallback value is used instead, which is
  3370. controlled by `org-format-latex-header',
  3371. `org-latex-default-packages-alist' and
  3372. `org-latex-packages-alist', which see.
  3373. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3374. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3375. replaced with values defined below.
  3376. :image-converter list of image converter commands strings. Each of them is
  3377. given to the shell and supports any of the following
  3378. place-holders defined below.
  3379. Place-holders used by `:image-converter' and `:latex-compiler':
  3380. %f input file name
  3381. %b base name of input file
  3382. %o base directory of input file
  3383. %O absolute output file name
  3384. Place-holders only used by `:image-converter':
  3385. %F foreground of image
  3386. %B background of image
  3387. %D dpi, which is used to adjust image size by some processing commands.
  3388. %S the image size scale ratio, which is used to adjust image size by some
  3389. processing commands."
  3390. :group 'org-latex
  3391. :version "26.1"
  3392. :package-version '(Org . "9.0")
  3393. :type '(alist :tag "LaTeX to image backends"
  3394. :value-type (plist)))
  3395. (defcustom org-preview-latex-image-directory "ltximg/"
  3396. "Path to store latex preview images.
  3397. A relative path here creates many directories relative to the
  3398. processed Org files paths. An absolute path puts all preview
  3399. images at the same place."
  3400. :group 'org-latex
  3401. :version "26.1"
  3402. :package-version '(Org . "9.0")
  3403. :type 'string)
  3404. (defun org-format-latex-mathml-available-p ()
  3405. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3406. (save-match-data
  3407. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3408. org-latex-to-mathml-convert-command)
  3409. (let ((executable (car (split-string
  3410. org-latex-to-mathml-convert-command))))
  3411. (when (executable-find executable)
  3412. (if (string-match
  3413. "%j" org-latex-to-mathml-convert-command)
  3414. (file-readable-p org-latex-to-mathml-jar-file)
  3415. t))))))
  3416. (defcustom org-format-latex-header "\\documentclass{article}
  3417. \\usepackage[usenames]{color}
  3418. \[PACKAGES]
  3419. \[DEFAULT-PACKAGES]
  3420. \\pagestyle{empty} % do not remove
  3421. % The settings below are copied from fullpage.sty
  3422. \\setlength{\\textwidth}{\\paperwidth}
  3423. \\addtolength{\\textwidth}{-3cm}
  3424. \\setlength{\\oddsidemargin}{1.5cm}
  3425. \\addtolength{\\oddsidemargin}{-2.54cm}
  3426. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3427. \\setlength{\\textheight}{\\paperheight}
  3428. \\addtolength{\\textheight}{-\\headheight}
  3429. \\addtolength{\\textheight}{-\\headsep}
  3430. \\addtolength{\\textheight}{-\\footskip}
  3431. \\addtolength{\\textheight}{-3cm}
  3432. \\setlength{\\topmargin}{1.5cm}
  3433. \\addtolength{\\topmargin}{-2.54cm}"
  3434. "The document header used for processing LaTeX fragments.
  3435. It is imperative that this header make sure that no page number
  3436. appears on the page. The package defined in the variables
  3437. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3438. will either replace the placeholder \"[PACKAGES]\" in this
  3439. header, or they will be appended."
  3440. :group 'org-latex
  3441. :type 'string)
  3442. (defun org-set-packages-alist (var val)
  3443. "Set the packages alist and make sure it has 3 elements per entry."
  3444. (set var (mapcar (lambda (x)
  3445. (if (and (consp x) (= (length x) 2))
  3446. (list (car x) (nth 1 x) t)
  3447. x))
  3448. val)))
  3449. (defun org-get-packages-alist (var)
  3450. "Get the packages alist and make sure it has 3 elements per entry."
  3451. (mapcar (lambda (x)
  3452. (if (and (consp x) (= (length x) 2))
  3453. (list (car x) (nth 1 x) t)
  3454. x))
  3455. (default-value var)))
  3456. (defcustom org-latex-default-packages-alist
  3457. '(("AUTO" "inputenc" t ("pdflatex"))
  3458. ("T1" "fontenc" t ("pdflatex"))
  3459. ("" "graphicx" t)
  3460. ("" "grffile" t)
  3461. ("" "longtable" nil)
  3462. ("" "wrapfig" nil)
  3463. ("" "rotating" nil)
  3464. ("normalem" "ulem" t)
  3465. ("" "amsmath" t)
  3466. ("" "textcomp" t)
  3467. ("" "amssymb" t)
  3468. ("" "capt-of" nil)
  3469. ("" "hyperref" nil))
  3470. "Alist of default packages to be inserted in the header.
  3471. Change this only if one of the packages here causes an
  3472. incompatibility with another package you are using.
  3473. The packages in this list are needed by one part or another of
  3474. Org mode to function properly:
  3475. - inputenc, fontenc: for basic font and character selection
  3476. - graphicx: for including images
  3477. - grffile: allow periods and spaces in graphics file names
  3478. - longtable: For multipage tables
  3479. - wrapfig: for figure placement
  3480. - rotating: for sideways figures and tables
  3481. - ulem: for underline and strike-through
  3482. - amsmath: for subscript and superscript and math environments
  3483. - textcomp, amssymb: for various symbols used
  3484. for interpreting the entities in `org-entities'. You can skip
  3485. some of these packages if you don't use any of their symbols.
  3486. - capt-of: for captions outside of floats
  3487. - hyperref: for cross references
  3488. Therefore you should not modify this variable unless you know
  3489. what you are doing. The one reason to change it anyway is that
  3490. you might be loading some other package that conflicts with one
  3491. of the default packages. Each element is either a cell or
  3492. a string.
  3493. A cell is of the format
  3494. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3495. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3496. when compiling LaTeX snippets into images for inclusion into
  3497. non-LaTeX output. COMPILERS is a list of compilers that should
  3498. include the package, see `org-latex-compiler'. If the document
  3499. compiler is not in the list, and the list is non-nil, the package
  3500. will not be inserted in the final document.
  3501. A string will be inserted as-is in the header of the document."
  3502. :group 'org-latex
  3503. :group 'org-export-latex
  3504. :set 'org-set-packages-alist
  3505. :get 'org-get-packages-alist
  3506. :version "26.1"
  3507. :package-version '(Org . "8.3")
  3508. :type '(repeat
  3509. (choice
  3510. (list :tag "options/package pair"
  3511. (string :tag "options")
  3512. (string :tag "package")
  3513. (boolean :tag "Snippet")
  3514. (choice
  3515. (const :tag "For all compilers" nil)
  3516. (repeat :tag "Allowed compiler" string)))
  3517. (string :tag "A line of LaTeX"))))
  3518. (defcustom org-latex-packages-alist nil
  3519. "Alist of packages to be inserted in every LaTeX header.
  3520. These will be inserted after `org-latex-default-packages-alist'.
  3521. Each element is either a cell or a string.
  3522. A cell is of the format:
  3523. (\"options\" \"package\" SNIPPET-FLAG)
  3524. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3525. needed when turning LaTeX snippets into images for inclusion into
  3526. non-LaTeX output.
  3527. A string will be inserted as-is in the header of the document.
  3528. Make sure that you only list packages here which:
  3529. - you want in every file;
  3530. - do not conflict with the setup in `org-format-latex-header';
  3531. - do not conflict with the default packages in
  3532. `org-latex-default-packages-alist'."
  3533. :group 'org-latex
  3534. :group 'org-export-latex
  3535. :set 'org-set-packages-alist
  3536. :get 'org-get-packages-alist
  3537. :type '(repeat
  3538. (choice
  3539. (list :tag "options/package pair"
  3540. (string :tag "options")
  3541. (string :tag "package")
  3542. (boolean :tag "Snippet"))
  3543. (string :tag "A line of LaTeX"))))
  3544. (defgroup org-appearance nil
  3545. "Settings for Org mode appearance."
  3546. :tag "Org Appearance"
  3547. :group 'org)
  3548. (defcustom org-level-color-stars-only nil
  3549. "Non-nil means fontify only the stars in each headline.
  3550. When nil, the entire headline is fontified.
  3551. Changing it requires restart of `font-lock-mode' to become effective
  3552. also in regions already fontified."
  3553. :group 'org-appearance
  3554. :type 'boolean)
  3555. (defcustom org-hide-leading-stars nil
  3556. "Non-nil means hide the first N-1 stars in a headline.
  3557. This works by using the face `org-hide' for these stars. This
  3558. face is white for a light background, and black for a dark
  3559. background. You may have to customize the face `org-hide' to
  3560. make this work.
  3561. Changing it requires restart of `font-lock-mode' to become effective
  3562. also in regions already fontified.
  3563. You may also set this on a per-file basis by adding one of the following
  3564. lines to the buffer:
  3565. #+STARTUP: hidestars
  3566. #+STARTUP: showstars"
  3567. :group 'org-appearance
  3568. :type 'boolean)
  3569. (defcustom org-hidden-keywords nil
  3570. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3571. For example, a value \\='(title) for this list makes the document's title
  3572. appear in the buffer without the initial \"#+TITLE:\" part."
  3573. :group 'org-appearance
  3574. :version "24.1"
  3575. :type '(set (const :tag "#+AUTHOR" author)
  3576. (const :tag "#+DATE" date)
  3577. (const :tag "#+EMAIL" email)
  3578. (const :tag "#+TITLE" title)))
  3579. (defcustom org-custom-properties nil
  3580. "List of properties (as strings) with a special meaning.
  3581. The default use of these custom properties is to let the user
  3582. hide them with `org-toggle-custom-properties-visibility'."
  3583. :group 'org-properties
  3584. :group 'org-appearance
  3585. :version "24.3"
  3586. :type '(repeat (string :tag "Property Name")))
  3587. (defcustom org-fontify-done-headline nil
  3588. "Non-nil means change the face of a headline if it is marked DONE.
  3589. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3590. When this is non-nil, the headline after the keyword is set to the
  3591. `org-headline-done' as an additional indication."
  3592. :group 'org-appearance
  3593. :type 'boolean)
  3594. (defcustom org-fontify-emphasized-text t
  3595. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3596. Changing this variable requires a restart of Emacs to take effect."
  3597. :group 'org-appearance
  3598. :type 'boolean)
  3599. (defcustom org-fontify-whole-heading-line nil
  3600. "Non-nil means fontify the whole line for headings.
  3601. This is useful when setting a background color for the
  3602. org-level-* faces."
  3603. :group 'org-appearance
  3604. :type 'boolean)
  3605. (defcustom org-highlight-latex-and-related nil
  3606. "Non-nil means highlight LaTeX related syntax in the buffer.
  3607. When non nil, the value should be a list containing any of the
  3608. following symbols:
  3609. `latex' Highlight LaTeX snippets and environments.
  3610. `script' Highlight subscript and superscript.
  3611. `entities' Highlight entities."
  3612. :group 'org-appearance
  3613. :version "24.4"
  3614. :package-version '(Org . "8.0")
  3615. :type '(choice
  3616. (const :tag "No highlighting" nil)
  3617. (set :greedy t :tag "Highlight"
  3618. (const :tag "LaTeX snippets and environments" latex)
  3619. (const :tag "Subscript and superscript" script)
  3620. (const :tag "Entities" entities))))
  3621. (defcustom org-hide-emphasis-markers nil
  3622. "Non-nil mean font-lock should hide the emphasis marker characters."
  3623. :group 'org-appearance
  3624. :type 'boolean)
  3625. (defcustom org-hide-macro-markers nil
  3626. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3627. :group 'org-appearance
  3628. :type 'boolean)
  3629. (defcustom org-pretty-entities nil
  3630. "Non-nil means show entities as UTF8 characters.
  3631. When nil, the \\name form remains in the buffer."
  3632. :group 'org-appearance
  3633. :version "24.1"
  3634. :type 'boolean)
  3635. (defcustom org-pretty-entities-include-sub-superscripts t
  3636. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3637. :group 'org-appearance
  3638. :version "24.1"
  3639. :type 'boolean)
  3640. (defvar org-emph-re nil
  3641. "Regular expression for matching emphasis.
  3642. After a match, the match groups contain these elements:
  3643. 0 The match of the full regular expression, including the characters
  3644. before and after the proper match
  3645. 1 The character before the proper match, or empty at beginning of line
  3646. 2 The proper match, including the leading and trailing markers
  3647. 3 The leading marker like * or /, indicating the type of highlighting
  3648. 4 The text between the emphasis markers, not including the markers
  3649. 5 The character after the match, empty at the end of a line")
  3650. (defvar org-verbatim-re nil
  3651. "Regular expression for matching verbatim text.")
  3652. (defvar org-emphasis-regexp-components) ; defined just below
  3653. (defvar org-emphasis-alist) ; defined just below
  3654. (defun org-set-emph-re (var val)
  3655. "Set variable and compute the emphasis regular expression."
  3656. (set var val)
  3657. (when (and (boundp 'org-emphasis-alist)
  3658. (boundp 'org-emphasis-regexp-components)
  3659. org-emphasis-alist org-emphasis-regexp-components)
  3660. (pcase-let*
  3661. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3662. (body (if (<= nl 0) body
  3663. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3664. (template
  3665. (format (concat "\\([%s]\\|^\\)" ;before markers
  3666. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3667. "\\([%s]\\|$\\)") ;after markers
  3668. pre border border body border post)))
  3669. (setq org-emph-re (format template "*/_+"))
  3670. (setq org-verbatim-re (format template "=~")))))
  3671. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3672. ;; set this option proved cumbersome. See this message/thread:
  3673. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3674. (defvar org-emphasis-regexp-components
  3675. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3676. "Components used to build the regular expression for emphasis.
  3677. This is a list with five entries. Terminology: In an emphasis string
  3678. like \" *strong word* \", we call the initial space PREMATCH, the final
  3679. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3680. and \"trong wor\" is the body. The different components in this variable
  3681. specify what is allowed/forbidden in each part:
  3682. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3683. post Chars allowed as postmatch. End of line will be allowed too.
  3684. border The chars *forbidden* as border characters.
  3685. body-regexp A regexp like \".\" to match a body character. Don't use
  3686. non-shy groups here, and don't allow newline here.
  3687. newline The maximum number of newlines allowed in an emphasis exp.
  3688. You need to reload Org or to restart Emacs after setting this.")
  3689. (defcustom org-emphasis-alist
  3690. '(("*" bold)
  3691. ("/" italic)
  3692. ("_" underline)
  3693. ("=" org-verbatim verbatim)
  3694. ("~" org-code verbatim)
  3695. ("+" (:strike-through t)))
  3696. "Alist of characters and faces to emphasize text.
  3697. Text starting and ending with a special character will be emphasized,
  3698. for example *bold*, _underlined_ and /italic/. This variable sets the
  3699. marker characters and the face to be used by font-lock for highlighting
  3700. in Org buffers.
  3701. You need to reload Org or to restart Emacs after customizing this."
  3702. :group 'org-appearance
  3703. :set 'org-set-emph-re
  3704. :version "24.4"
  3705. :package-version '(Org . "8.0")
  3706. :type '(repeat
  3707. (list
  3708. (string :tag "Marker character")
  3709. (choice
  3710. (face :tag "Font-lock-face")
  3711. (plist :tag "Face property list"))
  3712. (option (const verbatim)))))
  3713. (defvar org-protecting-blocks '("src" "example" "export")
  3714. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3715. This is needed for font-lock setup.")
  3716. ;;; Functions and variables from their packages
  3717. ;; Declared here to avoid compiler warnings
  3718. (defvar mark-active)
  3719. ;; Various packages
  3720. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3721. (declare-function calendar-forward-day "cal-move" (arg))
  3722. (declare-function calendar-goto-date "cal-move" (date))
  3723. (declare-function calendar-goto-today "cal-move" ())
  3724. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3725. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3726. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3727. (declare-function cdlatex-tab "ext:cdlatex" ())
  3728. (declare-function dired-get-filename
  3729. "dired"
  3730. (&optional localp no-error-if-not-filep))
  3731. (declare-function iswitchb-read-buffer
  3732. "iswitchb"
  3733. (prompt &optional
  3734. default require-match _predicate start matches-set))
  3735. (declare-function org-agenda-change-all-lines
  3736. "org-agenda"
  3737. (newhead hdmarker &optional fixface just-this))
  3738. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3739. "org-agenda"
  3740. (&optional end))
  3741. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3742. (declare-function org-agenda-format-item
  3743. "org-agenda"
  3744. (extra txt &optional level category tags dotime
  3745. remove-re habitp))
  3746. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3747. (declare-function org-agenda-save-markers-for-cut-and-paste
  3748. "org-agenda"
  3749. (beg end))
  3750. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3751. (declare-function org-agenda-skip "org-agenda" ())
  3752. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3753. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3754. (declare-function org-indent-mode "org-indent" (&optional arg))
  3755. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3756. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3757. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3758. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3759. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3760. (declare-function parse-time-string "parse-time" (string))
  3761. (defvar align-mode-rules-list)
  3762. (defvar calc-embedded-close-formula)
  3763. (defvar calc-embedded-open-formula)
  3764. (defvar calc-embedded-open-mode)
  3765. (defvar font-lock-unfontify-region-function)
  3766. (defvar iswitchb-temp-buflist)
  3767. (defvar org-agenda-tags-todo-honor-ignore-options)
  3768. (defvar remember-data-file)
  3769. (defvar texmathp-why)
  3770. ;;;###autoload
  3771. (defun turn-on-orgtbl ()
  3772. "Unconditionally turn on `orgtbl-mode'."
  3773. (require 'org-table)
  3774. (orgtbl-mode 1))
  3775. (defun org-at-table-p (&optional table-type)
  3776. "Non-nil if the cursor is inside an Org table.
  3777. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3778. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3779. (or (not (derived-mode-p 'org-mode))
  3780. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3781. (and e (or table-type
  3782. (eq 'org (org-element-property :type e))))))))
  3783. (defun org-at-table.el-p ()
  3784. "Non-nil when point is at a table.el table."
  3785. (and (org-match-line "[ \t]*[|+]")
  3786. (let ((element (org-element-at-point)))
  3787. (and (eq (org-element-type element) 'table)
  3788. (eq (org-element-property :type element) 'table.el)))))
  3789. (defun org-at-table-hline-p ()
  3790. "Non-nil when point is inside a hline in a table.
  3791. Assume point is already in a table."
  3792. (org-match-line org-table-hline-regexp))
  3793. (defun org-table-map-tables (function &optional quietly)
  3794. "Apply FUNCTION to the start of all tables in the buffer."
  3795. (org-with-wide-buffer
  3796. (goto-char (point-min))
  3797. (while (re-search-forward org-table-any-line-regexp nil t)
  3798. (unless quietly
  3799. (message "Mapping tables: %d%%"
  3800. (floor (* 100.0 (point)) (buffer-size))))
  3801. (beginning-of-line 1)
  3802. (when (and (looking-at org-table-line-regexp)
  3803. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3804. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3805. (save-excursion (funcall function))
  3806. (or (looking-at org-table-line-regexp)
  3807. (forward-char 1)))
  3808. (re-search-forward org-table-any-border-regexp nil 1)))
  3809. (unless quietly (message "Mapping tables: done")))
  3810. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3811. (declare-function org-clock-update-mode-line "org-clock" ())
  3812. (declare-function org-resolve-clocks "org-clock"
  3813. (&optional also-non-dangling-p prompt last-valid))
  3814. (defun org-at-TBLFM-p (&optional pos)
  3815. "Non-nil when point (or POS) is in #+TBLFM line."
  3816. (save-excursion
  3817. (goto-char (or pos (point)))
  3818. (beginning-of-line)
  3819. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3820. (eq (org-element-type (org-element-at-point)) 'table))))
  3821. (defvar org-clock-start-time)
  3822. (defvar org-clock-marker (make-marker)
  3823. "Marker recording the last clock-in.")
  3824. (defvar org-clock-hd-marker (make-marker)
  3825. "Marker recording the last clock-in, but the headline position.")
  3826. (defvar org-clock-heading ""
  3827. "The heading of the current clock entry.")
  3828. (defun org-clock-is-active ()
  3829. "Return the buffer where the clock is currently running.
  3830. Return nil if no clock is running."
  3831. (marker-buffer org-clock-marker))
  3832. (defun org-check-running-clock ()
  3833. "Check if the current buffer contains the running clock.
  3834. If yes, offer to stop it and to save the buffer with the changes."
  3835. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3836. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3837. (buffer-name))))
  3838. (org-clock-out)
  3839. (when (y-or-n-p "Save changed buffer?")
  3840. (save-buffer))))
  3841. (defun org-clocktable-try-shift (dir n)
  3842. "Check if this line starts a clock table, if yes, shift the time block."
  3843. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3844. (org-clocktable-shift dir n)))
  3845. ;;;###autoload
  3846. (defun org-clock-persistence-insinuate ()
  3847. "Set up hooks for clock persistence."
  3848. (require 'org-clock)
  3849. (add-hook 'org-mode-hook 'org-clock-load)
  3850. (add-hook 'kill-emacs-hook 'org-clock-save))
  3851. (defgroup org-archive nil
  3852. "Options concerning archiving in Org mode."
  3853. :tag "Org Archive"
  3854. :group 'org-structure)
  3855. (defcustom org-archive-location "%s_archive::"
  3856. "The location where subtrees should be archived.
  3857. The value of this variable is a string, consisting of two parts,
  3858. separated by a double-colon. The first part is a filename and
  3859. the second part is a headline.
  3860. When the filename is omitted, archiving happens in the same file.
  3861. %s in the filename will be replaced by the current file
  3862. name (without the directory part). Archiving to a different file
  3863. is useful to keep archived entries from contributing to the
  3864. Org Agenda.
  3865. The archived entries will be filed as subtrees of the specified
  3866. headline. When the headline is omitted, the subtrees are simply
  3867. filed away at the end of the file, as top-level entries. Also in
  3868. the heading you can use %s to represent the file name, this can be
  3869. useful when using the same archive for a number of different files.
  3870. Here are a few examples:
  3871. \"%s_archive::\"
  3872. If the current file is Projects.org, archive in file
  3873. Projects.org_archive, as top-level trees. This is the default.
  3874. \"::* Archived Tasks\"
  3875. Archive in the current file, under the top-level headline
  3876. \"* Archived Tasks\".
  3877. \"~/org/archive.org::\"
  3878. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3879. \"~/org/archive.org::* From %s\"
  3880. Archive in file ~/org/archive.org (absolute path), under headlines
  3881. \"From FILENAME\" where file name is the current file name.
  3882. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3883. The \"datetree/\" string is special, signifying to archive
  3884. items to the datetree. Items are placed in either the CLOSED
  3885. date of the item, or the current date if there is no CLOSED date.
  3886. The heading will be a subentry to the current date. There doesn't
  3887. need to be a heading, but there always needs to be a slash after
  3888. datetree. For example, to store archived items directly in the
  3889. datetree, use \"~/org/datetree.org::datetree/\".
  3890. \"basement::** Finished Tasks\"
  3891. Archive in file ./basement (relative path), as level 3 trees
  3892. below the level 2 heading \"** Finished Tasks\".
  3893. You may set this option on a per-file basis by adding to the buffer a
  3894. line like
  3895. #+ARCHIVE: basement::** Finished Tasks
  3896. You may also define it locally for a subtree by setting an ARCHIVE property
  3897. in the entry. If such a property is found in an entry, or anywhere up
  3898. the hierarchy, it will be used."
  3899. :group 'org-archive
  3900. :type 'string)
  3901. (defcustom org-agenda-skip-archived-trees t
  3902. "Non-nil means the agenda will skip any items located in archived trees.
  3903. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3904. variable is no longer recommended, you should leave it at the value t.
  3905. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3906. :group 'org-archive
  3907. :group 'org-agenda-skip
  3908. :type 'boolean)
  3909. (defcustom org-columns-skip-archived-trees t
  3910. "Non-nil means ignore archived trees when creating column view."
  3911. :group 'org-archive
  3912. :group 'org-properties
  3913. :type 'boolean)
  3914. (defcustom org-cycle-open-archived-trees nil
  3915. "Non-nil means `org-cycle' will open archived trees.
  3916. An archived tree is a tree marked with the tag ARCHIVE.
  3917. When nil, archived trees will stay folded. You can still open them with
  3918. normal outline commands like `show-all', but not with the cycling commands."
  3919. :group 'org-archive
  3920. :group 'org-cycle
  3921. :type 'boolean)
  3922. (defcustom org-sparse-tree-open-archived-trees nil
  3923. "Non-nil means sparse tree construction shows matches in archived trees.
  3924. When nil, matches in these trees are highlighted, but the trees are kept in
  3925. collapsed state."
  3926. :group 'org-archive
  3927. :group 'org-sparse-trees
  3928. :type 'boolean)
  3929. (defcustom org-sparse-tree-default-date-type nil
  3930. "The default date type when building a sparse tree.
  3931. When this is nil, a date is a scheduled or a deadline timestamp.
  3932. Otherwise, these types are allowed:
  3933. all: all timestamps
  3934. active: only active timestamps (<...>)
  3935. inactive: only inactive timestamps ([...])
  3936. scheduled: only scheduled timestamps
  3937. deadline: only deadline timestamps"
  3938. :type '(choice (const :tag "Scheduled or deadline" nil)
  3939. (const :tag "All timestamps" all)
  3940. (const :tag "Only active timestamps" active)
  3941. (const :tag "Only inactive timestamps" inactive)
  3942. (const :tag "Only scheduled timestamps" scheduled)
  3943. (const :tag "Only deadline timestamps" deadline)
  3944. (const :tag "Only closed timestamps" closed))
  3945. :version "26.1"
  3946. :package-version '(Org . "8.3")
  3947. :group 'org-sparse-trees)
  3948. (defun org-cycle-hide-archived-subtrees (state)
  3949. "Re-hide all archived subtrees after a visibility state change.
  3950. STATE should be one of the symbols listed in the docstring of
  3951. `org-cycle-hook'."
  3952. (when (and (not org-cycle-open-archived-trees)
  3953. (not (memq state '(overview folded))))
  3954. (save-excursion
  3955. (let* ((globalp (memq state '(contents all)))
  3956. (beg (if globalp (point-min) (point)))
  3957. (end (if globalp (point-max) (org-end-of-subtree t))))
  3958. (org-hide-archived-subtrees beg end)
  3959. (goto-char beg)
  3960. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3961. (message "%s" (substitute-command-keys
  3962. "Subtree is archived and stays closed. Use \
  3963. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3964. (defun org-force-cycle-archived ()
  3965. "Cycle subtree even if it is archived."
  3966. (interactive)
  3967. (setq this-command 'org-cycle)
  3968. (let ((org-cycle-open-archived-trees t))
  3969. (call-interactively 'org-cycle)))
  3970. (defun org-hide-archived-subtrees (beg end)
  3971. "Re-hide all archived subtrees after a visibility state change."
  3972. (org-with-wide-buffer
  3973. (let ((case-fold-search nil)
  3974. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3975. (goto-char beg)
  3976. ;; Include headline point is currently on.
  3977. (beginning-of-line)
  3978. (while (and (< (point) end) (re-search-forward re end t))
  3979. (when (member org-archive-tag (org-get-tags))
  3980. (org-flag-subtree t)
  3981. (org-end-of-subtree t))))))
  3982. (defun org-flag-subtree (flag)
  3983. (save-excursion
  3984. (org-back-to-heading t)
  3985. (org-flag-region (line-end-position)
  3986. (progn (org-end-of-subtree t) (point))
  3987. flag
  3988. 'outline)))
  3989. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3990. ;; Declare Column View Code
  3991. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3992. (declare-function org-columns-compute "org-colview" (property))
  3993. ;; Declare ID code
  3994. (declare-function org-id-store-link "org-id")
  3995. (declare-function org-id-locations-load "org-id")
  3996. (declare-function org-id-locations-save "org-id")
  3997. (defvar org-id-track-globally)
  3998. ;;; Variables for pre-computed regular expressions, all buffer local
  3999. (defvar-local org-todo-regexp nil
  4000. "Matches any of the TODO state keywords.
  4001. Since TODO keywords are case-sensitive, `case-fold-search' is
  4002. expected to be bound to nil when matching against this regexp.")
  4003. (defvar-local org-not-done-regexp nil
  4004. "Matches any of the TODO state keywords except the last one.
  4005. Since TODO keywords are case-sensitive, `case-fold-search' is
  4006. expected to be bound to nil when matching against this regexp.")
  4007. (defvar-local org-not-done-heading-regexp nil
  4008. "Matches a TODO headline that is not done.
  4009. Since TODO keywords are case-sensitive, `case-fold-search' is
  4010. expected to be bound to nil when matching against this regexp.")
  4011. (defvar-local org-todo-line-regexp nil
  4012. "Matches a headline and puts TODO state into group 2 if present.
  4013. Since TODO keywords are case-sensitive, `case-fold-search' is
  4014. expected to be bound to nil when matching against this regexp.")
  4015. (defvar-local org-complex-heading-regexp nil
  4016. "Matches a headline and puts everything into groups:
  4017. group 1: Stars
  4018. group 2: The TODO keyword, maybe
  4019. group 3: Priority cookie
  4020. group 4: True headline
  4021. group 5: Tags
  4022. Since TODO keywords are case-sensitive, `case-fold-search' is
  4023. expected to be bound to nil when matching against this regexp.")
  4024. (defvar-local org-complex-heading-regexp-format nil
  4025. "Printf format to make regexp to match an exact headline.
  4026. This regexp will match the headline of any node which has the
  4027. exact headline text that is put into the format, but may have any
  4028. TODO state, priority and tags.")
  4029. (defvar-local org-todo-line-tags-regexp nil
  4030. "Matches a headline and puts TODO state into group 2 if present.
  4031. Also put tags into group 4 if tags are present.")
  4032. (defconst org-plain-time-of-day-regexp
  4033. (concat
  4034. "\\(\\<[012]?[0-9]"
  4035. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4036. "\\(--?"
  4037. "\\(\\<[012]?[0-9]"
  4038. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4039. "\\)?")
  4040. "Regular expression to match a plain time or time range.
  4041. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4042. groups carry important information:
  4043. 0 the full match
  4044. 1 the first time, range or not
  4045. 8 the second time, if it is a range.")
  4046. (defconst org-plain-time-extension-regexp
  4047. (concat
  4048. "\\(\\<[012]?[0-9]"
  4049. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4050. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4051. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4052. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4053. groups carry important information:
  4054. 0 the full match
  4055. 7 hours of duration
  4056. 9 minutes of duration")
  4057. (defconst org-stamp-time-of-day-regexp
  4058. (concat
  4059. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4060. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4061. "\\(--?"
  4062. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4063. "Regular expression to match a timestamp time or time range.
  4064. After a match, the following groups carry important information:
  4065. 0 the full match
  4066. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4067. 2 the first time, range or not
  4068. 4 the second time, if it is a range.")
  4069. (defconst org-startup-options
  4070. '(("fold" org-startup-folded t)
  4071. ("overview" org-startup-folded t)
  4072. ("nofold" org-startup-folded nil)
  4073. ("showall" org-startup-folded nil)
  4074. ("showeverything" org-startup-folded showeverything)
  4075. ("content" org-startup-folded content)
  4076. ("indent" org-startup-indented t)
  4077. ("noindent" org-startup-indented nil)
  4078. ("hidestars" org-hide-leading-stars t)
  4079. ("showstars" org-hide-leading-stars nil)
  4080. ("odd" org-odd-levels-only t)
  4081. ("oddeven" org-odd-levels-only nil)
  4082. ("align" org-startup-align-all-tables t)
  4083. ("noalign" org-startup-align-all-tables nil)
  4084. ("shrink" org-startup-shrink-all-tables t)
  4085. ("inlineimages" org-startup-with-inline-images t)
  4086. ("noinlineimages" org-startup-with-inline-images nil)
  4087. ("latexpreview" org-startup-with-latex-preview t)
  4088. ("nolatexpreview" org-startup-with-latex-preview nil)
  4089. ("customtime" org-display-custom-times t)
  4090. ("logdone" org-log-done time)
  4091. ("lognotedone" org-log-done note)
  4092. ("nologdone" org-log-done nil)
  4093. ("lognoteclock-out" org-log-note-clock-out t)
  4094. ("nolognoteclock-out" org-log-note-clock-out nil)
  4095. ("logrepeat" org-log-repeat state)
  4096. ("lognoterepeat" org-log-repeat note)
  4097. ("logdrawer" org-log-into-drawer t)
  4098. ("nologdrawer" org-log-into-drawer nil)
  4099. ("logstatesreversed" org-log-states-order-reversed t)
  4100. ("nologstatesreversed" org-log-states-order-reversed nil)
  4101. ("nologrepeat" org-log-repeat nil)
  4102. ("logreschedule" org-log-reschedule time)
  4103. ("lognotereschedule" org-log-reschedule note)
  4104. ("nologreschedule" org-log-reschedule nil)
  4105. ("logredeadline" org-log-redeadline time)
  4106. ("lognoteredeadline" org-log-redeadline note)
  4107. ("nologredeadline" org-log-redeadline nil)
  4108. ("logrefile" org-log-refile time)
  4109. ("lognoterefile" org-log-refile note)
  4110. ("nologrefile" org-log-refile nil)
  4111. ("fninline" org-footnote-define-inline t)
  4112. ("nofninline" org-footnote-define-inline nil)
  4113. ("fnlocal" org-footnote-section nil)
  4114. ("fnauto" org-footnote-auto-label t)
  4115. ("fnprompt" org-footnote-auto-label nil)
  4116. ("fnconfirm" org-footnote-auto-label confirm)
  4117. ("fnplain" org-footnote-auto-label plain)
  4118. ("fnadjust" org-footnote-auto-adjust t)
  4119. ("nofnadjust" org-footnote-auto-adjust nil)
  4120. ("constcgs" constants-unit-system cgs)
  4121. ("constSI" constants-unit-system SI)
  4122. ("noptag" org-tag-persistent-alist nil)
  4123. ("hideblocks" org-hide-block-startup t)
  4124. ("nohideblocks" org-hide-block-startup nil)
  4125. ("beamer" org-startup-with-beamer-mode t)
  4126. ("entitiespretty" org-pretty-entities t)
  4127. ("entitiesplain" org-pretty-entities nil))
  4128. "Variable associated with STARTUP options for Org.
  4129. Each element is a list of three items: the startup options (as written
  4130. in the #+STARTUP line), the corresponding variable, and the value to set
  4131. this variable to if the option is found. An optional forth element PUSH
  4132. means to push this value onto the list in the variable.")
  4133. (defcustom org-group-tags t
  4134. "When non-nil (the default), use group tags.
  4135. This can be turned on/off through `org-toggle-tags-groups'."
  4136. :group 'org-tags
  4137. :group 'org-startup
  4138. :type 'boolean)
  4139. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4140. (defun org-toggle-tags-groups ()
  4141. "Toggle support for group tags.
  4142. Support for group tags is controlled by the option
  4143. `org-group-tags', which is non-nil by default."
  4144. (interactive)
  4145. (setq org-group-tags (not org-group-tags))
  4146. (cond ((and (derived-mode-p 'org-agenda-mode)
  4147. org-group-tags)
  4148. (org-agenda-redo))
  4149. ((derived-mode-p 'org-mode)
  4150. (let ((org-inhibit-startup t)) (org-mode))))
  4151. (message "Groups tags support has been turned %s"
  4152. (if org-group-tags "on" "off")))
  4153. (defun org-set-regexps-and-options (&optional tags-only)
  4154. "Precompute regular expressions used in the current buffer.
  4155. When optional argument TAGS-ONLY is non-nil, only compute tags
  4156. related expressions."
  4157. (when (derived-mode-p 'org-mode)
  4158. (let ((alist (org--setup-collect-keywords
  4159. (org-make-options-regexp
  4160. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4161. (and (not tags-only)
  4162. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4163. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4164. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4165. ;; Startup options. Get this early since it does change
  4166. ;; behavior for other options (e.g., tags).
  4167. (let ((startup (cdr (assq 'startup alist))))
  4168. (dolist (option startup)
  4169. (let ((entry (assoc-string option org-startup-options t)))
  4170. (when entry
  4171. (let ((var (nth 1 entry))
  4172. (val (nth 2 entry)))
  4173. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4174. (unless (listp (symbol-value var))
  4175. (set (make-local-variable var) nil))
  4176. (add-to-list var val)))))))
  4177. (setq-local org-file-tags
  4178. (mapcar #'org-add-prop-inherited
  4179. (cdr (assq 'filetags alist))))
  4180. (setq org-current-tag-alist
  4181. (append org-tag-persistent-alist
  4182. (let ((tags (cdr (assq 'tags alist))))
  4183. (if tags (org-tag-string-to-alist tags)
  4184. org-tag-alist))))
  4185. (setq org-tag-groups-alist
  4186. (org-tag-alist-to-groups org-current-tag-alist))
  4187. (unless tags-only
  4188. ;; File properties.
  4189. (setq-local org-file-properties (cdr (assq 'property alist)))
  4190. ;; Archive location.
  4191. (let ((archive (cdr (assq 'archive alist))))
  4192. (when archive (setq-local org-archive-location archive)))
  4193. ;; Category.
  4194. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4195. (when cat
  4196. (setq-local org-category (intern cat))
  4197. (setq-local org-file-properties
  4198. (org--update-property-plist
  4199. "CATEGORY" cat org-file-properties))))
  4200. ;; Columns.
  4201. (let ((column (cdr (assq 'columns alist))))
  4202. (when column (setq-local org-columns-default-format column)))
  4203. ;; Constants.
  4204. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4205. ;; Link abbreviations.
  4206. (let ((links (cdr (assq 'link alist))))
  4207. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4208. ;; Priorities.
  4209. (let ((priorities (cdr (assq 'priorities alist))))
  4210. (when priorities
  4211. (setq-local org-highest-priority (nth 0 priorities))
  4212. (setq-local org-lowest-priority (nth 1 priorities))
  4213. (setq-local org-default-priority (nth 2 priorities))))
  4214. ;; Scripts.
  4215. (let ((scripts (assq 'scripts alist)))
  4216. (when scripts
  4217. (setq-local org-use-sub-superscripts (cdr scripts))))
  4218. ;; TODO keywords.
  4219. (setq-local org-todo-kwd-alist nil)
  4220. (setq-local org-todo-key-alist nil)
  4221. (setq-local org-todo-key-trigger nil)
  4222. (setq-local org-todo-keywords-1 nil)
  4223. (setq-local org-done-keywords nil)
  4224. (setq-local org-todo-heads nil)
  4225. (setq-local org-todo-sets nil)
  4226. (setq-local org-todo-log-states nil)
  4227. (let ((todo-sequences
  4228. (or (nreverse (cdr (assq 'todo alist)))
  4229. (let ((d (default-value 'org-todo-keywords)))
  4230. (if (not (stringp (car d))) d
  4231. ;; XXX: Backward compatibility code.
  4232. (list (cons org-todo-interpretation d)))))))
  4233. (dolist (sequence todo-sequences)
  4234. (let* ((sequence (or (run-hook-with-args-until-success
  4235. 'org-todo-setup-filter-hook sequence)
  4236. sequence))
  4237. (sequence-type (car sequence))
  4238. (keywords (cdr sequence))
  4239. (sep (member "|" keywords))
  4240. names alist)
  4241. (dolist (k (remove "|" keywords))
  4242. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4243. k)
  4244. (error "Invalid TODO keyword %s" k))
  4245. (let ((name (match-string 1 k))
  4246. (key (match-string 2 k))
  4247. (log (org-extract-log-state-settings k)))
  4248. (push name names)
  4249. (push (cons name (and key (string-to-char key))) alist)
  4250. (when log (push log org-todo-log-states))))
  4251. (let* ((names (nreverse names))
  4252. (done (if sep (org-remove-keyword-keys (cdr sep))
  4253. (last names)))
  4254. (head (car names))
  4255. (tail (list sequence-type head (car done) (org-last done))))
  4256. (add-to-list 'org-todo-heads head 'append)
  4257. (push names org-todo-sets)
  4258. (setq org-done-keywords (append org-done-keywords done nil))
  4259. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4260. (setq org-todo-key-alist
  4261. (append org-todo-key-alist
  4262. (and alist
  4263. (append '((:startgroup))
  4264. (nreverse alist)
  4265. '((:endgroup))))))
  4266. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4267. (setq org-todo-sets (nreverse org-todo-sets)
  4268. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4269. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4270. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4271. ;; Compute the regular expressions and other local variables.
  4272. ;; Using `org-outline-regexp-bol' would complicate them much,
  4273. ;; because of the fixed white space at the end of that string.
  4274. (unless org-done-keywords
  4275. (setq org-done-keywords
  4276. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4277. (setq org-not-done-keywords
  4278. (org-delete-all org-done-keywords
  4279. (copy-sequence org-todo-keywords-1))
  4280. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4281. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4282. org-not-done-heading-regexp
  4283. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4284. org-todo-line-regexp
  4285. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4286. org-complex-heading-regexp
  4287. (concat "^\\(\\*+\\)"
  4288. "\\(?: +" org-todo-regexp "\\)?"
  4289. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4290. "\\(?: +\\(.*?\\)\\)??"
  4291. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4292. "[ \t]*$")
  4293. org-complex-heading-regexp-format
  4294. (concat "^\\(\\*+\\)"
  4295. "\\(?: +" org-todo-regexp "\\)?"
  4296. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4297. "\\(?: +"
  4298. ;; Stats cookies can be stuck to body.
  4299. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4300. "\\(%s\\)"
  4301. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4302. "\\)"
  4303. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4304. "[ \t]*$")
  4305. org-todo-line-tags-regexp
  4306. (concat "^\\(\\*+\\)"
  4307. "\\(?: +" org-todo-regexp "\\)?"
  4308. "\\(?: +\\(.*?\\)\\)??"
  4309. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4310. "[ \t]*$"))
  4311. (org-compute-latex-and-related-regexp)))))
  4312. (defun org--setup-collect-keywords (regexp &optional files alist)
  4313. "Return setup keywords values as an alist.
  4314. REGEXP matches a subset of setup keywords. FILES is a list of
  4315. file names already visited. It is used to avoid circular setup
  4316. files. ALIST, when non-nil, is the alist computed so far.
  4317. Return value contains the following keys: `archive', `category',
  4318. `columns', `constants', `filetags', `link', `priorities',
  4319. `property', `scripts', `startup', `tags' and `todo'."
  4320. (org-with-wide-buffer
  4321. (goto-char (point-min))
  4322. (let ((case-fold-search t))
  4323. (while (re-search-forward regexp nil t)
  4324. (let ((element (org-element-at-point)))
  4325. (when (eq (org-element-type element) 'keyword)
  4326. (let ((key (org-element-property :key element))
  4327. (value (org-element-property :value element)))
  4328. (cond
  4329. ((equal key "ARCHIVE")
  4330. (when (org-string-nw-p value)
  4331. (push (cons 'archive value) alist)))
  4332. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4333. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4334. ((equal key "CONSTANTS")
  4335. (let* ((constants (assq 'constants alist))
  4336. (store (cdr constants)))
  4337. (dolist (pair (split-string value))
  4338. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4339. pair)
  4340. (let* ((name (match-string 1 pair))
  4341. (value (match-string 2 pair))
  4342. (old (assoc name store)))
  4343. (if old (setcdr old value)
  4344. (push (cons name value) store)))))
  4345. (if constants (setcdr constants store)
  4346. (push (cons 'constants store) alist))))
  4347. ((equal key "FILETAGS")
  4348. (when (org-string-nw-p value)
  4349. (let ((old (assq 'filetags alist))
  4350. (new (apply #'nconc
  4351. (mapcar (lambda (x) (org-split-string x ":"))
  4352. (split-string value)))))
  4353. (if old (setcdr old (append new (cdr old)))
  4354. (push (cons 'filetags new) alist)))))
  4355. ((equal key "LINK")
  4356. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4357. (let ((links (assq 'link alist))
  4358. (pair (cons (match-string-no-properties 1 value)
  4359. (match-string-no-properties 2 value))))
  4360. (if links (push pair (cdr links))
  4361. (push (list 'link pair) alist)))))
  4362. ((equal key "OPTIONS")
  4363. (when (and (org-string-nw-p value)
  4364. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4365. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4366. ((equal key "PRIORITIES")
  4367. (push (cons 'priorities
  4368. (let ((prio (split-string value)))
  4369. (if (< (length prio) 3) '(?A ?C ?B)
  4370. (mapcar #'string-to-char prio))))
  4371. alist))
  4372. ((equal key "PROPERTY")
  4373. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4374. (let* ((property (assq 'property alist))
  4375. (value (org--update-property-plist
  4376. (match-string-no-properties 1 value)
  4377. (match-string-no-properties 2 value)
  4378. (cdr property))))
  4379. (if property (setcdr property value)
  4380. (push (cons 'property value) alist)))))
  4381. ((equal key "STARTUP")
  4382. (let ((startup (assq 'startup alist)))
  4383. (if startup
  4384. (setcdr startup
  4385. (append (cdr startup) (split-string value)))
  4386. (push (cons 'startup (split-string value)) alist))))
  4387. ((equal key "TAGS")
  4388. (let ((tag-cell (assq 'tags alist)))
  4389. (if tag-cell
  4390. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4391. (push (cons 'tags value) alist))))
  4392. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4393. (let ((todo (assq 'todo alist))
  4394. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4395. (split-string value))))
  4396. (if todo (push value (cdr todo))
  4397. (push (list 'todo value) alist))))
  4398. ((equal key "SETUPFILE")
  4399. (unless buffer-read-only ; Do not check in Gnus messages.
  4400. (let ((f (and (org-string-nw-p value)
  4401. (expand-file-name
  4402. (org-unbracket-string "\"" "\"" value)))))
  4403. (when (and f (file-readable-p f) (not (member f files)))
  4404. (with-temp-buffer
  4405. (setq default-directory (file-name-directory f))
  4406. (insert-file-contents f)
  4407. (setq alist
  4408. ;; Fake Org mode to benefit from cache
  4409. ;; without recurring needlessly.
  4410. (let ((major-mode 'org-mode))
  4411. (org--setup-collect-keywords
  4412. regexp (cons f files) alist)))))))))))))))
  4413. alist)
  4414. (defun org-tag-string-to-alist (s)
  4415. "Return tag alist associated to string S.
  4416. S is a value for TAGS keyword or produced with
  4417. `org-tag-alist-to-string'. Return value is an alist suitable for
  4418. `org-tag-alist' or `org-tag-persistent-alist'."
  4419. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4420. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4421. "\\|{.+?}\\)" ; regular expression
  4422. "\\(?:(\\(.\\))\\)?\\'"))
  4423. alist group-flag)
  4424. (dolist (tokens lines (cdr (nreverse alist)))
  4425. (push '(:newline) alist)
  4426. (while tokens
  4427. (let ((token (pop tokens)))
  4428. (pcase token
  4429. ("{"
  4430. (push '(:startgroup) alist)
  4431. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4432. ("}"
  4433. (push '(:endgroup) alist)
  4434. (setq group-flag nil))
  4435. ("["
  4436. (push '(:startgrouptag) alist)
  4437. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4438. ("]"
  4439. (push '(:endgrouptag) alist)
  4440. (setq group-flag nil))
  4441. (":"
  4442. (push '(:grouptags) alist))
  4443. ((guard (string-match tag-re token))
  4444. (let ((tag (match-string 1 token))
  4445. (key (and (match-beginning 2)
  4446. (string-to-char (match-string 2 token)))))
  4447. ;; Push all tags in groups, no matter if they already
  4448. ;; appear somewhere else in the list.
  4449. (when (or group-flag (not (assoc tag alist)))
  4450. (push (cons tag key) alist))))))))))
  4451. (defun org-tag-alist-to-string (alist &optional skip-key)
  4452. "Return tag string associated to ALIST.
  4453. ALIST is an alist, as defined in `org-tag-alist' or
  4454. `org-tag-persistent-alist', or produced with
  4455. `org-tag-string-to-alist'.
  4456. Return value is a string suitable as a value for \"TAGS\"
  4457. keyword.
  4458. When optional argument SKIP-KEY is non-nil, skip selection keys
  4459. next to tags."
  4460. (mapconcat (lambda (token)
  4461. (pcase token
  4462. (`(:startgroup) "{")
  4463. (`(:endgroup) "}")
  4464. (`(:startgrouptag) "[")
  4465. (`(:endgrouptag) "]")
  4466. (`(:grouptags) ":")
  4467. (`(:newline) "\\n")
  4468. ((and
  4469. (guard (not skip-key))
  4470. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4471. (format "%s(%c)" tag key))
  4472. (`(,(and tag (pred stringp)) . ,_) tag)
  4473. (_ (user-error "Invalid tag token: %S" token))))
  4474. alist
  4475. " "))
  4476. (defun org-tag-alist-to-groups (alist)
  4477. "Return group alist from tag ALIST.
  4478. ALIST is an alist, as defined in `org-tag-alist' or
  4479. `org-tag-persistent-alist', or produced with
  4480. `org-tag-string-to-alist'. Return value is an alist following
  4481. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4482. a string, summarizing TAGS, as a list of strings."
  4483. (let (groups group-status current-group)
  4484. (dolist (token alist (nreverse groups))
  4485. (pcase token
  4486. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4487. (`(,(or :endgroup :endgrouptag))
  4488. (when (eq group-status 'append)
  4489. (push (nreverse current-group) groups))
  4490. (setq group-status nil))
  4491. (`(:grouptags) (setq group-status 'append))
  4492. ((and `(,tag . ,_) (guard group-status))
  4493. (if (eq group-status 'append) (push tag current-group)
  4494. (setq current-group (list tag))))
  4495. (_ nil)))))
  4496. (defvar org--file-cache (make-hash-table :test #'equal)
  4497. "Hash table to store contents of files referenced via a URL.
  4498. This is the cache of file URLs read using `org-file-contents'.")
  4499. (defun org-reset-file-cache ()
  4500. "Reset the cache of files downloaded by `org-file-contents'."
  4501. (clrhash org--file-cache))
  4502. (defun org-file-url-p (file)
  4503. "Non-nil if FILE is a URL."
  4504. (require 'ffap)
  4505. (string-match-p ffap-url-regexp file))
  4506. (defun org-file-contents (file &optional noerror nocache)
  4507. "Return the contents of FILE, as a string.
  4508. FILE can be a file name or URL.
  4509. If FILE is a URL, download the contents. If the URL contents are
  4510. already cached in the `org--file-cache' hash table, the download step
  4511. is skipped.
  4512. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4513. from file or URL.
  4514. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4515. is available. This option applies only if FILE is a URL."
  4516. (let* ((is-url (org-file-url-p file))
  4517. (cache (and is-url
  4518. (not nocache)
  4519. (gethash file org--file-cache))))
  4520. (cond
  4521. (cache)
  4522. (is-url
  4523. (with-current-buffer (url-retrieve-synchronously file)
  4524. (goto-char (point-min))
  4525. ;; Move point to after the url-retrieve header.
  4526. (search-forward "\n\n" nil :move)
  4527. ;; Search for the success code only in the url-retrieve header.
  4528. (if (save-excursion
  4529. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4530. ;; Update the cache `org--file-cache' and return contents.
  4531. (puthash file
  4532. (buffer-substring-no-properties (point) (point-max))
  4533. org--file-cache)
  4534. (funcall (if noerror #'message #'user-error)
  4535. "Unable to fetch file from %S"
  4536. file))))
  4537. (t
  4538. (with-temp-buffer
  4539. (condition-case nil
  4540. (progn
  4541. (insert-file-contents file)
  4542. (buffer-string))
  4543. (file-error
  4544. (funcall (if noerror #'message #'user-error)
  4545. "Unable to read file %S"
  4546. file))))))))
  4547. (defun org-extract-log-state-settings (x)
  4548. "Extract the log state setting from a TODO keyword string.
  4549. This will extract info from a string like \"WAIT(w@/!)\"."
  4550. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4551. (let ((kw (match-string 1 x))
  4552. (log1 (and (match-end 3) (match-string 3 x)))
  4553. (log2 (and (match-end 4) (match-string 4 x))))
  4554. (and (or log1 log2)
  4555. (list kw
  4556. (and log1 (if (equal log1 "!") 'time 'note))
  4557. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4558. (defun org-remove-keyword-keys (list)
  4559. "Remove a pair of parenthesis at the end of each string in LIST."
  4560. (mapcar (lambda (x)
  4561. (if (string-match "(.*)$" x)
  4562. (substring x 0 (match-beginning 0))
  4563. x))
  4564. list))
  4565. (defun org-assign-fast-keys (alist)
  4566. "Assign fast keys to a keyword-key alist.
  4567. Respect keys that are already there."
  4568. (let (new e (alt ?0))
  4569. (while (setq e (pop alist))
  4570. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4571. (cdr e)) ;; Key already assigned.
  4572. (push e new)
  4573. (let ((clist (string-to-list (downcase (car e))))
  4574. (used (append new alist)))
  4575. (when (= (car clist) ?@)
  4576. (pop clist))
  4577. (while (and clist (rassoc (car clist) used))
  4578. (pop clist))
  4579. (unless clist
  4580. (while (rassoc alt used)
  4581. (cl-incf alt)))
  4582. (push (cons (car e) (or (car clist) alt)) new))))
  4583. (nreverse new)))
  4584. ;;; Some variables used in various places
  4585. (defvar org-window-configuration nil
  4586. "Used in various places to store a window configuration.")
  4587. (defvar org-selected-window nil
  4588. "Used in various places to store a window configuration.")
  4589. (defvar org-finish-function nil
  4590. "Function to be called when `C-c C-c' is used.
  4591. This is for getting out of special buffers like capture.")
  4592. (defvar org-last-state)
  4593. ;; Defined somewhere in this file, but used before definition.
  4594. (defvar org-entities) ;; defined in org-entities.el
  4595. (defvar org-struct-menu)
  4596. (defvar org-org-menu)
  4597. (defvar org-tbl-menu)
  4598. ;;;; Define the Org mode
  4599. ;; We use a before-change function to check if a table might need
  4600. ;; an update.
  4601. (defvar org-table-may-need-update t
  4602. "Indicates that a table might need an update.
  4603. This variable is set by `org-before-change-function'.
  4604. `org-table-align' sets it back to nil.")
  4605. (defun org-before-change-function (_beg _end)
  4606. "Every change indicates that a table might need an update."
  4607. (setq org-table-may-need-update t))
  4608. (defvar org-mode-map)
  4609. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4610. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4611. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4612. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4613. (defvar org-table-buffer-is-an nil)
  4614. (defvar bidi-paragraph-direction)
  4615. (defvar buffer-face-mode-face)
  4616. (require 'outline)
  4617. ;; Other stuff we need.
  4618. (require 'time-date)
  4619. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4620. (require 'easymenu)
  4621. (autoload 'easy-menu-add "easymenu")
  4622. (require 'overlay)
  4623. ;; (require 'org-macs) moved higher up in the file before it is first used
  4624. (require 'org-entities)
  4625. ;; (require 'org-compat) moved higher up in the file before it is first used
  4626. (require 'org-faces)
  4627. (require 'org-list)
  4628. (require 'org-pcomplete)
  4629. (require 'org-src)
  4630. (require 'org-footnote)
  4631. (require 'org-macro)
  4632. ;; babel
  4633. (require 'ob)
  4634. ;;;###autoload
  4635. (define-derived-mode org-mode outline-mode "Org"
  4636. "Outline-based notes management and organizer, alias
  4637. \"Carsten's outline-mode for keeping track of everything.\"
  4638. Org mode develops organizational tasks around a NOTES file which
  4639. contains information about projects as plain text. Org mode is
  4640. implemented on top of Outline mode, which is ideal to keep the content
  4641. of large files well structured. It supports ToDo items, deadlines and
  4642. time stamps, which magically appear in the diary listing of the Emacs
  4643. calendar. Tables are easily created with a built-in table editor.
  4644. Plain text URL-like links connect to websites, emails (VM), Usenet
  4645. messages (Gnus), BBDB entries, and any files related to the project.
  4646. For printing and sharing of notes, an Org file (or a part of it)
  4647. can be exported as a structured ASCII or HTML file.
  4648. The following commands are available:
  4649. \\{org-mode-map}"
  4650. ;; Get rid of Outline menus, they are not needed
  4651. ;; Need to do this here because define-derived-mode sets up
  4652. ;; the keymap so late. Still, it is a waste to call this each time
  4653. ;; we switch another buffer into Org mode.
  4654. (define-key org-mode-map [menu-bar headings] 'undefined)
  4655. (define-key org-mode-map [menu-bar hide] 'undefined)
  4656. (define-key org-mode-map [menu-bar show] 'undefined)
  4657. (org-load-modules-maybe)
  4658. (org-install-agenda-files-menu)
  4659. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4660. (add-to-invisibility-spec '(org-hide-block . t))
  4661. (add-to-invisibility-spec '(org-hide-drawer . t))
  4662. (setq-local outline-regexp org-outline-regexp)
  4663. (setq-local outline-level 'org-outline-level)
  4664. (setq bidi-paragraph-direction 'left-to-right)
  4665. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4666. (unless org-display-table
  4667. (setq org-display-table (make-display-table)))
  4668. (set-display-table-slot
  4669. org-display-table 4
  4670. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4671. org-ellipsis)))
  4672. (setq buffer-display-table org-display-table))
  4673. (org-set-regexps-and-options)
  4674. (org-set-font-lock-defaults)
  4675. (when (and org-tag-faces (not org-tags-special-faces-re))
  4676. ;; tag faces set outside customize.... force initialization.
  4677. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4678. ;; Calc embedded
  4679. (setq-local calc-embedded-open-mode "# ")
  4680. ;; Modify a few syntax entries
  4681. (modify-syntax-entry ?@ "w")
  4682. (modify-syntax-entry ?\" "\"")
  4683. (modify-syntax-entry ?\\ "_")
  4684. (modify-syntax-entry ?~ "_")
  4685. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4686. ;; Activate before-change-function
  4687. (setq-local org-table-may-need-update t)
  4688. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4689. ;; Check for running clock before killing a buffer
  4690. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4691. ;; Initialize macros templates.
  4692. (org-macro-initialize-templates)
  4693. ;; Initialize radio targets.
  4694. (org-update-radio-target-regexp)
  4695. ;; Indentation.
  4696. (setq-local indent-line-function 'org-indent-line)
  4697. (setq-local indent-region-function 'org-indent-region)
  4698. ;; Filling and auto-filling.
  4699. (org-setup-filling)
  4700. ;; Comments.
  4701. (org-setup-comments-handling)
  4702. ;; Initialize cache.
  4703. (org-element-cache-reset)
  4704. ;; Beginning/end of defun
  4705. (setq-local beginning-of-defun-function 'org-backward-element)
  4706. (setq-local end-of-defun-function
  4707. (lambda ()
  4708. (if (not (org-at-heading-p))
  4709. (org-forward-element)
  4710. (org-forward-element)
  4711. (forward-char -1))))
  4712. ;; Next error for sparse trees
  4713. (setq-local next-error-function 'org-occur-next-match)
  4714. ;; Make sure dependence stuff works reliably, even for users who set it
  4715. ;; too late :-(
  4716. (if org-enforce-todo-dependencies
  4717. (add-hook 'org-blocker-hook
  4718. 'org-block-todo-from-children-or-siblings-or-parent)
  4719. (remove-hook 'org-blocker-hook
  4720. 'org-block-todo-from-children-or-siblings-or-parent))
  4721. (if org-enforce-todo-checkbox-dependencies
  4722. (add-hook 'org-blocker-hook
  4723. 'org-block-todo-from-checkboxes)
  4724. (remove-hook 'org-blocker-hook
  4725. 'org-block-todo-from-checkboxes))
  4726. ;; Align options lines
  4727. (setq-local
  4728. align-mode-rules-list
  4729. '((org-in-buffer-settings
  4730. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4731. (modes . '(org-mode)))))
  4732. ;; Imenu
  4733. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4734. ;; Make isearch reveal context
  4735. (setq-local outline-isearch-open-invisible-function
  4736. (lambda (&rest _) (org-show-context 'isearch)))
  4737. ;; Setup the pcomplete hooks
  4738. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4739. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4740. (setq-local pcomplete-default-completion-function 'ignore)
  4741. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4742. (setq-local pcomplete-termination-string "")
  4743. (setq-local buffer-face-mode-face 'org-default)
  4744. ;; If empty file that did not turn on Org mode automatically, make
  4745. ;; it to.
  4746. (when (and org-insert-mode-line-in-empty-file
  4747. (called-interactively-p 'any)
  4748. (= (point-min) (point-max)))
  4749. (insert "# -*- mode: org -*-\n\n"))
  4750. (unless org-inhibit-startup
  4751. (org-unmodified
  4752. (when org-startup-with-beamer-mode (org-beamer-mode))
  4753. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4754. (org-table-map-tables
  4755. (cond ((and org-startup-align-all-tables
  4756. org-startup-shrink-all-tables)
  4757. (lambda () (org-table-align) (org-table-shrink)))
  4758. (org-startup-align-all-tables #'org-table-align)
  4759. (t #'org-table-shrink))
  4760. t))
  4761. (when org-startup-with-inline-images (org-display-inline-images))
  4762. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4763. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4764. (when org-startup-truncated (setq truncate-lines t))
  4765. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4766. (org-refresh-effort-properties)))
  4767. ;; Try to set `org-hide' face correctly.
  4768. (let ((foreground (org-find-invisible-foreground)))
  4769. (when foreground
  4770. (set-face-foreground 'org-hide foreground))))
  4771. ;; Update `customize-package-emacs-version-alist'
  4772. (add-to-list 'customize-package-emacs-version-alist
  4773. '(Org ("8.0" . "24.4")
  4774. ("8.1" . "24.4")
  4775. ("8.2" . "24.4")
  4776. ("8.2.7" . "24.4")
  4777. ("8.3" . "26.1")
  4778. ("9.0" . "26.1")
  4779. ("9.1" . "26.1")
  4780. ("9.2" . "27.1")))
  4781. (defvar org-mode-transpose-word-syntax-table
  4782. (let ((st (make-syntax-table text-mode-syntax-table)))
  4783. (dolist (c org-emphasis-alist st)
  4784. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4785. (when (fboundp 'abbrev-table-put)
  4786. (abbrev-table-put org-mode-abbrev-table
  4787. :parents (list text-mode-abbrev-table)))
  4788. (defun org-find-invisible-foreground ()
  4789. (let ((candidates (remove
  4790. "unspecified-bg"
  4791. (nconc
  4792. (list (face-background 'default)
  4793. (face-background 'org-default))
  4794. (mapcar
  4795. (lambda (alist)
  4796. (when (boundp alist)
  4797. (cdr (assq 'background-color (symbol-value alist)))))
  4798. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4799. (list (face-foreground 'org-hide))))))
  4800. (car (remove nil candidates))))
  4801. (defun org-current-time (&optional rounding-minutes past)
  4802. "Current time, possibly rounded to ROUNDING-MINUTES.
  4803. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4804. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4805. the rounding returns a past time."
  4806. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4807. (car org-time-stamp-rounding-minutes)))
  4808. (time (decode-time)) res)
  4809. (if (< r 1)
  4810. (current-time)
  4811. (setq res
  4812. (apply 'encode-time
  4813. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4814. (nthcdr 2 time))))
  4815. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4816. (seconds-to-time (- (float-time res) (* r 60)))
  4817. res))))
  4818. (defun org-today ()
  4819. "Return today date, considering `org-extend-today-until'."
  4820. (time-to-days
  4821. (time-subtract (current-time)
  4822. (list 0 (* 3600 org-extend-today-until) 0))))
  4823. ;;;; Font-Lock stuff, including the activators
  4824. (defvar org-mouse-map (make-sparse-keymap))
  4825. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4826. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4827. (when org-mouse-1-follows-link
  4828. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4829. (when org-tab-follows-link
  4830. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4831. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4832. (require 'font-lock)
  4833. (defconst org-non-link-chars "]\t\n\r<>")
  4834. (defvar org-link-types-re nil
  4835. "Matches a link that has a url-like prefix like \"http:\"")
  4836. (defvar org-link-re-with-space nil
  4837. "Matches a link with spaces, optional angular brackets around it.")
  4838. (defvar org-link-re-with-space2 nil
  4839. "Matches a link with spaces, optional angular brackets around it.")
  4840. (defvar org-link-re-with-space3 nil
  4841. "Matches a link with spaces, only for internal part in bracket links.")
  4842. (defvar org-angle-link-re nil
  4843. "Matches link with angular brackets, spaces are allowed.")
  4844. (defvar org-plain-link-re nil
  4845. "Matches plain link, without spaces.")
  4846. (defvar org-bracket-link-regexp nil
  4847. "Matches a link in double brackets.")
  4848. (defvar org-bracket-link-analytic-regexp nil
  4849. "Regular expression used to analyze links.
  4850. Here is what the match groups contain after a match:
  4851. 1: http:
  4852. 2: http
  4853. 3: path
  4854. 4: [desc]
  4855. 5: desc")
  4856. (defvar org-bracket-link-analytic-regexp++ nil
  4857. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4858. (defvar org-any-link-re nil
  4859. "Regular expression matching any link.")
  4860. (defconst org-match-sexp-depth 3
  4861. "Number of stacked braces for sub/superscript matching.")
  4862. (defun org-create-multibrace-regexp (left right n)
  4863. "Create a regular expression which will match a balanced sexp.
  4864. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4865. as single character strings.
  4866. The regexp returned will match the entire expression including the
  4867. delimiters. It will also define a single group which contains the
  4868. match except for the outermost delimiters. The maximum depth of
  4869. stacked delimiters is N. Escaping delimiters is not possible."
  4870. (let* ((nothing (concat "[^" left right "]*?"))
  4871. (or "\\|")
  4872. (re nothing)
  4873. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4874. (while (> n 1)
  4875. (setq n (1- n)
  4876. re (concat re or next)
  4877. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4878. (concat left "\\(" re "\\)" right)))
  4879. (defconst org-match-substring-regexp
  4880. (concat
  4881. "\\(\\S-\\)\\([_^]\\)\\("
  4882. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4883. "\\|"
  4884. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4885. "\\|"
  4886. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4887. "The regular expression matching a sub- or superscript.")
  4888. (defconst org-match-substring-with-braces-regexp
  4889. (concat
  4890. "\\(\\S-\\)\\([_^]\\)"
  4891. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4892. "The regular expression matching a sub- or superscript, forcing braces.")
  4893. (defun org-make-link-regexps ()
  4894. "Update the link regular expressions.
  4895. This should be called after the variable `org-link-parameters' has changed."
  4896. (let ((types-re (regexp-opt (org-link-types) t)))
  4897. (setq org-link-types-re
  4898. (concat "\\`" types-re ":")
  4899. org-link-re-with-space
  4900. (concat "<?" types-re ":"
  4901. "\\([^" org-non-link-chars " ]"
  4902. "[^" org-non-link-chars "]*"
  4903. "[^" org-non-link-chars " ]\\)>?")
  4904. org-link-re-with-space2
  4905. (concat "<?" types-re ":"
  4906. "\\([^" org-non-link-chars " ]"
  4907. "[^\t\n\r]*"
  4908. "[^" org-non-link-chars " ]\\)>?")
  4909. org-link-re-with-space3
  4910. (concat "<?" types-re ":"
  4911. "\\([^" org-non-link-chars " ]"
  4912. "[^\t\n\r]*\\)")
  4913. org-angle-link-re
  4914. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4915. types-re)
  4916. org-plain-link-re
  4917. (concat
  4918. "\\<" types-re ":"
  4919. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4920. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4921. org-bracket-link-regexp
  4922. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4923. org-bracket-link-analytic-regexp
  4924. (concat
  4925. "\\[\\["
  4926. "\\(" types-re ":\\)?"
  4927. "\\([^]]+\\)"
  4928. "\\]"
  4929. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4930. "\\]")
  4931. org-bracket-link-analytic-regexp++
  4932. (concat
  4933. "\\[\\["
  4934. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4935. "\\([^]]+\\)"
  4936. "\\]"
  4937. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4938. "\\]")
  4939. org-any-link-re
  4940. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4941. org-angle-link-re "\\)\\|\\("
  4942. org-plain-link-re "\\)"))))
  4943. (org-make-link-regexps)
  4944. (defvar org-emph-face nil)
  4945. (defun org-do-emphasis-faces (limit)
  4946. "Run through the buffer and emphasize strings."
  4947. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4948. (car org-emphasis-regexp-components))))
  4949. (catch :exit
  4950. (while (re-search-forward quick-re limit t)
  4951. (let* ((marker (match-string 2))
  4952. (verbatim? (member marker '("~" "="))))
  4953. (when (save-excursion
  4954. (goto-char (match-beginning 0))
  4955. (and
  4956. ;; Do not match table hlines.
  4957. (not (and (equal marker "+")
  4958. (org-match-line
  4959. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4960. ;; Do not match headline stars. Do not consider
  4961. ;; stars of a headline as closing marker for bold
  4962. ;; markup either.
  4963. (not (and (equal marker "*")
  4964. (save-excursion
  4965. (forward-char)
  4966. (skip-chars-backward "*")
  4967. (looking-at-p org-outline-regexp-bol))))
  4968. ;; Match full emphasis markup regexp.
  4969. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4970. ;; Do not span over paragraph boundaries.
  4971. (not (string-match-p org-element-paragraph-separate
  4972. (match-string 2)))
  4973. ;; Do not span over cells in table rows.
  4974. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4975. (string-match-p "|" (match-string 4))))))
  4976. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4977. (font-lock-prepend-text-property
  4978. (match-beginning 2) (match-end 2) 'face face)
  4979. (when verbatim?
  4980. (org-remove-flyspell-overlays-in
  4981. (match-beginning 0) (match-end 0)))
  4982. (add-text-properties (match-beginning 2) (match-end 2)
  4983. '(font-lock-multiline t org-emphasis t))
  4984. (when org-hide-emphasis-markers
  4985. (add-text-properties (match-end 4) (match-beginning 5)
  4986. '(invisible org-link))
  4987. (add-text-properties (match-beginning 3) (match-end 3)
  4988. '(invisible org-link)))
  4989. (throw :exit t))))))))
  4990. (defun org-emphasize (&optional char)
  4991. "Insert or change an emphasis, i.e. a font like bold or italic.
  4992. If there is an active region, change that region to a new emphasis.
  4993. If there is no region, just insert the marker characters and position
  4994. the cursor between them.
  4995. CHAR should be the marker character. If it is a space, it means to
  4996. remove the emphasis of the selected region.
  4997. If CHAR is not given (for example in an interactive call) it will be
  4998. prompted for."
  4999. (interactive)
  5000. (let ((erc org-emphasis-regexp-components)
  5001. (string "") beg end move s)
  5002. (if (org-region-active-p)
  5003. (setq beg (region-beginning)
  5004. end (region-end)
  5005. string (buffer-substring beg end))
  5006. (setq move t))
  5007. (unless char
  5008. (message "Emphasis marker or tag: [%s]"
  5009. (mapconcat #'car org-emphasis-alist ""))
  5010. (setq char (read-char-exclusive)))
  5011. (if (equal char ?\s)
  5012. (setq s ""
  5013. move nil)
  5014. (unless (assoc (char-to-string char) org-emphasis-alist)
  5015. (user-error "No such emphasis marker: \"%c\"" char))
  5016. (setq s (char-to-string char)))
  5017. (while (and (> (length string) 1)
  5018. (equal (substring string 0 1) (substring string -1))
  5019. (assoc (substring string 0 1) org-emphasis-alist))
  5020. (setq string (substring string 1 -1)))
  5021. (setq string (concat s string s))
  5022. (when beg (delete-region beg end))
  5023. (unless (or (bolp)
  5024. (string-match (concat "[" (nth 0 erc) "\n]")
  5025. (char-to-string (char-before (point)))))
  5026. (insert " "))
  5027. (unless (or (eobp)
  5028. (string-match (concat "[" (nth 1 erc) "\n]")
  5029. (char-to-string (char-after (point)))))
  5030. (insert " ") (backward-char 1))
  5031. (insert string)
  5032. (and move (backward-char 1))))
  5033. (defconst org-nonsticky-props
  5034. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5035. (defsubst org-rear-nonsticky-at (pos)
  5036. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5037. (defun org-activate-links (limit)
  5038. "Add link properties to links.
  5039. This includes angle, plain, and bracket links."
  5040. (catch :exit
  5041. (while (re-search-forward org-any-link-re limit t)
  5042. (let* ((start (match-beginning 0))
  5043. (end (match-end 0))
  5044. (style (cond ((eq ?< (char-after start)) 'angle)
  5045. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5046. (t 'plain))))
  5047. (when (and (memq style org-highlight-links)
  5048. ;; Do not confuse plain links with tags.
  5049. (not (and (eq style 'plain)
  5050. (let ((face (get-text-property
  5051. (max (1- start) (point-min)) 'face)))
  5052. (if (consp face) (memq 'org-tag face)
  5053. (eq 'org-tag face))))))
  5054. (let* ((link-object (save-excursion
  5055. (goto-char start)
  5056. (save-match-data (org-element-link-parser))))
  5057. (link (org-element-property :raw-link link-object))
  5058. (type (org-element-property :type link-object))
  5059. (path (org-element-property :path link-object))
  5060. (properties ;for link's visible part
  5061. (list
  5062. 'face (pcase (org-link-get-parameter type :face)
  5063. ((and (pred functionp) face) (funcall face path))
  5064. ((and (pred facep) face) face)
  5065. ((and (pred consp) face) face) ;anonymous
  5066. (_ 'org-link))
  5067. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5068. 'highlight)
  5069. 'keymap (or (org-link-get-parameter type :keymap)
  5070. org-mouse-map)
  5071. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5072. ((and (pred stringp) echo) echo)
  5073. ((and (pred functionp) echo) echo)
  5074. (_ (concat "LINK: " link)))
  5075. 'htmlize-link (pcase (org-link-get-parameter type
  5076. :htmlize-link)
  5077. ((and (pred functionp) f) (funcall f))
  5078. (_ `(:uri ,link)))
  5079. 'font-lock-multiline t)))
  5080. (org-remove-flyspell-overlays-in start end)
  5081. (org-rear-nonsticky-at end)
  5082. (if (not (eq 'bracket style))
  5083. (add-text-properties start end properties)
  5084. ;; Handle invisible parts in bracket links.
  5085. (remove-text-properties start end '(invisible nil))
  5086. (let ((hidden
  5087. (append `(invisible
  5088. ,(or (org-link-get-parameter type :display)
  5089. 'org-link))
  5090. properties))
  5091. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5092. (visible-end (or (match-end 4) (match-end 2))))
  5093. (add-text-properties start visible-start hidden)
  5094. (add-text-properties visible-start visible-end properties)
  5095. (add-text-properties visible-end end hidden)
  5096. (org-rear-nonsticky-at visible-start)
  5097. (org-rear-nonsticky-at visible-end)))
  5098. (let ((f (org-link-get-parameter type :activate-func)))
  5099. (when (functionp f)
  5100. (funcall f start end path (eq style 'bracket))))
  5101. (throw :exit t))))) ;signal success
  5102. nil))
  5103. (defun org-activate-code (limit)
  5104. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5105. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5106. (remove-text-properties (match-beginning 0) (match-end 0)
  5107. '(display t invisible t intangible t))
  5108. t))
  5109. (defcustom org-src-fontify-natively t
  5110. "When non-nil, fontify code in code blocks.
  5111. See also the `org-block' face."
  5112. :type 'boolean
  5113. :version "26.1"
  5114. :package-version '(Org . "8.3")
  5115. :group 'org-appearance
  5116. :group 'org-babel)
  5117. (defcustom org-allow-promoting-top-level-subtree nil
  5118. "When non-nil, allow promoting a top level subtree.
  5119. The leading star of the top level headline will be replaced
  5120. by a #."
  5121. :type 'boolean
  5122. :version "24.1"
  5123. :group 'org-appearance)
  5124. (defun org-fontify-meta-lines-and-blocks (limit)
  5125. (condition-case nil
  5126. (org-fontify-meta-lines-and-blocks-1 limit)
  5127. (error (message "Org mode fontification error in %S at %d"
  5128. (current-buffer)
  5129. (line-number-at-pos)))))
  5130. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5131. "Fontify #+ lines and blocks."
  5132. (let ((case-fold-search t))
  5133. (when (re-search-forward
  5134. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5135. limit t)
  5136. (let ((beg (match-beginning 0))
  5137. (block-start (match-end 0))
  5138. (block-end nil)
  5139. (lang (match-string 7))
  5140. (beg1 (line-beginning-position 2))
  5141. (dc1 (downcase (match-string 2)))
  5142. (dc3 (downcase (match-string 3)))
  5143. end end1 quoting block-type)
  5144. (cond
  5145. ((and (match-end 4) (equal dc3 "+begin"))
  5146. ;; Truly a block
  5147. (setq block-type (downcase (match-string 5))
  5148. quoting (member block-type org-protecting-blocks))
  5149. (when (re-search-forward
  5150. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5151. nil t) ;; on purpose, we look further than LIMIT
  5152. (setq end (min (point-max) (match-end 0))
  5153. end1 (min (point-max) (1- (match-beginning 0))))
  5154. (setq block-end (match-beginning 0))
  5155. (when quoting
  5156. (org-remove-flyspell-overlays-in beg1 end1)
  5157. (remove-text-properties beg end
  5158. '(display t invisible t intangible t)))
  5159. (add-text-properties
  5160. beg end '(font-lock-fontified t font-lock-multiline t))
  5161. (add-text-properties beg beg1 '(face org-meta-line))
  5162. (org-remove-flyspell-overlays-in beg beg1)
  5163. (add-text-properties ; For end_src
  5164. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5165. (org-remove-flyspell-overlays-in end1 end)
  5166. (cond
  5167. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5168. (org-src-font-lock-fontify-block lang block-start block-end)
  5169. (add-text-properties beg1 block-end '(src-block t)))
  5170. (quoting
  5171. (add-text-properties beg1 (min (point-max) (1+ end1))
  5172. (list 'face
  5173. (list :inherit
  5174. (let ((face-name
  5175. (intern (format "org-block-%s" lang))))
  5176. (append (and (facep face-name) (list face-name))
  5177. '(org-block))))))) ; end of source block
  5178. ((not org-fontify-quote-and-verse-blocks))
  5179. ((string= block-type "quote")
  5180. (add-face-text-property
  5181. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5182. ((string= block-type "verse")
  5183. (add-face-text-property
  5184. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5185. (add-text-properties beg beg1 '(face org-block-begin-line))
  5186. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5187. '(face org-block-end-line))
  5188. t))
  5189. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5190. (org-remove-flyspell-overlays-in
  5191. (match-beginning 0)
  5192. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5193. (add-text-properties
  5194. beg (match-end 3)
  5195. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5196. '(font-lock-fontified t invisible t)
  5197. '(font-lock-fontified t face org-document-info-keyword)))
  5198. (add-text-properties
  5199. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5200. (if (string-equal dc1 "+title:")
  5201. '(font-lock-fontified t face org-document-title)
  5202. '(font-lock-fontified t face org-document-info))))
  5203. ((string-prefix-p "+caption" dc1)
  5204. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5205. (remove-text-properties (match-beginning 0) (match-end 0)
  5206. '(display t invisible t intangible t))
  5207. ;; Handle short captions.
  5208. (save-excursion
  5209. (beginning-of-line)
  5210. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5211. (add-text-properties (line-beginning-position) (match-end 1)
  5212. '(font-lock-fontified t face org-meta-line))
  5213. (add-text-properties (match-end 0) (line-end-position)
  5214. '(font-lock-fontified t face org-block))
  5215. t)
  5216. ((member dc3 '(" " ""))
  5217. (org-remove-flyspell-overlays-in beg (match-end 0))
  5218. (add-text-properties
  5219. beg (match-end 0)
  5220. '(font-lock-fontified t face font-lock-comment-face)))
  5221. (t ;; just any other in-buffer setting, but not indented
  5222. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5223. (remove-text-properties (match-beginning 0) (match-end 0)
  5224. '(display t invisible t intangible t))
  5225. (add-text-properties beg (match-end 0)
  5226. '(font-lock-fontified t face org-meta-line))
  5227. t))))))
  5228. (defun org-fontify-drawers (limit)
  5229. "Fontify drawers."
  5230. (when (re-search-forward org-drawer-regexp limit t)
  5231. (add-text-properties
  5232. (match-beginning 0) (match-end 0)
  5233. '(font-lock-fontified t face org-special-keyword))
  5234. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5235. t))
  5236. (defun org-fontify-macros (limit)
  5237. "Fontify macros."
  5238. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5239. (add-text-properties
  5240. (match-beginning 0) (match-end 0)
  5241. '(font-lock-fontified t face org-macro))
  5242. (when org-hide-macro-markers
  5243. (add-text-properties (match-end 2) (match-beginning 2)
  5244. '(invisible t))
  5245. (add-text-properties (match-beginning 1) (match-end 1)
  5246. '(invisible t)))
  5247. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5248. t))
  5249. (defun org-activate-footnote-links (limit)
  5250. "Add text properties for footnotes."
  5251. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5252. (when fn
  5253. (let* ((beg (nth 1 fn))
  5254. (end (nth 2 fn))
  5255. (label (car fn))
  5256. (referencep (/= (line-beginning-position) beg)))
  5257. (when (and referencep (nth 3 fn))
  5258. (save-excursion
  5259. (goto-char beg)
  5260. (search-forward (or label "fn:"))
  5261. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5262. (add-text-properties beg end
  5263. (list 'mouse-face 'highlight
  5264. 'keymap org-mouse-map
  5265. 'help-echo
  5266. (if referencep "Footnote reference"
  5267. "Footnote definition")
  5268. 'font-lock-fontified t
  5269. 'font-lock-multiline t
  5270. 'face 'org-footnote))))))
  5271. (defun org-activate-dates (limit)
  5272. "Add text properties for dates."
  5273. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5274. (not (equal (char-before (match-beginning 0)) 91)))
  5275. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5276. (add-text-properties (match-beginning 0) (match-end 0)
  5277. (list 'mouse-face 'highlight
  5278. 'keymap org-mouse-map))
  5279. (org-rear-nonsticky-at (match-end 0))
  5280. (when org-display-custom-times
  5281. ;; If it's a date range, activate custom time for second date.
  5282. (when (match-end 3)
  5283. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5284. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5285. t))
  5286. (defvar-local org-target-link-regexp nil
  5287. "Regular expression matching radio targets in plain text.")
  5288. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5289. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5290. border border border))
  5291. "Regular expression matching a link target.")
  5292. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5293. "Regular expression matching a radio target.")
  5294. (defconst org-any-target-regexp
  5295. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5296. "Regular expression matching any target.")
  5297. (defun org-activate-target-links (limit)
  5298. "Add text properties for target matches."
  5299. (when org-target-link-regexp
  5300. (let ((case-fold-search t))
  5301. (when (re-search-forward org-target-link-regexp limit t)
  5302. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5303. (add-text-properties (match-beginning 1) (match-end 1)
  5304. (list 'mouse-face 'highlight
  5305. 'keymap org-mouse-map
  5306. 'help-echo "Radio target link"
  5307. 'org-linked-text t))
  5308. (org-rear-nonsticky-at (match-end 1))
  5309. t))))
  5310. (defun org-update-radio-target-regexp ()
  5311. "Find all radio targets in this file and update the regular expression.
  5312. Also refresh fontification if needed."
  5313. (interactive)
  5314. (let ((old-regexp org-target-link-regexp)
  5315. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5316. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5317. (targets
  5318. (org-with-wide-buffer
  5319. (goto-char (point-min))
  5320. (let (rtn)
  5321. (while (re-search-forward org-radio-target-regexp nil t)
  5322. ;; Make sure point is really within the object.
  5323. (backward-char)
  5324. (let ((obj (org-element-context)))
  5325. (when (eq (org-element-type obj) 'radio-target)
  5326. (cl-pushnew (org-element-property :value obj) rtn
  5327. :test #'equal))))
  5328. rtn))))
  5329. (setq org-target-link-regexp
  5330. (and targets
  5331. (concat before-re
  5332. (mapconcat
  5333. (lambda (x)
  5334. (replace-regexp-in-string
  5335. " +" "\\s-+" (regexp-quote x) t t))
  5336. targets
  5337. "\\|")
  5338. after-re)))
  5339. (unless (equal old-regexp org-target-link-regexp)
  5340. ;; Clean-up cache.
  5341. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5342. ((not org-target-link-regexp) old-regexp)
  5343. (t
  5344. (concat before-re
  5345. (mapconcat
  5346. (lambda (re)
  5347. (substring re (length before-re)
  5348. (- (length after-re))))
  5349. (list old-regexp org-target-link-regexp)
  5350. "\\|")
  5351. after-re)))))
  5352. (org-with-wide-buffer
  5353. (goto-char (point-min))
  5354. (while (re-search-forward regexp nil t)
  5355. (org-element-cache-refresh (match-beginning 1)))))
  5356. ;; Re fontify buffer.
  5357. (when (memq 'radio org-highlight-links)
  5358. (org-restart-font-lock)))))
  5359. (defvar org-latex-and-related-regexp nil
  5360. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5361. (defun org-compute-latex-and-related-regexp ()
  5362. "Compute regular expression for LaTeX, entities and sub/superscript.
  5363. Result depends on variable `org-highlight-latex-and-related'."
  5364. (setq-local
  5365. org-latex-and-related-regexp
  5366. (let* ((re-sub
  5367. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5368. ((eq org-use-sub-superscripts '{})
  5369. (list org-match-substring-with-braces-regexp))
  5370. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5371. (re-latex
  5372. (when (memq 'latex org-highlight-latex-and-related)
  5373. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5374. (delq nil
  5375. (mapcar (lambda (x)
  5376. (and (member (car x) matchers) (nth 1 x)))
  5377. org-latex-regexps)))))
  5378. (re-entities
  5379. (when (memq 'entities org-highlight-latex-and-related)
  5380. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5381. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5382. (defun org-do-latex-and-related (limit)
  5383. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5384. LIMIT bounds the search for syntax to highlight. Stop at first
  5385. highlighted object, if any. Return t if some highlighting was
  5386. done, nil otherwise."
  5387. (when (org-string-nw-p org-latex-and-related-regexp)
  5388. (catch 'found
  5389. (while (re-search-forward org-latex-and-related-regexp limit t)
  5390. (unless
  5391. (cl-some
  5392. (lambda (f)
  5393. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5394. (save-excursion
  5395. (goto-char (1+ (match-beginning 0)))
  5396. (face-at-point nil t)))
  5397. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5398. '(?_ ?^))
  5399. 1
  5400. 0)))
  5401. (font-lock-prepend-text-property
  5402. (+ offset (match-beginning 0)) (match-end 0)
  5403. 'face 'org-latex-and-related)
  5404. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5405. '(font-lock-multiline t)))
  5406. (throw 'found t)))
  5407. nil)))
  5408. (defun org-restart-font-lock ()
  5409. "Restart `font-lock-mode', to force refontification."
  5410. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5411. (font-lock-mode -1)
  5412. (font-lock-mode 1)))
  5413. (defun org-activate-tags (limit)
  5414. (when (re-search-forward
  5415. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5416. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5417. (add-text-properties (match-beginning 1) (match-end 1)
  5418. (list 'mouse-face 'highlight
  5419. 'keymap org-mouse-map))
  5420. (org-rear-nonsticky-at (match-end 1))
  5421. t))
  5422. (defun org-outline-level ()
  5423. "Compute the outline level of the heading at point.
  5424. If this is called at a normal headline, the level is the number
  5425. of stars. Use `org-reduced-level' to remove the effect of
  5426. `org-odd-levels'. Unlike to `org-current-level', this function
  5427. takes into consideration inlinetasks."
  5428. (org-with-wide-buffer
  5429. (end-of-line)
  5430. (if (re-search-backward org-outline-regexp-bol nil t)
  5431. (1- (- (match-end 0) (match-beginning 0)))
  5432. 0)))
  5433. (defvar org-font-lock-keywords nil)
  5434. (defsubst org-re-property (property &optional literal allow-null value)
  5435. "Return a regexp matching a PROPERTY line.
  5436. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5437. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5438. non-nil, match properties even without a value.
  5439. Match group 3 is set to the value when it exists. If there is no
  5440. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5441. With optional argument VALUE, match only property lines with
  5442. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5443. unless LITERAL is non-nil."
  5444. (concat
  5445. "^\\(?4:[ \t]*\\)"
  5446. (format "\\(?1::\\(?2:%s\\):\\)"
  5447. (if literal property (regexp-quote property)))
  5448. (cond (value
  5449. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5450. (if literal value (regexp-quote value))))
  5451. (allow-null
  5452. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5453. (t
  5454. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5455. (defconst org-property-re
  5456. (org-re-property "\\S-+" 'literal t)
  5457. "Regular expression matching a property line.
  5458. There are four matching groups:
  5459. 1: :PROPKEY: including the leading and trailing colon,
  5460. 2: PROPKEY without the leading and trailing colon,
  5461. 3: PROPVAL without leading or trailing spaces,
  5462. 4: the indentation of the current line,
  5463. 5: trailing whitespace.")
  5464. (defvar org-font-lock-hook nil
  5465. "Functions to be called for special font lock stuff.")
  5466. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5467. (defvar org-font-lock-set-keywords-hook nil
  5468. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5469. This is called after `org-font-lock-extra-keywords' is defined, but before
  5470. it is installed to be used by font lock. This can be useful if something
  5471. needs to be inserted at a specific position in the font-lock sequence.")
  5472. (defun org-font-lock-hook (limit)
  5473. "Run `org-font-lock-hook' within LIMIT."
  5474. (run-hook-with-args 'org-font-lock-hook limit))
  5475. (defun org-set-font-lock-defaults ()
  5476. "Set font lock defaults for the current buffer."
  5477. (let* ((em org-fontify-emphasized-text)
  5478. (lk org-highlight-links)
  5479. (org-font-lock-extra-keywords
  5480. (list
  5481. ;; Call the hook
  5482. '(org-font-lock-hook)
  5483. ;; Headlines
  5484. `(,(if org-fontify-whole-heading-line
  5485. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5486. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5487. (1 (org-get-level-face 1))
  5488. (2 (org-get-level-face 2))
  5489. (3 (org-get-level-face 3)))
  5490. ;; Table lines
  5491. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5492. (1 'org-table t))
  5493. ;; Table internals
  5494. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5495. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5496. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5497. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5498. ;; Drawers
  5499. '(org-fontify-drawers)
  5500. ;; Properties
  5501. (list org-property-re
  5502. '(1 'org-special-keyword t)
  5503. '(3 'org-property-value t))
  5504. ;; Link related fontification.
  5505. '(org-activate-links)
  5506. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5507. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5508. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5509. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5510. ;; Targets.
  5511. (list org-any-target-regexp '(0 'org-target t))
  5512. ;; Diary sexps.
  5513. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5514. ;; Macro
  5515. '(org-fontify-macros)
  5516. ;; TODO keyword
  5517. (list (format org-heading-keyword-regexp-format
  5518. org-todo-regexp)
  5519. '(2 (org-get-todo-face 2) t))
  5520. ;; DONE
  5521. (if org-fontify-done-headline
  5522. (list (format org-heading-keyword-regexp-format
  5523. (concat
  5524. "\\(?:"
  5525. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5526. "\\)"))
  5527. '(2 'org-headline-done t))
  5528. nil)
  5529. ;; Priorities
  5530. '(org-font-lock-add-priority-faces)
  5531. ;; Tags
  5532. '(org-font-lock-add-tag-faces)
  5533. ;; Tags groups
  5534. (when (and org-group-tags org-tag-groups-alist)
  5535. (list (concat org-outline-regexp-bol ".+\\(:"
  5536. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5537. ":\\).*$")
  5538. '(1 'org-tag-group prepend)))
  5539. ;; Special keywords
  5540. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5541. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5542. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5543. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5544. ;; Emphasis
  5545. (when em '(org-do-emphasis-faces))
  5546. ;; Checkboxes
  5547. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5548. 1 'org-checkbox prepend)
  5549. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5550. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5551. (0 (org-get-checkbox-statistics-face) t)))
  5552. ;; Description list items
  5553. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5554. 1 'org-list-dt prepend)
  5555. ;; ARCHIVEd headings
  5556. (list (concat
  5557. org-outline-regexp-bol
  5558. "\\(.*:" org-archive-tag ":.*\\)")
  5559. '(1 'org-archived prepend))
  5560. ;; Specials
  5561. '(org-do-latex-and-related)
  5562. '(org-fontify-entities)
  5563. '(org-raise-scripts)
  5564. ;; Code
  5565. '(org-activate-code (1 'org-code t))
  5566. ;; COMMENT
  5567. (list (format
  5568. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5569. org-todo-regexp
  5570. org-comment-string)
  5571. '(9 'org-special-keyword t))
  5572. ;; Blocks and meta lines
  5573. '(org-fontify-meta-lines-and-blocks))))
  5574. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5575. (run-hooks 'org-font-lock-set-keywords-hook)
  5576. ;; Now set the full font-lock-keywords
  5577. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5578. (setq-local font-lock-defaults
  5579. '(org-font-lock-keywords t nil nil backward-paragraph))
  5580. (kill-local-variable 'font-lock-keywords)
  5581. nil))
  5582. (defun org-toggle-pretty-entities ()
  5583. "Toggle the composition display of entities as UTF8 characters."
  5584. (interactive)
  5585. (setq-local org-pretty-entities (not org-pretty-entities))
  5586. (org-restart-font-lock)
  5587. (if org-pretty-entities
  5588. (message "Entities are now displayed as UTF8 characters")
  5589. (save-restriction
  5590. (widen)
  5591. (decompose-region (point-min) (point-max))
  5592. (message "Entities are now displayed as plain text"))))
  5593. (defvar-local org-custom-properties-overlays nil
  5594. "List of overlays used for custom properties.")
  5595. (defun org-toggle-custom-properties-visibility ()
  5596. "Display or hide properties in `org-custom-properties'."
  5597. (interactive)
  5598. (if org-custom-properties-overlays
  5599. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5600. (setq org-custom-properties-overlays nil))
  5601. (when org-custom-properties
  5602. (org-with-wide-buffer
  5603. (goto-char (point-min))
  5604. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5605. (while (re-search-forward regexp nil t)
  5606. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5607. (when (and end (< (point) end))
  5608. ;; Hide first custom property in current drawer.
  5609. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5610. (overlay-put o 'invisible t)
  5611. (overlay-put o 'org-custom-property t)
  5612. (push o org-custom-properties-overlays))
  5613. ;; Hide additional custom properties in the same drawer.
  5614. (while (re-search-forward regexp end t)
  5615. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5616. (overlay-put o 'invisible t)
  5617. (overlay-put o 'org-custom-property t)
  5618. (push o org-custom-properties-overlays)))))
  5619. ;; Each entry is limited to a single property drawer.
  5620. (outline-next-heading)))))))
  5621. (defun org-fontify-entities (limit)
  5622. "Find an entity to fontify."
  5623. (let (ee)
  5624. (when org-pretty-entities
  5625. (catch 'match
  5626. ;; "\_ "-family is left out on purpose. Only the first one,
  5627. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5628. ;; confusing when adding a second white space character.
  5629. (while (re-search-forward
  5630. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5631. limit t)
  5632. (when (and (not (org-at-comment-p))
  5633. (setq ee (org-entity-get (match-string 1)))
  5634. (= (length (nth 6 ee)) 1))
  5635. (let* ((end (if (equal (match-string 2) "{}")
  5636. (match-end 2)
  5637. (match-end 1))))
  5638. (add-text-properties
  5639. (match-beginning 0) end
  5640. (list 'font-lock-fontified t))
  5641. (compose-region (match-beginning 0) end
  5642. (nth 6 ee) nil)
  5643. (backward-char 1)
  5644. (throw 'match t))))
  5645. nil))))
  5646. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5647. "Fontify string S like in Org mode."
  5648. (with-temp-buffer
  5649. (insert s)
  5650. (let ((org-odd-levels-only odd-levels))
  5651. (org-mode)
  5652. (org-font-lock-ensure)
  5653. (buffer-string))))
  5654. (defvar org-m nil)
  5655. (defvar org-l nil)
  5656. (defvar org-f nil)
  5657. (defun org-get-level-face (n)
  5658. "Get the right face for match N in font-lock matching of headlines."
  5659. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5660. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5661. (if org-cycle-level-faces
  5662. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5663. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5664. (cond
  5665. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5666. ((eq n 2) org-f)
  5667. (t (unless org-level-color-stars-only org-f))))
  5668. (defun org-face-from-face-or-color (context inherit face-or-color)
  5669. "Create a face list that inherits INHERIT, but sets the foreground color.
  5670. When FACE-OR-COLOR is not a string, just return it."
  5671. (if (stringp face-or-color)
  5672. (list :inherit inherit
  5673. (cdr (assoc context org-faces-easy-properties))
  5674. face-or-color)
  5675. face-or-color))
  5676. (defun org-get-todo-face (kwd)
  5677. "Get the right face for a TODO keyword KWD.
  5678. If KWD is a number, get the corresponding match group."
  5679. (when (numberp kwd) (setq kwd (match-string kwd)))
  5680. (or (org-face-from-face-or-color
  5681. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5682. (and (member kwd org-done-keywords) 'org-done)
  5683. 'org-todo))
  5684. (defun org-get-priority-face (priority)
  5685. "Get the right face for PRIORITY.
  5686. PRIORITY is a character."
  5687. (or (org-face-from-face-or-color
  5688. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5689. 'org-priority))
  5690. (defun org-get-tag-face (tag)
  5691. "Get the right face for TAG.
  5692. If TAG is a number, get the corresponding match group."
  5693. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5694. (or (org-face-from-face-or-color
  5695. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5696. 'org-tag)))
  5697. (defun org-font-lock-add-priority-faces (limit)
  5698. "Add the special priority faces."
  5699. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5700. (add-text-properties
  5701. (match-beginning 1) (match-end 1)
  5702. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5703. 'font-lock-fontified t))))
  5704. (defun org-font-lock-add-tag-faces (limit)
  5705. "Add the special tag faces."
  5706. (when (and org-tag-faces org-tags-special-faces-re)
  5707. (while (re-search-forward org-tags-special-faces-re limit t)
  5708. (add-text-properties (match-beginning 1) (match-end 1)
  5709. (list 'face (org-get-tag-face 1)
  5710. 'font-lock-fontified t))
  5711. (backward-char 1))))
  5712. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5713. "Remove fontification and activation overlays from links."
  5714. (font-lock-default-unfontify-region beg end)
  5715. (let* ((buffer-undo-list t)
  5716. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5717. (inhibit-modification-hooks t)
  5718. deactivate-mark buffer-file-name buffer-file-truename)
  5719. (decompose-region beg end)
  5720. (remove-text-properties beg end
  5721. '(mouse-face t keymap t org-linked-text t
  5722. invisible t intangible t
  5723. org-emphasis t))
  5724. (org-remove-font-lock-display-properties beg end)))
  5725. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5726. ((raise 0.3) (height 0.7))
  5727. ((raise -0.5))
  5728. ((raise 0.5)))
  5729. "Display properties for showing superscripts and subscripts.")
  5730. (defun org-remove-font-lock-display-properties (beg end)
  5731. "Remove specific display properties that have been added by font lock.
  5732. The will remove the raise properties that are used to show superscripts
  5733. and subscripts."
  5734. (let (next prop)
  5735. (while (< beg end)
  5736. (setq next (next-single-property-change beg 'display nil end)
  5737. prop (get-text-property beg 'display))
  5738. (when (member prop org-script-display)
  5739. (put-text-property beg next 'display nil))
  5740. (setq beg next))))
  5741. (defun org-raise-scripts (limit)
  5742. "Add raise properties to sub/superscripts."
  5743. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5744. (re-search-forward
  5745. (if (eq org-use-sub-superscripts t)
  5746. org-match-substring-regexp
  5747. org-match-substring-with-braces-regexp)
  5748. limit t))
  5749. (let* ((pos (point)) table-p comment-p
  5750. (mpos (match-beginning 3))
  5751. (emph-p (get-text-property mpos 'org-emphasis))
  5752. (link-p (get-text-property mpos 'mouse-face))
  5753. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5754. (goto-char (point-at-bol))
  5755. (setq table-p (looking-at-p org-table-dataline-regexp)
  5756. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5757. (goto-char pos)
  5758. ;; Handle a_b^c
  5759. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5760. (unless (or comment-p emph-p link-p keyw-p)
  5761. (put-text-property (match-beginning 3) (match-end 0)
  5762. 'display
  5763. (if (equal (char-after (match-beginning 2)) ?^)
  5764. (nth (if table-p 3 1) org-script-display)
  5765. (nth (if table-p 2 0) org-script-display)))
  5766. (add-text-properties (match-beginning 2) (match-end 2)
  5767. (list 'invisible t))
  5768. (when (and (eq (char-after (match-beginning 3)) ?{)
  5769. (eq (char-before (match-end 3)) ?}))
  5770. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5771. (list 'invisible t))
  5772. (add-text-properties (1- (match-end 3)) (match-end 3)
  5773. (list 'invisible t))))
  5774. t)))
  5775. (defun org-remove-empty-overlays-at (pos)
  5776. "Remove outline overlays that do not contain non-white stuff."
  5777. (dolist (o (overlays-at pos))
  5778. (and (eq 'outline (overlay-get o 'invisible))
  5779. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5780. (overlay-end o))))
  5781. (delete-overlay o))))
  5782. (defun org-show-empty-lines-in-parent ()
  5783. "Move to the parent and re-show empty lines before visible headlines."
  5784. (save-excursion
  5785. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5786. (org-cycle-show-empty-lines context))))
  5787. (defun org-files-list ()
  5788. "Return `org-agenda-files' list, plus all open Org files.
  5789. This is useful for operations that need to scan all of a user's
  5790. open and agenda-wise Org files."
  5791. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5792. (dolist (buf (buffer-list))
  5793. (with-current-buffer buf
  5794. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5795. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5796. :test #'equal))))
  5797. files))
  5798. (defsubst org-entry-beginning-position ()
  5799. "Return the beginning position of the current entry."
  5800. (save-excursion (org-back-to-heading t) (point)))
  5801. (defsubst org-entry-end-position ()
  5802. "Return the end position of the current entry."
  5803. (save-excursion (outline-next-heading) (point)))
  5804. (defun org-subtree-end-visible-p ()
  5805. "Is the end of the current subtree visible?"
  5806. (pos-visible-in-window-p
  5807. (save-excursion (org-end-of-subtree t) (point))))
  5808. (defun org-first-headline-recenter ()
  5809. "Move cursor to the first headline and recenter the headline."
  5810. (let ((window (get-buffer-window)))
  5811. (when window
  5812. (goto-char (point-min))
  5813. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5814. (set-window-start window (line-beginning-position))))))
  5815. ;;; Visibility (headlines, blocks, drawers)
  5816. (defun org-flag-region (from to flag spec)
  5817. "Hide or show lines from FROM to TO, according to FLAG.
  5818. SPEC is the invisibility spec, as a symbol."
  5819. (remove-overlays from to 'invisible spec)
  5820. ;; Use `front-advance' since text right before to the beginning of
  5821. ;; the overlay belongs to the visible line than to the contents.
  5822. (when flag
  5823. (let ((o (make-overlay from to nil 'front-advance)))
  5824. (overlay-put o 'evaporate t)
  5825. (overlay-put o 'invisible spec)
  5826. (overlay-put o 'isearch-open-invisible #'delete-overlay))))
  5827. ;;;; Headlines visibility
  5828. (defun org-show-entry ()
  5829. "Show the body directly following this heading.
  5830. Show the heading too, if it is currently invisible."
  5831. (interactive)
  5832. (save-excursion
  5833. (ignore-errors
  5834. (org-back-to-heading t)
  5835. (org-flag-region
  5836. (line-end-position 0)
  5837. (save-excursion
  5838. (if (re-search-forward
  5839. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5840. (match-beginning 1)
  5841. (point-max)))
  5842. nil
  5843. 'outline))))
  5844. (defun org-show-children (&optional level)
  5845. "Show all direct subheadings of this heading.
  5846. Prefix arg LEVEL is how many levels below the current level
  5847. should be shown. Default is enough to cause the following
  5848. heading to appear."
  5849. (interactive "p")
  5850. (save-excursion
  5851. (org-back-to-heading t)
  5852. (let* ((current-level (funcall outline-level))
  5853. (max-level (org-get-valid-level
  5854. current-level
  5855. (if level (prefix-numeric-value level) 1)))
  5856. (end (save-excursion (org-end-of-subtree t t)))
  5857. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5858. (past-first-child nil)
  5859. ;; Make sure to skip inlinetasks.
  5860. (re (format regexp-fmt
  5861. current-level
  5862. (cond
  5863. ((not (featurep 'org-inlinetask)) "")
  5864. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5865. 3))
  5866. (t (1- org-inlinetask-min-level))))))
  5867. ;; Display parent heading.
  5868. (org-flag-heading nil)
  5869. (forward-line)
  5870. ;; Display children. First child may be deeper than expected
  5871. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5872. ;; MAX-LEVEL accordingly.
  5873. (while (re-search-forward re end t)
  5874. (unless past-first-child
  5875. (setq re (format regexp-fmt
  5876. current-level
  5877. (max (funcall outline-level) max-level)))
  5878. (setq past-first-child t))
  5879. (org-flag-heading nil)))))
  5880. (defun org-show-subtree ()
  5881. "Show everything after this heading at deeper levels."
  5882. (interactive)
  5883. (org-flag-region
  5884. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5885. ;;;; Blocks visibility
  5886. (defun org-hide-block-toggle-maybe ()
  5887. "Toggle visibility of block at point.
  5888. Unlike to `org-hide-block-toggle', this function does not throw
  5889. an error. Return a non-nil value when toggling is successful."
  5890. (interactive)
  5891. (ignore-errors (org-hide-block-toggle)))
  5892. (defun org-hide-block-toggle (&optional force)
  5893. "Toggle the visibility of the current block.
  5894. When optional argument FORCE is `off', make block visible. If it
  5895. is non-nil, hide it unconditionally. Throw an error when not at
  5896. a block. Return a non-nil value when toggling is successful."
  5897. (interactive)
  5898. (let ((element (org-element-at-point)))
  5899. (unless (memq (org-element-type element)
  5900. '(center-block comment-block dynamic-block example-block
  5901. export-block quote-block special-block
  5902. src-block verse-block))
  5903. (user-error "Not at a block"))
  5904. (let* ((post (org-element-property :post-affiliated element))
  5905. (start (save-excursion
  5906. (goto-char post)
  5907. (line-end-position)))
  5908. (end (save-excursion
  5909. (goto-char (org-element-property :end element))
  5910. (skip-chars-backward " \t\n")
  5911. (line-end-position))))
  5912. ;; Do nothing when not before or at the block opening line or at
  5913. ;; the block closing line.
  5914. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5915. (cond ((eq force 'off)
  5916. (org-flag-region start end nil 'org-hide-block))
  5917. (force
  5918. (org-flag-region start end t 'org-hide-block))
  5919. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5920. (org-flag-region start end nil 'org-hide-block))
  5921. (t
  5922. (org-flag-region start end t 'org-hide-block)))
  5923. ;; When the block is hidden away, make sure point is left in
  5924. ;; a visible part of the buffer.
  5925. (when (invisible-p (max (1- (point)) (point-min)))
  5926. (goto-char post))
  5927. ;; Signal success.
  5928. t))))
  5929. (defun org-hide-block-toggle-all ()
  5930. "Toggle the visibility of all blocks in the current buffer."
  5931. (org-block-map 'org-hide-block-toggle))
  5932. (defun org-hide-block-all ()
  5933. "Fold all blocks in the current buffer."
  5934. (interactive)
  5935. (org-show-all '(blocks))
  5936. (org-block-map 'org-hide-block-toggle-maybe))
  5937. ;;;; Drawers visibility
  5938. (defun org-cycle-hide-drawers (state &optional exceptions)
  5939. "Re-hide all drawers after a visibility state change.
  5940. STATE should be one of the symbols listed in the docstring of
  5941. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5942. a list of strings specifying which drawers should not be hidden."
  5943. (when (and (derived-mode-p 'org-mode)
  5944. (not (memq state '(overview folded contents))))
  5945. (save-excursion
  5946. (let* ((globalp (eq state 'all))
  5947. (beg (if globalp (point-min) (point)))
  5948. (end (if globalp (point-max)
  5949. (if (eq state 'children)
  5950. (save-excursion (outline-next-heading) (point))
  5951. (org-end-of-subtree t)))))
  5952. (goto-char beg)
  5953. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5954. (unless (member-ignore-case (match-string 1) exceptions)
  5955. (let ((drawer (org-element-at-point)))
  5956. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5957. (org-flag-drawer t drawer)
  5958. ;; Make sure to skip drawer entirely or we might flag
  5959. ;; it another time when matching its ending line with
  5960. ;; `org-drawer-regexp'.
  5961. (goto-char (org-element-property :end drawer))))))))))
  5962. (defun org-flag-drawer (flag &optional element)
  5963. "When FLAG is non-nil, hide the drawer we are at.
  5964. Otherwise make it visible. When optional argument ELEMENT is
  5965. a parsed drawer, as returned by `org-element-at-point', hide or
  5966. show that drawer instead."
  5967. (let ((drawer (or element
  5968. (and (save-excursion
  5969. (beginning-of-line)
  5970. (looking-at-p org-drawer-regexp))
  5971. (org-element-at-point)))))
  5972. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5973. (let ((post (org-element-property :post-affiliated drawer)))
  5974. (org-flag-region
  5975. (save-excursion (goto-char post) (line-end-position))
  5976. (save-excursion (goto-char (org-element-property :end drawer))
  5977. (skip-chars-backward " \t\n")
  5978. (line-end-position))
  5979. flag 'org-hide-drawer)
  5980. ;; When the drawer is hidden away, make sure point lies in
  5981. ;; a visible part of the buffer.
  5982. (when (invisible-p (max (1- (point)) (point-min)))
  5983. (goto-char post))))))
  5984. ;;;; Visibility cycling
  5985. (defvar-local org-cycle-global-status nil)
  5986. (put 'org-cycle-global-status 'org-state t)
  5987. (defvar-local org-cycle-subtree-status nil)
  5988. (put 'org-cycle-subtree-status 'org-state t)
  5989. (defun org-show-all (&optional types)
  5990. "Show all contents in the visible part of the buffer.
  5991. By default, the function expands headings, blocks and drawers.
  5992. When optional argument TYPE is a list of symbols among `blocks',
  5993. `drawers' and `headings', to only expand one specific type."
  5994. (dolist (type (or types '(blocks drawers headings)))
  5995. (org-flag-region (point-min) (point-max) nil
  5996. (pcase type
  5997. (`blocks 'org-hide-block)
  5998. (`drawers 'org-hide-drawer)
  5999. (`headings 'outline)
  6000. (_ (error "Invalid type: %S" type))))))
  6001. ;;;###autoload
  6002. (defun org-cycle (&optional arg)
  6003. "TAB-action and visibility cycling for Org mode.
  6004. This is the command invoked in Org mode by the `TAB' key. Its main
  6005. purpose is outline visibility cycling, but it also invokes other actions
  6006. in special contexts.
  6007. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6008. the entire
  6009. buffer through 3 states (global cycling)
  6010. 1. OVERVIEW: Show only top-level headlines.
  6011. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6012. 3. SHOW ALL: Show everything.
  6013. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6014. switch to the startup visibility,
  6015. determined by the variable `org-startup-folded', and by any VISIBILITY
  6016. properties in the buffer.
  6017. With a `\\[universal-argument] \\[universal-argument] \
  6018. \\[universal-argument]' prefix argument, show the entire buffer, including
  6019. any drawers.
  6020. When inside a table, re-align the table and move to the next field.
  6021. When point is at the beginning of a headline, rotate the subtree started
  6022. by this line through 3 different states (local cycling)
  6023. 1. FOLDED: Only the main headline is shown.
  6024. 2. CHILDREN: The main headline and the direct children are shown.
  6025. From this state, you can move to one of the children
  6026. and zoom in further.
  6027. 3. SUBTREE: Show the entire subtree, including body text.
  6028. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6029. When point is at the beginning of an empty headline and the variable
  6030. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6031. of the headline by demoting and promoting it to likely levels. This
  6032. speeds up creation document structure by pressing `TAB' once or several
  6033. times right after creating a new headline.
  6034. When there is a numeric prefix, go up to a heading with level ARG, do
  6035. a `show-subtree' and return to the previous cursor position. If ARG
  6036. is negative, go up that many levels.
  6037. When point is not at the beginning of a headline, execute the global
  6038. binding for `TAB', which is re-indenting the line. See the option
  6039. `org-cycle-emulate-tab' for details.
  6040. As a special case, if point is at the beginning of the buffer and there is
  6041. no headline in line 1, this function will act as if called with prefix arg
  6042. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6043. prefix arg, but only
  6044. if the variable `org-cycle-global-at-bob' is t."
  6045. (interactive "P")
  6046. (org-load-modules-maybe)
  6047. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6048. (and org-cycle-level-after-item/entry-creation
  6049. (or (org-cycle-level)
  6050. (org-cycle-item-indentation))))
  6051. (let* ((limit-level
  6052. (or org-cycle-max-level
  6053. (and (boundp 'org-inlinetask-min-level)
  6054. org-inlinetask-min-level
  6055. (1- org-inlinetask-min-level))))
  6056. (nstars (and limit-level
  6057. (if org-odd-levels-only
  6058. (and limit-level (1- (* limit-level 2)))
  6059. limit-level)))
  6060. (org-outline-regexp
  6061. (if (not (derived-mode-p 'org-mode))
  6062. outline-regexp
  6063. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6064. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6065. (not (looking-at org-outline-regexp))))
  6066. (org-cycle-hook
  6067. (if bob-special
  6068. (delq 'org-optimize-window-after-visibility-change
  6069. (copy-sequence org-cycle-hook))
  6070. org-cycle-hook))
  6071. (pos (point)))
  6072. (cond
  6073. ((equal arg '(16))
  6074. (setq last-command 'dummy)
  6075. (org-set-startup-visibility)
  6076. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6077. ((equal arg '(64))
  6078. (org-show-all)
  6079. (org-unlogged-message "Entire buffer visible, including drawers"))
  6080. ((equal arg '(4)) (org-cycle-internal-global))
  6081. ;; Try hiding block at point.
  6082. ((org-hide-block-toggle-maybe))
  6083. ;; Try cdlatex TAB completion
  6084. ((org-try-cdlatex-tab))
  6085. ;; Table: enter it or move to the next field.
  6086. ((org-at-table-p 'any)
  6087. (if (org-at-table.el-p)
  6088. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6089. Use `\\[org-edit-special]' to edit table.el tables"))
  6090. (if arg (org-table-edit-field t)
  6091. (org-table-justify-field-maybe)
  6092. (call-interactively 'org-table-next-field))))
  6093. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6094. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6095. (bob-special (org-cycle-internal-global))
  6096. ;; Drawers: delegate to `org-flag-drawer'.
  6097. ((save-excursion
  6098. (beginning-of-line 1)
  6099. (looking-at org-drawer-regexp))
  6100. (org-flag-drawer ; toggle block visibility
  6101. (not (get-char-property (match-end 0) 'invisible))))
  6102. ;; Show-subtree, ARG levels up from here.
  6103. ((integerp arg)
  6104. (save-excursion
  6105. (org-back-to-heading)
  6106. (outline-up-heading (if (< arg 0) (- arg)
  6107. (- (funcall outline-level) arg)))
  6108. (org-show-subtree)))
  6109. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6110. ((and (featurep 'org-inlinetask)
  6111. (org-inlinetask-at-task-p)
  6112. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6113. (org-inlinetask-toggle-visibility))
  6114. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6115. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6116. (save-excursion (move-beginning-of-line 1)
  6117. (looking-at org-outline-regexp)))
  6118. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6119. (org-cycle-internal-local))
  6120. ;; From there: TAB emulation and template completion.
  6121. (buffer-read-only (org-back-to-heading))
  6122. ((run-hook-with-args-until-success
  6123. 'org-tab-after-check-for-cycling-hook))
  6124. ((run-hook-with-args-until-success
  6125. 'org-tab-before-tab-emulation-hook))
  6126. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6127. (or (not (bolp))
  6128. (not (looking-at org-outline-regexp))))
  6129. (call-interactively (global-key-binding "\t")))
  6130. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6131. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6132. (or (and (eq org-cycle-emulate-tab 'white)
  6133. (= (match-end 0) (point-at-eol)))
  6134. (and (eq org-cycle-emulate-tab 'whitestart)
  6135. (>= (match-end 0) pos))))
  6136. t
  6137. (eq org-cycle-emulate-tab t))
  6138. (call-interactively (global-key-binding "\t")))
  6139. (t (save-excursion
  6140. (org-back-to-heading)
  6141. (org-cycle)))))))
  6142. (defun org-cycle-internal-global ()
  6143. "Do the global cycling action."
  6144. ;; Hack to avoid display of messages for .org attachments in Gnus
  6145. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6146. (cond
  6147. ((and (eq last-command this-command)
  6148. (eq org-cycle-global-status 'overview))
  6149. ;; We just created the overview - now do table of contents
  6150. ;; This can be slow in very large buffers, so indicate action
  6151. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6152. (unless ga (org-unlogged-message "CONTENTS..."))
  6153. (org-content)
  6154. (unless ga (org-unlogged-message "CONTENTS...done"))
  6155. (setq org-cycle-global-status 'contents)
  6156. (run-hook-with-args 'org-cycle-hook 'contents))
  6157. ((and (eq last-command this-command)
  6158. (eq org-cycle-global-status 'contents))
  6159. ;; We just showed the table of contents - now show everything
  6160. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6161. (org-show-all '(headings blocks))
  6162. (unless ga (org-unlogged-message "SHOW ALL"))
  6163. (setq org-cycle-global-status 'all)
  6164. (run-hook-with-args 'org-cycle-hook 'all))
  6165. (t
  6166. ;; Default action: go to overview
  6167. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6168. (org-overview)
  6169. (unless ga (org-unlogged-message "OVERVIEW"))
  6170. (setq org-cycle-global-status 'overview)
  6171. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6172. (defvar org-called-with-limited-levels nil
  6173. "Non-nil when `org-with-limited-levels' is currently active.")
  6174. (defun org-cycle-internal-local ()
  6175. "Do the local cycling action."
  6176. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6177. ;; First, determine end of headline (EOH), end of subtree or item
  6178. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6179. (save-excursion
  6180. (if (org-at-item-p)
  6181. (progn
  6182. (beginning-of-line)
  6183. (setq struct (org-list-struct))
  6184. (setq eoh (point-at-eol))
  6185. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6186. (setq has-children (org-list-has-child-p (point) struct)))
  6187. (org-back-to-heading)
  6188. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6189. (setq eos (save-excursion (org-end-of-subtree t t)
  6190. (when (bolp) (backward-char)) (point)))
  6191. (setq has-children
  6192. (or (save-excursion
  6193. (let ((level (funcall outline-level)))
  6194. (outline-next-heading)
  6195. (and (org-at-heading-p t)
  6196. (> (funcall outline-level) level))))
  6197. (save-excursion
  6198. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6199. ;; Determine end invisible part of buffer (EOL)
  6200. (beginning-of-line 2)
  6201. (while (and (not (eobp)) ;This is like `next-line'.
  6202. (get-char-property (1- (point)) 'invisible))
  6203. (goto-char (next-single-char-property-change (point) 'invisible))
  6204. (and (eolp) (beginning-of-line 2)))
  6205. (setq eol (point)))
  6206. ;; Find out what to do next and set `this-command'
  6207. (cond
  6208. ((= eos eoh)
  6209. ;; Nothing is hidden behind this heading
  6210. (unless (org-before-first-heading-p)
  6211. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6212. (org-unlogged-message "EMPTY ENTRY")
  6213. (setq org-cycle-subtree-status nil)
  6214. (save-excursion
  6215. (goto-char eos)
  6216. (outline-next-heading)
  6217. (when (org-invisible-p) (org-flag-heading nil))))
  6218. ((and (or (>= eol eos)
  6219. (not (string-match "\\S-" (buffer-substring eol eos))))
  6220. (or has-children
  6221. (not (setq children-skipped
  6222. org-cycle-skip-children-state-if-no-children))))
  6223. ;; Entire subtree is hidden in one line: children view
  6224. (unless (org-before-first-heading-p)
  6225. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6226. (if (org-at-item-p)
  6227. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6228. (org-show-entry)
  6229. (org-with-limited-levels (org-show-children))
  6230. (org-show-set-visibility 'canonical)
  6231. ;; Fold every list in subtree to top-level items.
  6232. (when (eq org-cycle-include-plain-lists 'integrate)
  6233. (save-excursion
  6234. (org-back-to-heading)
  6235. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6236. (beginning-of-line 1)
  6237. (let* ((struct (org-list-struct))
  6238. (prevs (org-list-prevs-alist struct))
  6239. (end (org-list-get-bottom-point struct)))
  6240. (dolist (e (org-list-get-all-items (point) struct prevs))
  6241. (org-list-set-item-visibility e struct 'folded))
  6242. (goto-char (if (< end eos) end eos)))))))
  6243. (org-unlogged-message "CHILDREN")
  6244. (save-excursion
  6245. (goto-char eos)
  6246. (outline-next-heading)
  6247. (when (org-invisible-p) (org-flag-heading nil)))
  6248. (setq org-cycle-subtree-status 'children)
  6249. (unless (org-before-first-heading-p)
  6250. (run-hook-with-args 'org-cycle-hook 'children)))
  6251. ((or children-skipped
  6252. (and (eq last-command this-command)
  6253. (eq org-cycle-subtree-status 'children)))
  6254. ;; We just showed the children, or no children are there,
  6255. ;; now show everything.
  6256. (unless (org-before-first-heading-p)
  6257. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6258. (org-flag-region eoh eos nil 'outline)
  6259. (org-unlogged-message
  6260. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6261. (setq org-cycle-subtree-status 'subtree)
  6262. (unless (org-before-first-heading-p)
  6263. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6264. (t
  6265. ;; Default action: hide the subtree.
  6266. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6267. (org-flag-region eoh eos t 'outline)
  6268. (org-unlogged-message "FOLDED")
  6269. (setq org-cycle-subtree-status 'folded)
  6270. (unless (org-before-first-heading-p)
  6271. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6272. ;;;###autoload
  6273. (defun org-global-cycle (&optional arg)
  6274. "Cycle the global visibility. For details see `org-cycle'.
  6275. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6276. With a numeric prefix, show all headlines up to that level."
  6277. (interactive "P")
  6278. (let ((org-cycle-include-plain-lists
  6279. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6280. (cond
  6281. ((integerp arg)
  6282. (org-show-all '(headings blocks))
  6283. (outline-hide-sublevels arg)
  6284. (setq org-cycle-global-status 'contents))
  6285. ((equal arg '(4))
  6286. (org-set-startup-visibility)
  6287. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6288. (t
  6289. (org-cycle '(4))))))
  6290. (defun org-set-startup-visibility ()
  6291. "Set the visibility required by startup options and properties."
  6292. (cond
  6293. ((eq org-startup-folded t)
  6294. (org-overview))
  6295. ((eq org-startup-folded 'content)
  6296. (org-content))
  6297. ((or (eq org-startup-folded 'showeverything)
  6298. (eq org-startup-folded nil))
  6299. (org-show-all)))
  6300. (unless (eq org-startup-folded 'showeverything)
  6301. (when org-hide-block-startup (org-hide-block-all))
  6302. (org-set-visibility-according-to-property)
  6303. (org-cycle-hide-archived-subtrees 'all)
  6304. (org-cycle-hide-drawers 'all)
  6305. (org-cycle-show-empty-lines t)))
  6306. (defun org-set-visibility-according-to-property ()
  6307. "Switch subtree visibilities according to :VISIBILITY: property."
  6308. (interactive)
  6309. (org-with-wide-buffer
  6310. (goto-char (point-min))
  6311. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6312. (if (not (org-at-property-p)) (outline-next-heading)
  6313. (let ((state (match-string 3)))
  6314. (save-excursion
  6315. (org-back-to-heading t)
  6316. (outline-hide-subtree)
  6317. (org-reveal)
  6318. (cond
  6319. ((equal state "folded")
  6320. (outline-hide-subtree))
  6321. ((equal state "children")
  6322. (org-show-hidden-entry)
  6323. (org-show-children))
  6324. ((equal state "content")
  6325. (save-excursion
  6326. (save-restriction
  6327. (org-narrow-to-subtree)
  6328. (org-content))))
  6329. ((member state '("all" "showall"))
  6330. (outline-show-subtree)))))))))
  6331. (defun org-overview ()
  6332. "Switch to overview mode, showing only top-level headlines.
  6333. This shows all headlines with a level equal or greater than the level
  6334. of the first headline in the buffer. This is important, because if the
  6335. first headline is not level one, then (hide-sublevels 1) gives confusing
  6336. results."
  6337. (interactive)
  6338. (save-excursion
  6339. (let ((level
  6340. (save-excursion
  6341. (goto-char (point-min))
  6342. (when (re-search-forward org-outline-regexp-bol nil t)
  6343. (goto-char (match-beginning 0))
  6344. (funcall outline-level)))))
  6345. (and level (outline-hide-sublevels level)))))
  6346. (defun org-content (&optional arg)
  6347. "Show all headlines in the buffer, like a table of contents.
  6348. With numerical argument N, show content up to level N."
  6349. (interactive "P")
  6350. (org-overview)
  6351. (save-excursion
  6352. ;; Visit all headings and show their offspring
  6353. (and (integerp arg) (org-overview))
  6354. (goto-char (point-max))
  6355. (catch 'exit
  6356. (while (and (progn (condition-case nil
  6357. (outline-previous-visible-heading 1)
  6358. (error (goto-char (point-min))))
  6359. t)
  6360. (looking-at org-outline-regexp))
  6361. (if (integerp arg)
  6362. (org-show-children (1- arg))
  6363. (outline-show-branches))
  6364. (when (bobp) (throw 'exit nil))))))
  6365. (defun org-optimize-window-after-visibility-change (state)
  6366. "Adjust the window after a change in outline visibility.
  6367. This function is the default value of the hook `org-cycle-hook'."
  6368. (when (get-buffer-window (current-buffer))
  6369. (cond
  6370. ((eq state 'content) nil)
  6371. ((eq state 'all) nil)
  6372. ((eq state 'folded) nil)
  6373. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6374. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6375. (defun org-clean-visibility-after-subtree-move ()
  6376. "Fix visibility issues after moving a subtree."
  6377. ;; First, find a reasonable region to look at:
  6378. ;; Start two siblings above, end three below
  6379. (let* ((beg (save-excursion
  6380. (and (org-get-last-sibling)
  6381. (org-get-last-sibling))
  6382. (point)))
  6383. (end (save-excursion
  6384. (and (org-get-next-sibling)
  6385. (org-get-next-sibling)
  6386. (org-get-next-sibling))
  6387. (if (org-at-heading-p)
  6388. (point-at-eol)
  6389. (point))))
  6390. (level (looking-at "\\*+"))
  6391. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6392. (save-excursion
  6393. (save-restriction
  6394. (narrow-to-region beg end)
  6395. (when re
  6396. ;; Properly fold already folded siblings
  6397. (goto-char (point-min))
  6398. (while (re-search-forward re nil t)
  6399. (when (and (not (org-invisible-p))
  6400. (org-invisible-p (line-end-position)))
  6401. (outline-hide-entry))))
  6402. (org-cycle-hide-drawers 'all)
  6403. (org-cycle-show-empty-lines 'overview)))))
  6404. (defun org-cycle-show-empty-lines (state)
  6405. "Show empty lines above all visible headlines.
  6406. The region to be covered depends on STATE when called through
  6407. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6408. entire buffer covered. Note that an empty line is only shown if there
  6409. are at least `org-cycle-separator-lines' empty lines before the headline."
  6410. (when (/= org-cycle-separator-lines 0)
  6411. (save-excursion
  6412. (let* ((n (abs org-cycle-separator-lines))
  6413. (re (cond
  6414. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6415. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6416. (t (let ((ns (number-to-string (- n 2))))
  6417. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6418. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6419. beg end)
  6420. (cond
  6421. ((memq state '(overview contents t))
  6422. (setq beg (point-min) end (point-max)))
  6423. ((memq state '(children folded))
  6424. (setq beg (point)
  6425. end (progn (org-end-of-subtree t t)
  6426. (line-beginning-position 2)))))
  6427. (when beg
  6428. (goto-char beg)
  6429. (while (re-search-forward re end t)
  6430. (unless (get-char-property (match-end 1) 'invisible)
  6431. (let ((e (match-end 1))
  6432. (b (if (>= org-cycle-separator-lines 0)
  6433. (match-beginning 1)
  6434. (save-excursion
  6435. (goto-char (match-beginning 0))
  6436. (skip-chars-backward " \t\n")
  6437. (line-end-position)))))
  6438. (org-flag-region b e nil 'outline))))))))
  6439. ;; Never hide empty lines at the end of the file.
  6440. (save-excursion
  6441. (goto-char (point-max))
  6442. (outline-previous-heading)
  6443. (outline-end-of-heading)
  6444. (when (and (looking-at "[ \t\n]+")
  6445. (= (match-end 0) (point-max)))
  6446. (org-flag-region (point) (match-end 0) nil 'outline))))
  6447. ;;;; Reveal point location
  6448. (defun org-show-context (&optional key)
  6449. "Make sure point and context are visible.
  6450. Optional argument KEY, when non-nil, is a symbol. See
  6451. `org-show-context-detail' for allowed values and how much is to
  6452. be shown."
  6453. (org-show-set-visibility
  6454. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6455. ((cdr (assq key org-show-context-detail)))
  6456. (t (cdr (assq 'default org-show-context-detail))))))
  6457. (defun org-show-set-visibility (detail)
  6458. "Set visibility around point according to DETAIL.
  6459. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6460. `tree', `canonical' or t. See `org-show-context-detail' for more
  6461. information."
  6462. ;; Show current heading and possibly its entry, following headline
  6463. ;; or all children.
  6464. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6465. (org-flag-heading nil)
  6466. (org-show-entry)
  6467. ;; If point is hidden within a drawer or a block, make sure to
  6468. ;; expose it.
  6469. (dolist (o (overlays-at (point)))
  6470. (when (memq (overlay-get o 'invisible)
  6471. '(org-hide-block org-hide-drawer outline))
  6472. (delete-overlay o)))
  6473. (unless (org-before-first-heading-p)
  6474. (org-with-limited-levels
  6475. (cl-case detail
  6476. ((tree canonical t) (org-show-children))
  6477. ((nil minimal ancestors))
  6478. (t (save-excursion
  6479. (outline-next-heading)
  6480. (org-flag-heading nil)))))))
  6481. ;; Show all siblings.
  6482. (when (eq detail 'lineage) (org-show-siblings))
  6483. ;; Show ancestors, possibly with their children.
  6484. (when (memq detail '(ancestors lineage tree canonical t))
  6485. (save-excursion
  6486. (while (org-up-heading-safe)
  6487. (org-flag-heading nil)
  6488. (when (memq detail '(canonical t)) (org-show-entry))
  6489. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6490. (defvar org-reveal-start-hook nil
  6491. "Hook run before revealing a location.")
  6492. (defun org-reveal (&optional siblings)
  6493. "Show current entry, hierarchy above it, and the following headline.
  6494. This can be used to show a consistent set of context around
  6495. locations exposed with `org-show-context'.
  6496. With optional argument SIBLINGS, on each level of the hierarchy all
  6497. siblings are shown. This repairs the tree structure to what it would
  6498. look like when opened with hierarchical calls to `org-cycle'.
  6499. With a \\[universal-argument] \\[universal-argument] prefix, \
  6500. go to the parent and show the entire tree."
  6501. (interactive "P")
  6502. (run-hooks 'org-reveal-start-hook)
  6503. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6504. ((equal siblings '(16))
  6505. (save-excursion
  6506. (when (org-up-heading-safe)
  6507. (org-show-subtree)
  6508. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6509. (t (org-show-set-visibility 'lineage))))
  6510. ;;; Indirect buffer display of subtrees
  6511. (defvar org-indirect-dedicated-frame nil
  6512. "This is the frame being used for indirect tree display.")
  6513. (defvar org-last-indirect-buffer nil)
  6514. (defun org-tree-to-indirect-buffer (&optional arg)
  6515. "Create indirect buffer and narrow it to current subtree.
  6516. With a numerical prefix ARG, go up to this level and then take that tree.
  6517. If ARG is negative, go up that many levels.
  6518. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6519. indirect buffer previously made with this command, to avoid proliferation of
  6520. indirect buffers. However, when you call the command with a \
  6521. `\\[universal-argument]' prefix, or
  6522. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6523. so that you can work with several indirect buffers at the same time. If
  6524. `org-indirect-buffer-display' is `dedicated-frame', the \
  6525. `\\[universal-argument]' prefix also
  6526. requests that a new frame be made for the new buffer, so that the dedicated
  6527. frame is not changed."
  6528. (interactive "P")
  6529. (let ((cbuf (current-buffer))
  6530. (cwin (selected-window))
  6531. (pos (point))
  6532. beg end level heading ibuf)
  6533. (save-excursion
  6534. (org-back-to-heading t)
  6535. (when (numberp arg)
  6536. (setq level (org-outline-level))
  6537. (when (< arg 0) (setq arg (+ level arg)))
  6538. (while (> (setq level (org-outline-level)) arg)
  6539. (org-up-heading-safe)))
  6540. (setq beg (point)
  6541. heading (org-get-heading 'no-tags))
  6542. (org-end-of-subtree t t)
  6543. (when (org-at-heading-p) (backward-char 1))
  6544. (setq end (point)))
  6545. (when (and (buffer-live-p org-last-indirect-buffer)
  6546. (not (eq org-indirect-buffer-display 'new-frame))
  6547. (not arg))
  6548. (kill-buffer org-last-indirect-buffer))
  6549. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6550. org-last-indirect-buffer ibuf)
  6551. (cond
  6552. ((or (eq org-indirect-buffer-display 'new-frame)
  6553. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6554. (select-frame (make-frame))
  6555. (delete-other-windows)
  6556. (pop-to-buffer-same-window ibuf)
  6557. (org-set-frame-title heading))
  6558. ((eq org-indirect-buffer-display 'dedicated-frame)
  6559. (raise-frame
  6560. (select-frame (or (and org-indirect-dedicated-frame
  6561. (frame-live-p org-indirect-dedicated-frame)
  6562. org-indirect-dedicated-frame)
  6563. (setq org-indirect-dedicated-frame (make-frame)))))
  6564. (delete-other-windows)
  6565. (pop-to-buffer-same-window ibuf)
  6566. (org-set-frame-title (concat "Indirect: " heading)))
  6567. ((eq org-indirect-buffer-display 'current-window)
  6568. (pop-to-buffer-same-window ibuf))
  6569. ((eq org-indirect-buffer-display 'other-window)
  6570. (pop-to-buffer ibuf))
  6571. (t (error "Invalid value")))
  6572. (narrow-to-region beg end)
  6573. (org-show-all '(headings blocks))
  6574. (goto-char pos)
  6575. (run-hook-with-args 'org-cycle-hook 'all)
  6576. (and (window-live-p cwin) (select-window cwin))))
  6577. (defun org-get-indirect-buffer (&optional buffer heading)
  6578. (setq buffer (or buffer (current-buffer)))
  6579. (let ((n 1) (base (buffer-name buffer)) bname)
  6580. (while (buffer-live-p
  6581. (get-buffer
  6582. (setq bname
  6583. (concat base "-"
  6584. (if heading (concat heading "-" (number-to-string n))
  6585. (number-to-string n))))))
  6586. (setq n (1+ n)))
  6587. (condition-case nil
  6588. (make-indirect-buffer buffer bname 'clone)
  6589. (error (make-indirect-buffer buffer bname)))))
  6590. (defun org-set-frame-title (title)
  6591. "Set the title of the current frame to the string TITLE."
  6592. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6593. ;;;; Structure editing
  6594. ;;; Inserting headlines
  6595. (defun org--line-empty-p (n)
  6596. "Is the Nth next line empty?
  6597. Counts the current line as N = 1 and the previous line as N = 0;
  6598. see `beginning-of-line'."
  6599. (save-excursion
  6600. (and (not (bobp))
  6601. (or (beginning-of-line n) t)
  6602. (save-match-data
  6603. (looking-at "[ \t]*$")))))
  6604. (defun org-previous-line-empty-p ()
  6605. "Is the previous line a blank line?
  6606. When NEXT is non-nil, check the next line instead."
  6607. (org--line-empty-p 0))
  6608. (defun org-next-line-empty-p ()
  6609. "Is the previous line a blank line?
  6610. When NEXT is non-nil, check the next line instead."
  6611. (org--line-empty-p 2))
  6612. (defun org--blank-before-heading-p (&optional parent)
  6613. "Non-nil when an empty line should precede a new heading here.
  6614. When optional argument PARENT is non-nil, consider parent
  6615. headline instead of current one."
  6616. (pcase (assq 'heading org-blank-before-new-entry)
  6617. (`(heading . auto)
  6618. (save-excursion
  6619. (org-with-limited-levels
  6620. (unless (and (org-before-first-heading-p)
  6621. (not (outline-next-heading)))
  6622. (org-back-to-heading t)
  6623. (when parent (org-up-heading-safe))
  6624. (cond ((not (bobp))
  6625. (org-previous-line-empty-p))
  6626. ((outline-next-heading)
  6627. (org-previous-line-empty-p))
  6628. ;; Ignore trailing spaces on last buffer line.
  6629. ((progn (skip-chars-backward " \t") (bolp))
  6630. (org-previous-line-empty-p))
  6631. (t nil))))))
  6632. (`(heading . ,value) value)
  6633. (_ nil)))
  6634. (defun org-insert-heading (&optional arg invisible-ok top)
  6635. "Insert a new heading or an item with the same depth at point.
  6636. If point is at the beginning of a heading, insert a new heading
  6637. or a new headline above the current one. When at the beginning
  6638. of a regular line of text, turn it into a heading.
  6639. If point is in the middle of a line, split it and create a new
  6640. headline with the text in the current line after point (see
  6641. `org-M-RET-may-split-line' on how to modify this behavior). As
  6642. a special case, on a headline, splitting can only happen on the
  6643. title itself. E.g., this excludes breaking stars or tags.
  6644. With a `\\[universal-argument]' prefix, set \
  6645. `org-insert-heading-respect-content' to
  6646. a non-nil value for the duration of the command. This forces the
  6647. insertion of a heading after the current subtree, independently
  6648. on the location of point.
  6649. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6650. insert the heading at the end of the tree
  6651. above the current heading. For example, if point is within a
  6652. 2nd-level heading, then it will insert a 2nd-level heading at
  6653. the end of the 1st-level parent subtree.
  6654. When INVISIBLE-OK is set, stop at invisible headlines when going
  6655. back. This is important for non-interactive uses of the
  6656. command.
  6657. When optional argument TOP is non-nil, insert a level 1 heading,
  6658. unconditionally."
  6659. (interactive "P")
  6660. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6661. (level (org-current-level))
  6662. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6663. (cond
  6664. ((or org-insert-heading-respect-content
  6665. (member arg '((4) (16)))
  6666. (and (not invisible-ok)
  6667. (invisible-p (max (1- (point)) (point-min)))))
  6668. ;; Position point at the location of insertion.
  6669. (if (not level) ;before first headline
  6670. (org-with-limited-levels (outline-next-heading))
  6671. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6672. ;; is nil.
  6673. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6674. (cond ((equal arg '(16))
  6675. (org-up-heading-safe)
  6676. (org-end-of-subtree t t))
  6677. (t
  6678. (org-end-of-subtree t t))))
  6679. (unless (bolp) (insert "\n")) ;ensure final newline
  6680. (unless (and blank? (org-previous-line-empty-p))
  6681. (org-N-empty-lines-before-current (if blank? 1 0)))
  6682. (insert stars " \n")
  6683. (forward-char -1))
  6684. ;; At a headline...
  6685. ((org-at-heading-p)
  6686. (cond ((bolp)
  6687. (when blank? (save-excursion (insert "\n")))
  6688. (save-excursion (insert stars " \n"))
  6689. (unless (and blank? (org-previous-line-empty-p))
  6690. (org-N-empty-lines-before-current (if blank? 1 0)))
  6691. (end-of-line))
  6692. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6693. (org-match-line org-complex-heading-regexp)
  6694. (org-pos-in-match-range (point) 4))
  6695. ;; Grab the text that should moved to the new headline.
  6696. ;; Preserve tags.
  6697. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6698. (if (looking-at "[ \t]*$") (replace-match "")
  6699. (org-set-tags nil t))
  6700. (end-of-line)
  6701. (when blank? (insert "\n"))
  6702. (insert "\n" stars " ")
  6703. (when (org-string-nw-p split) (insert split))
  6704. (when (eobp) (save-excursion (insert "\n")))))
  6705. (t
  6706. (end-of-line)
  6707. (when blank? (insert "\n"))
  6708. (insert "\n" stars " ")
  6709. (when (eobp) (save-excursion (insert "\n"))))))
  6710. ;; On regular text, turn line into a headline or split, if
  6711. ;; appropriate.
  6712. ((bolp)
  6713. (insert stars " ")
  6714. (unless (and blank? (org-previous-line-empty-p))
  6715. (org-N-empty-lines-before-current (if blank? 1 0))))
  6716. (t
  6717. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6718. (end-of-line))
  6719. (insert "\n" stars " ")
  6720. (unless (and blank? (org-previous-line-empty-p))
  6721. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6722. (run-hooks 'org-insert-heading-hook))
  6723. (defun org-N-empty-lines-before-current (n)
  6724. "Make the number of empty lines before current exactly N.
  6725. So this will delete or add empty lines."
  6726. (let ((column (current-column)))
  6727. (beginning-of-line)
  6728. (unless (bobp)
  6729. (let ((start (save-excursion
  6730. (skip-chars-backward " \r\t\n")
  6731. (line-end-position))))
  6732. (delete-region start (line-end-position 0))))
  6733. (insert (make-string n ?\n))
  6734. (move-to-column column)))
  6735. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6736. "Return the heading of the current entry, without the stars.
  6737. When NO-TAGS is non-nil, don't include tags.
  6738. When NO-TODO is non-nil, don't include TODO keywords.
  6739. When NO-PRIORITY is non-nil, don't include priority cookie.
  6740. When NO-COMMENT is non-nil, don't include COMMENT string."
  6741. (save-excursion
  6742. (org-back-to-heading t)
  6743. (let ((case-fold-search nil))
  6744. (looking-at org-complex-heading-regexp)
  6745. (let ((todo (and (not no-todo) (match-string 2)))
  6746. (priority (and (not no-priority) (match-string 3)))
  6747. (headline (pcase (match-string 4)
  6748. (`nil "")
  6749. ((and (guard no-comment) h)
  6750. (replace-regexp-in-string
  6751. (eval-when-compile
  6752. (format "\\`%s[ \t]+" org-comment-string))
  6753. "" h))
  6754. (h h)))
  6755. (tags (and (not no-tags) (match-string 5))))
  6756. (mapconcat #'identity
  6757. (delq nil (list todo priority headline tags))
  6758. " ")))))
  6759. (defun org-heading-components ()
  6760. "Return the components of the current heading.
  6761. This is a list with the following elements:
  6762. - the level as an integer
  6763. - the reduced level, different if `org-odd-levels-only' is set.
  6764. - the TODO keyword, or nil
  6765. - the priority character, like ?A, or nil if no priority is given
  6766. - the headline text itself, or the tags string if no headline text
  6767. - the tags string, or nil."
  6768. (save-excursion
  6769. (org-back-to-heading t)
  6770. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6771. (list (length (match-string 1))
  6772. (org-reduced-level (length (match-string 1)))
  6773. (match-string-no-properties 2)
  6774. (and (match-end 3) (aref (match-string 3) 2))
  6775. (match-string-no-properties 4)
  6776. (match-string-no-properties 5)))))
  6777. (defun org-get-entry ()
  6778. "Get the entry text, after heading, entire subtree."
  6779. (save-excursion
  6780. (org-back-to-heading t)
  6781. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6782. (defun org-edit-headline (&optional heading)
  6783. "Edit the current headline.
  6784. Set it to HEADING when provided."
  6785. (interactive)
  6786. (org-with-wide-buffer
  6787. (org-back-to-heading t)
  6788. (let ((case-fold-search nil))
  6789. (when (looking-at org-complex-heading-regexp)
  6790. (let* ((old (match-string-no-properties 4))
  6791. (new (save-match-data
  6792. (org-trim (or heading (read-string "Edit: " old))))))
  6793. (unless (equal old new)
  6794. (if old (replace-match new t t nil 4)
  6795. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6796. (insert " " new))
  6797. (org-set-tags nil t)
  6798. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6799. (defun org-insert-heading-after-current ()
  6800. "Insert a new heading with same level as current, after current subtree."
  6801. (interactive)
  6802. (org-back-to-heading)
  6803. (org-insert-heading)
  6804. (org-move-subtree-down)
  6805. (end-of-line 1))
  6806. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6807. "Insert heading with `org-insert-heading-respect-content' set to t."
  6808. (interactive)
  6809. (org-insert-heading '(4) invisible-ok))
  6810. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6811. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6812. (interactive)
  6813. (org-insert-todo-heading force-state '(4)))
  6814. (defun org-insert-todo-heading (arg &optional force-heading)
  6815. "Insert a new heading with the same level and TODO state as current heading.
  6816. If the heading has no TODO state, or if the state is DONE, use
  6817. the first state (TODO by default). Also with one prefix arg,
  6818. force first state. With two prefix args, force inserting at the
  6819. end of the parent subtree.
  6820. When called at a plain list item, insert a new item with an
  6821. unchecked check box."
  6822. (interactive "P")
  6823. (when (or force-heading (not (org-insert-item 'checkbox)))
  6824. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6825. force-heading))
  6826. (save-excursion
  6827. (org-forward-heading-same-level -1)
  6828. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6829. (let* ((new-mark-x
  6830. (if (or (equal arg '(4))
  6831. (not (match-beginning 2))
  6832. (member (match-string 2) org-done-keywords))
  6833. (car org-todo-keywords-1)
  6834. (match-string 2)))
  6835. (new-mark
  6836. (or
  6837. (run-hook-with-args-until-success
  6838. 'org-todo-get-default-hook new-mark-x nil)
  6839. new-mark-x)))
  6840. (beginning-of-line 1)
  6841. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6842. (if org-treat-insert-todo-heading-as-state-change
  6843. (org-todo new-mark)
  6844. (insert new-mark " "))))
  6845. (when org-provide-todo-statistics
  6846. (org-update-parent-todo-statistics))))
  6847. (defun org-insert-subheading (arg)
  6848. "Insert a new subheading and demote it.
  6849. Works for outline headings and for plain lists alike."
  6850. (interactive "P")
  6851. (org-insert-heading arg)
  6852. (cond
  6853. ((org-at-heading-p) (org-do-demote))
  6854. ((org-at-item-p) (org-indent-item))))
  6855. (defun org-insert-todo-subheading (arg)
  6856. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6857. Works for outline headings and for plain lists alike."
  6858. (interactive "P")
  6859. (org-insert-todo-heading arg)
  6860. (cond
  6861. ((org-at-heading-p) (org-do-demote))
  6862. ((org-at-item-p) (org-indent-item))))
  6863. ;;; Promotion and Demotion
  6864. (defvar org-after-demote-entry-hook nil
  6865. "Hook run after an entry has been demoted.
  6866. The cursor will be at the beginning of the entry.
  6867. When a subtree is being demoted, the hook will be called for each node.")
  6868. (defvar org-after-promote-entry-hook nil
  6869. "Hook run after an entry has been promoted.
  6870. The cursor will be at the beginning of the entry.
  6871. When a subtree is being promoted, the hook will be called for each node.")
  6872. (defun org-promote-subtree ()
  6873. "Promote the entire subtree.
  6874. See also `org-promote'."
  6875. (interactive)
  6876. (save-excursion
  6877. (org-with-limited-levels (org-map-tree 'org-promote)))
  6878. (org-fix-position-after-promote))
  6879. (defun org-demote-subtree ()
  6880. "Demote the entire subtree.
  6881. See `org-demote' and `org-promote'."
  6882. (interactive)
  6883. (save-excursion
  6884. (org-with-limited-levels (org-map-tree 'org-demote)))
  6885. (org-fix-position-after-promote))
  6886. (defun org-do-promote ()
  6887. "Promote the current heading higher up the tree.
  6888. If the region is active in `transient-mark-mode', promote all
  6889. headings in the region."
  6890. (interactive)
  6891. (save-excursion
  6892. (if (org-region-active-p)
  6893. (org-map-region 'org-promote (region-beginning) (region-end))
  6894. (org-promote)))
  6895. (org-fix-position-after-promote))
  6896. (defun org-do-demote ()
  6897. "Demote the current heading lower down the tree.
  6898. If the region is active in `transient-mark-mode', demote all
  6899. headings in the region."
  6900. (interactive)
  6901. (save-excursion
  6902. (if (org-region-active-p)
  6903. (org-map-region 'org-demote (region-beginning) (region-end))
  6904. (org-demote)))
  6905. (org-fix-position-after-promote))
  6906. (defun org-fix-position-after-promote ()
  6907. "Fix cursor position and indentation after demoting/promoting."
  6908. (let ((pos (point)))
  6909. (when (save-excursion
  6910. (beginning-of-line)
  6911. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6912. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6913. (cond ((eobp) (insert " "))
  6914. ((eolp) (insert " "))
  6915. ((equal (char-after) ?\s) (forward-char 1))))))
  6916. (defun org-current-level ()
  6917. "Return the level of the current entry, or nil if before the first headline.
  6918. The level is the number of stars at the beginning of the
  6919. headline. Use `org-reduced-level' to remove the effect of
  6920. `org-odd-levels'. Unlike to `org-outline-level', this function
  6921. ignores inlinetasks."
  6922. (let ((level (org-with-limited-levels (org-outline-level))))
  6923. (and (> level 0) level)))
  6924. (defun org-get-previous-line-level ()
  6925. "Return the outline depth of the last headline before the current line.
  6926. Returns 0 for the first headline in the buffer, and nil if before the
  6927. first headline."
  6928. (and (org-current-level)
  6929. (or (and (/= (line-beginning-position) (point-min))
  6930. (save-excursion (beginning-of-line 0) (org-current-level)))
  6931. 0)))
  6932. (defun org-reduced-level (l)
  6933. "Compute the effective level of a heading.
  6934. This takes into account the setting of `org-odd-levels-only'."
  6935. (cond
  6936. ((zerop l) 0)
  6937. (org-odd-levels-only (1+ (floor (/ l 2))))
  6938. (t l)))
  6939. (defun org-level-increment ()
  6940. "Return the number of stars that will be added or removed at a
  6941. time to headlines when structure editing, based on the value of
  6942. `org-odd-levels-only'."
  6943. (if org-odd-levels-only 2 1))
  6944. (defun org-get-valid-level (level &optional change)
  6945. "Rectify a level change under the influence of `org-odd-levels-only'.
  6946. LEVEL is a current level, CHANGE is by how much the level should
  6947. be modified. Even if CHANGE is nil, LEVEL may be returned
  6948. modified because even level numbers will become the next higher
  6949. odd number. Returns values greater than 0."
  6950. (if org-odd-levels-only
  6951. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6952. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6953. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6954. (max 1 (+ level (or change 0)))))
  6955. (defun org-promote ()
  6956. "Promote the current heading higher up the tree."
  6957. (org-with-wide-buffer
  6958. (org-back-to-heading t)
  6959. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6960. after-change-functions))
  6961. (level (save-match-data (funcall outline-level)))
  6962. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6963. (diff (abs (- level (length up-head) -1))))
  6964. (cond
  6965. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6966. (replace-match "# " nil t))
  6967. ((= level 1)
  6968. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6969. (t (replace-match up-head nil t)))
  6970. (unless (= level 1)
  6971. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6972. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6973. (run-hooks 'org-after-promote-entry-hook))))
  6974. (defun org-demote ()
  6975. "Demote the current heading lower down the tree."
  6976. (org-with-wide-buffer
  6977. (org-back-to-heading t)
  6978. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6979. after-change-functions))
  6980. (level (save-match-data (funcall outline-level)))
  6981. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6982. (diff (abs (- level (length down-head) -1))))
  6983. (replace-match down-head nil t)
  6984. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6985. (when org-adapt-indentation (org-fixup-indentation diff))
  6986. (run-hooks 'org-after-demote-entry-hook))))
  6987. (defun org-cycle-level ()
  6988. "Cycle the level of an empty headline through possible states.
  6989. This goes first to child, then to parent, level, then up the hierarchy.
  6990. After top level, it switches back to sibling level."
  6991. (interactive)
  6992. (let ((org-adapt-indentation nil))
  6993. (when (org-point-at-end-of-empty-headline)
  6994. (setq this-command 'org-cycle-level) ; Only needed for caching
  6995. (let ((cur-level (org-current-level))
  6996. (prev-level (org-get-previous-line-level)))
  6997. (cond
  6998. ;; If first headline in file, promote to top-level.
  6999. ((= prev-level 0)
  7000. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7001. do (org-do-promote)))
  7002. ;; If same level as prev, demote one.
  7003. ((= prev-level cur-level)
  7004. (org-do-demote))
  7005. ;; If parent is top-level, promote to top level if not already.
  7006. ((= prev-level 1)
  7007. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7008. do (org-do-promote)))
  7009. ;; If top-level, return to prev-level.
  7010. ((= cur-level 1)
  7011. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7012. do (org-do-demote)))
  7013. ;; If less than prev-level, promote one.
  7014. ((< cur-level prev-level)
  7015. (org-do-promote))
  7016. ;; If deeper than prev-level, promote until higher than
  7017. ;; prev-level.
  7018. ((> cur-level prev-level)
  7019. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7020. do (org-do-promote))))
  7021. t))))
  7022. (defun org-map-tree (fun)
  7023. "Call FUN for every heading underneath the current one."
  7024. (org-back-to-heading t)
  7025. (let ((level (funcall outline-level)))
  7026. (save-excursion
  7027. (funcall fun)
  7028. (while (and (progn
  7029. (outline-next-heading)
  7030. (> (funcall outline-level) level))
  7031. (not (eobp)))
  7032. (funcall fun)))))
  7033. (defun org-map-region (fun beg end)
  7034. "Call FUN for every heading between BEG and END."
  7035. (let ((org-ignore-region t))
  7036. (save-excursion
  7037. (setq end (copy-marker end))
  7038. (goto-char beg)
  7039. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7040. (< (point) end))
  7041. (funcall fun))
  7042. (while (and (progn
  7043. (outline-next-heading)
  7044. (< (point) end))
  7045. (not (eobp)))
  7046. (funcall fun)))))
  7047. (defun org-fixup-indentation (diff)
  7048. "Change the indentation in the current entry by DIFF.
  7049. DIFF is an integer. Indentation is done according to the
  7050. following rules:
  7051. - Planning information and property drawers are always indented
  7052. according to the new level of the headline;
  7053. - Footnote definitions and their contents are ignored;
  7054. - Inlinetasks' boundaries are not shifted;
  7055. - Empty lines are ignored;
  7056. - Other lines' indentation are shifted by DIFF columns, unless
  7057. it would introduce a structural change in the document, in
  7058. which case no shifting is done at all.
  7059. Assume point is at a heading or an inlinetask beginning."
  7060. (org-with-wide-buffer
  7061. (narrow-to-region (line-beginning-position)
  7062. (save-excursion
  7063. (if (org-with-limited-levels (org-at-heading-p))
  7064. (org-with-limited-levels (outline-next-heading))
  7065. (org-inlinetask-goto-end))
  7066. (point)))
  7067. (forward-line)
  7068. ;; Indent properly planning info and property drawer.
  7069. (when (looking-at-p org-planning-line-re)
  7070. (org-indent-line)
  7071. (forward-line))
  7072. (when (looking-at org-property-drawer-re)
  7073. (goto-char (match-end 0))
  7074. (forward-line)
  7075. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7076. (catch 'no-shift
  7077. (when (zerop diff) (throw 'no-shift nil))
  7078. ;; If DIFF is negative, first check if a shift is possible at all
  7079. ;; (e.g., it doesn't break structure). This can only happen if
  7080. ;; some contents are not properly indented.
  7081. (let ((case-fold-search t))
  7082. (when (< diff 0)
  7083. (let ((diff (- diff))
  7084. (forbidden-re (concat org-outline-regexp
  7085. "\\|"
  7086. (substring org-footnote-definition-re 1))))
  7087. (save-excursion
  7088. (while (not (eobp))
  7089. (cond
  7090. ((looking-at-p "[ \t]*$") (forward-line))
  7091. ((and (looking-at-p org-footnote-definition-re)
  7092. (let ((e (org-element-at-point)))
  7093. (and (eq (org-element-type e) 'footnote-definition)
  7094. (goto-char (org-element-property :end e))))))
  7095. ((looking-at-p org-outline-regexp) (forward-line))
  7096. ;; Give up if shifting would move before column 0 or
  7097. ;; if it would introduce a headline or a footnote
  7098. ;; definition.
  7099. (t
  7100. (skip-chars-forward " \t")
  7101. (let ((ind (current-column)))
  7102. (when (or (< ind diff)
  7103. (and (= ind diff) (looking-at-p forbidden-re)))
  7104. (throw 'no-shift nil)))
  7105. ;; Ignore contents of example blocks and source
  7106. ;; blocks if their indentation is meant to be
  7107. ;; preserved. Jump to block's closing line.
  7108. (beginning-of-line)
  7109. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7110. (let ((e (org-element-at-point)))
  7111. (and (memq (org-element-type e)
  7112. '(example-block src-block))
  7113. (or org-src-preserve-indentation
  7114. (org-element-property :preserve-indent e))
  7115. (goto-char (org-element-property :end e))
  7116. (progn (skip-chars-backward " \r\t\n")
  7117. (beginning-of-line)
  7118. t))))
  7119. (forward-line))))))))
  7120. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7121. ;; by DIFF. Also skip contents of source or example blocks
  7122. ;; when indentation is meant to be preserved.
  7123. (while (not (eobp))
  7124. (cond
  7125. ((and (looking-at-p org-footnote-definition-re)
  7126. (let ((e (org-element-at-point)))
  7127. (and (eq (org-element-type e) 'footnote-definition)
  7128. (goto-char (org-element-property :end e))))))
  7129. ((looking-at-p org-outline-regexp) (forward-line))
  7130. ((looking-at-p "[ \t]*$") (forward-line))
  7131. (t
  7132. (indent-line-to (+ (org-get-indentation) diff))
  7133. (beginning-of-line)
  7134. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7135. (let ((e (org-element-at-point)))
  7136. (and (memq (org-element-type e)
  7137. '(example-block src-block))
  7138. (or org-src-preserve-indentation
  7139. (org-element-property :preserve-indent e))
  7140. (goto-char (org-element-property :end e))
  7141. (progn (skip-chars-backward " \r\t\n")
  7142. (beginning-of-line)
  7143. t))))
  7144. (forward-line)))))))))
  7145. (defun org-convert-to-odd-levels ()
  7146. "Convert an Org file with all levels allowed to one with odd levels.
  7147. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7148. level 5 etc."
  7149. (interactive)
  7150. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7151. (let ((outline-level 'org-outline-level)
  7152. (org-odd-levels-only nil) n)
  7153. (save-excursion
  7154. (goto-char (point-min))
  7155. (while (re-search-forward "^\\*\\*+ " nil t)
  7156. (setq n (- (length (match-string 0)) 2))
  7157. (while (>= (setq n (1- n)) 0)
  7158. (org-demote))
  7159. (end-of-line 1))))))
  7160. (defun org-convert-to-oddeven-levels ()
  7161. "Convert an Org file with only odd levels to one with odd/even levels.
  7162. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7163. file contains a section with an even level, conversion would
  7164. destroy the structure of the file. An error is signaled in this
  7165. case."
  7166. (interactive)
  7167. (goto-char (point-min))
  7168. ;; First check if there are no even levels
  7169. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7170. (org-show-set-visibility 'canonical)
  7171. (error "Not all levels are odd in this file. Conversion not possible"))
  7172. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7173. (let ((outline-regexp org-outline-regexp)
  7174. (outline-level 'org-outline-level)
  7175. (org-odd-levels-only nil) n)
  7176. (save-excursion
  7177. (goto-char (point-min))
  7178. (while (re-search-forward "^\\*\\*+ " nil t)
  7179. (setq n (/ (1- (length (match-string 0))) 2))
  7180. (while (>= (setq n (1- n)) 0)
  7181. (org-promote))
  7182. (end-of-line 1))))))
  7183. (defun org-tr-level (n)
  7184. "Make N odd if required."
  7185. (if org-odd-levels-only (1+ (/ n 2)) n))
  7186. ;;; Vertical tree motion, cutting and pasting of subtrees
  7187. (defun org-move-subtree-up (&optional arg)
  7188. "Move the current subtree up past ARG headlines of the same level."
  7189. (interactive "p")
  7190. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7191. (defun org-move-subtree-down (&optional arg)
  7192. "Move the current subtree down past ARG headlines of the same level."
  7193. (interactive "p")
  7194. (setq arg (prefix-numeric-value arg))
  7195. (org-preserve-local-variables
  7196. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7197. 'org-get-last-sibling))
  7198. (ins-point (make-marker))
  7199. (cnt (abs arg))
  7200. (col (current-column))
  7201. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7202. ;; Select the tree
  7203. (org-back-to-heading)
  7204. (setq beg0 (point))
  7205. (save-excursion
  7206. (setq ne-beg (org-back-over-empty-lines))
  7207. (setq beg (point)))
  7208. (save-match-data
  7209. (save-excursion (outline-end-of-heading)
  7210. (setq folded (org-invisible-p)))
  7211. (progn (org-end-of-subtree nil t)
  7212. (unless (eobp) (backward-char))))
  7213. (outline-next-heading)
  7214. (setq ne-end (org-back-over-empty-lines))
  7215. (setq end (point))
  7216. (goto-char beg0)
  7217. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7218. ;; include less whitespace
  7219. (save-excursion
  7220. (goto-char beg)
  7221. (forward-line (- ne-beg ne-end))
  7222. (setq beg (point))))
  7223. ;; Find insertion point, with error handling
  7224. (while (> cnt 0)
  7225. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7226. (goto-char beg0)
  7227. (user-error "Cannot move past superior level or buffer limit"))
  7228. (setq cnt (1- cnt)))
  7229. (when (> arg 0)
  7230. ;; Moving forward - still need to move over subtree
  7231. (org-end-of-subtree t t)
  7232. (save-excursion
  7233. (org-back-over-empty-lines)
  7234. (or (bolp) (newline))))
  7235. (setq ne-ins (org-back-over-empty-lines))
  7236. (move-marker ins-point (point))
  7237. (setq txt (buffer-substring beg end))
  7238. (org-save-markers-in-region beg end)
  7239. (delete-region beg end)
  7240. (org-remove-empty-overlays-at beg)
  7241. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7242. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7243. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7244. (let ((bbb (point)))
  7245. (insert-before-markers txt)
  7246. (org-reinstall-markers-in-region bbb)
  7247. (move-marker ins-point bbb))
  7248. (or (bolp) (insert "\n"))
  7249. (setq ins-end (point))
  7250. (goto-char ins-point)
  7251. (org-skip-whitespace)
  7252. (when (and (< arg 0)
  7253. (org-first-sibling-p)
  7254. (> ne-ins ne-beg))
  7255. ;; Move whitespace back to beginning
  7256. (save-excursion
  7257. (goto-char ins-end)
  7258. (let ((kill-whole-line t))
  7259. (kill-line (- ne-ins ne-beg)) (point)))
  7260. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7261. (move-marker ins-point nil)
  7262. (if folded
  7263. (outline-hide-subtree)
  7264. (org-show-entry)
  7265. (org-show-children))
  7266. (org-clean-visibility-after-subtree-move)
  7267. ;; move back to the initial column we were at
  7268. (move-to-column col))))
  7269. (defvar org-subtree-clip ""
  7270. "Clipboard for cut and paste of subtrees.
  7271. This is actually only a copy of the kill, because we use the normal kill
  7272. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7273. (defvar org-subtree-clip-folded nil
  7274. "Was the last copied subtree folded?
  7275. This is used to fold the tree back after pasting.")
  7276. (defun org-cut-subtree (&optional n)
  7277. "Cut the current subtree into the clipboard.
  7278. With prefix arg N, cut this many sequential subtrees.
  7279. This is a short-hand for marking the subtree and then cutting it."
  7280. (interactive "p")
  7281. (org-copy-subtree n 'cut))
  7282. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7283. "Copy the current subtree into the clipboard.
  7284. With prefix arg N, copy this many sequential subtrees.
  7285. This is a short-hand for marking the subtree and then copying it.
  7286. If CUT is non-nil, actually cut the subtree.
  7287. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7288. of some markers in the region, even if CUT is non-nil. This is
  7289. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7290. (interactive "p")
  7291. (org-preserve-local-variables
  7292. (let (beg end folded (beg0 (point)))
  7293. (if (called-interactively-p 'any)
  7294. (org-back-to-heading nil) ; take what looks like a subtree
  7295. (org-back-to-heading t)) ; take what is really there
  7296. (setq beg (point))
  7297. (skip-chars-forward " \t\r\n")
  7298. (save-match-data
  7299. (if nosubtrees
  7300. (outline-next-heading)
  7301. (save-excursion (outline-end-of-heading)
  7302. (setq folded (org-invisible-p)))
  7303. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7304. (org-end-of-subtree t t)))
  7305. ;; Include the end of an inlinetask
  7306. (when (and (featurep 'org-inlinetask)
  7307. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7308. "END[ \t]*$")))
  7309. (end-of-line))
  7310. (setq end (point))
  7311. (goto-char beg0)
  7312. (when (> end beg)
  7313. (setq org-subtree-clip-folded folded)
  7314. (when (or cut force-store-markers)
  7315. (org-save-markers-in-region beg end))
  7316. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7317. (setq org-subtree-clip (current-kill 0))
  7318. (message "%s: Subtree(s) with %d characters"
  7319. (if cut "Cut" "Copied")
  7320. (length org-subtree-clip))))))
  7321. (defun org-paste-subtree (&optional level tree for-yank remove)
  7322. "Paste the clipboard as a subtree, with modification of headline level.
  7323. The entire subtree is promoted or demoted in order to match a new headline
  7324. level.
  7325. If the cursor is at the beginning of a headline, the same level as
  7326. that headline is used to paste the tree.
  7327. If not, the new level is derived from the *visible* headings
  7328. before and after the insertion point, and taken to be the inferior headline
  7329. level of the two. So if the previous visible heading is level 3 and the
  7330. next is level 4 (or vice versa), level 4 will be used for insertion.
  7331. This makes sure that the subtree remains an independent subtree and does
  7332. not swallow low level entries.
  7333. You can also force a different level, either by using a numeric prefix
  7334. argument, or by inserting the heading marker by hand. For example, if the
  7335. cursor is after \"*****\", then the tree will be shifted to level 5.
  7336. If optional TREE is given, use this text instead of the kill ring.
  7337. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7338. move back over whitespace before inserting, and move point to the end of
  7339. the inserted text when done.
  7340. When REMOVE is non-nil, remove the subtree from the clipboard."
  7341. (interactive "P")
  7342. (setq tree (or tree (and kill-ring (current-kill 0))))
  7343. (unless (org-kill-is-subtree-p tree)
  7344. (user-error "%s"
  7345. (substitute-command-keys
  7346. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7347. (org-with-limited-levels
  7348. (let* ((visp (not (org-invisible-p)))
  7349. (txt tree)
  7350. (^re_ "\\(\\*+\\)[ \t]*")
  7351. (old-level (if (string-match org-outline-regexp-bol txt)
  7352. (- (match-end 0) (match-beginning 0) 1)
  7353. -1))
  7354. (force-level (cond (level (prefix-numeric-value level))
  7355. ((and (looking-at "[ \t]*$")
  7356. (string-match
  7357. "^\\*+$" (buffer-substring
  7358. (point-at-bol) (point))))
  7359. (- (match-end 0) (match-beginning 0)))
  7360. ((and (bolp)
  7361. (looking-at org-outline-regexp))
  7362. (- (match-end 0) (point) 1))))
  7363. (previous-level (save-excursion
  7364. (condition-case nil
  7365. (progn
  7366. (outline-previous-visible-heading 1)
  7367. (if (looking-at ^re_)
  7368. (- (match-end 0) (match-beginning 0) 1)
  7369. 1))
  7370. (error 1))))
  7371. (next-level (save-excursion
  7372. (condition-case nil
  7373. (progn
  7374. (or (looking-at org-outline-regexp)
  7375. (outline-next-visible-heading 1))
  7376. (if (looking-at ^re_)
  7377. (- (match-end 0) (match-beginning 0) 1)
  7378. 1))
  7379. (error 1))))
  7380. (new-level (or force-level (max previous-level next-level)))
  7381. (shift (if (or (= old-level -1)
  7382. (= new-level -1)
  7383. (= old-level new-level))
  7384. 0
  7385. (- new-level old-level)))
  7386. (delta (if (> shift 0) -1 1))
  7387. (func (if (> shift 0) 'org-demote 'org-promote))
  7388. (org-odd-levels-only nil)
  7389. beg end newend)
  7390. ;; Remove the forced level indicator
  7391. (when force-level
  7392. (delete-region (point-at-bol) (point)))
  7393. ;; Paste
  7394. (beginning-of-line (if (bolp) 1 2))
  7395. (setq beg (point))
  7396. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7397. (insert-before-markers txt)
  7398. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7399. (setq newend (point))
  7400. (org-reinstall-markers-in-region beg)
  7401. (setq end (point))
  7402. (goto-char beg)
  7403. (skip-chars-forward " \t\n\r")
  7404. (setq beg (point))
  7405. (when (and (org-invisible-p) visp)
  7406. (save-excursion (outline-show-heading)))
  7407. ;; Shift if necessary
  7408. (unless (= shift 0)
  7409. (save-restriction
  7410. (narrow-to-region beg end)
  7411. (while (not (= shift 0))
  7412. (org-map-region func (point-min) (point-max))
  7413. (setq shift (+ delta shift)))
  7414. (goto-char (point-min))
  7415. (setq newend (point-max))))
  7416. (when (or (called-interactively-p 'interactive) for-yank)
  7417. (message "Clipboard pasted as level %d subtree" new-level))
  7418. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7419. kill-ring
  7420. (eq org-subtree-clip (current-kill 0))
  7421. org-subtree-clip-folded)
  7422. ;; The tree was folded before it was killed/copied
  7423. (outline-hide-subtree))
  7424. (and for-yank (goto-char newend))
  7425. (and remove (setq kill-ring (cdr kill-ring))))))
  7426. (defun org-kill-is-subtree-p (&optional txt)
  7427. "Check if the current kill is an outline subtree, or a set of trees.
  7428. Returns nil if kill does not start with a headline, or if the first
  7429. headline level is not the largest headline level in the tree.
  7430. So this will actually accept several entries of equal levels as well,
  7431. which is OK for `org-paste-subtree'.
  7432. If optional TXT is given, check this string instead of the current kill."
  7433. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7434. (re (org-get-limited-outline-regexp))
  7435. (^re (concat "^" re))
  7436. (start-level (and kill
  7437. (string-match
  7438. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7439. kill)
  7440. (- (match-end 2) (match-beginning 2) 1)))
  7441. (start (1+ (or (match-beginning 2) -1))))
  7442. (if (not start-level)
  7443. (progn
  7444. nil) ;; does not even start with a heading
  7445. (catch 'exit
  7446. (while (setq start (string-match ^re kill (1+ start)))
  7447. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7448. (throw 'exit nil)))
  7449. t))))
  7450. (defvar org-markers-to-move nil
  7451. "Markers that should be moved with a cut-and-paste operation.
  7452. Those markers are stored together with their positions relative to
  7453. the start of the region.")
  7454. (defun org-save-markers-in-region (beg end)
  7455. "Check markers in region.
  7456. If these markers are between BEG and END, record their position relative
  7457. to BEG, so that after moving the block of text, we can put the markers back
  7458. into place.
  7459. This function gets called just before an entry or tree gets cut from the
  7460. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7461. called immediately, to move the markers with the entries."
  7462. (setq org-markers-to-move nil)
  7463. (when (featurep 'org-clock)
  7464. (org-clock-save-markers-for-cut-and-paste beg end))
  7465. (when (featurep 'org-agenda)
  7466. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7467. (defun org-check-and-save-marker (marker beg end)
  7468. "Check if MARKER is between BEG and END.
  7469. If yes, remember the marker and the distance to BEG."
  7470. (when (and (marker-buffer marker)
  7471. (equal (marker-buffer marker) (current-buffer))
  7472. (>= marker beg) (< marker end))
  7473. (push (cons marker (- marker beg)) org-markers-to-move)))
  7474. (defun org-reinstall-markers-in-region (beg)
  7475. "Move all remembered markers to their position relative to BEG."
  7476. (dolist (x org-markers-to-move)
  7477. (move-marker (car x) (+ beg (cdr x))))
  7478. (setq org-markers-to-move nil))
  7479. (defun org-narrow-to-subtree ()
  7480. "Narrow buffer to the current subtree."
  7481. (interactive)
  7482. (save-excursion
  7483. (save-match-data
  7484. (org-with-limited-levels
  7485. (narrow-to-region
  7486. (progn (org-back-to-heading t) (point))
  7487. (progn (org-end-of-subtree t t)
  7488. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7489. (point)))))))
  7490. (defun org-narrow-to-block ()
  7491. "Narrow buffer to the current block."
  7492. (interactive)
  7493. (let* ((case-fold-search t)
  7494. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7495. "^[ \t]*#\\+end_.*")))
  7496. (if blockp
  7497. (narrow-to-region (car blockp) (cdr blockp))
  7498. (user-error "Not in a block"))))
  7499. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7500. "Clone the task (subtree) at point N times.
  7501. The clones will be inserted as siblings.
  7502. In interactive use, the user will be prompted for the number of
  7503. clones to be produced. If the entry has a timestamp, the user
  7504. will also be prompted for a time shift, which may be a repeater
  7505. as used in time stamps, for example `+3d'. To disable this,
  7506. you can call the function with a universal prefix argument.
  7507. When a valid repeater is given and the entry contains any time
  7508. stamps, the clones will become a sequence in time, with time
  7509. stamps in the subtree shifted for each clone produced. If SHIFT
  7510. is nil or the empty string, time stamps will be left alone. The
  7511. ID property of the original subtree is removed.
  7512. In each clone, all the CLOCK entries will be removed. This
  7513. prevents Org from considering that the clocked times overlap.
  7514. If the original subtree did contain time stamps with a repeater,
  7515. the following will happen:
  7516. - the repeater will be removed in each clone
  7517. - an additional clone will be produced, with the current, unshifted
  7518. date(s) in the entry.
  7519. - the original entry will be placed *after* all the clones, with
  7520. repeater intact.
  7521. - the start days in the repeater in the original entry will be shifted
  7522. to past the last clone.
  7523. In this way you can spell out a number of instances of a repeating task,
  7524. and still retain the repeater to cover future instances of the task.
  7525. As described above, N+1 clones are produced when the original
  7526. subtree has a repeater. Setting N to 0, then, can be used to
  7527. remove the repeater from a subtree and create a shifted clone
  7528. with the original repeater."
  7529. (interactive "nNumber of clones to produce: ")
  7530. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7531. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7532. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7533. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7534. (shift
  7535. (or shift
  7536. (if (and (not (equal current-prefix-arg '(4)))
  7537. (save-excursion
  7538. (goto-char beg)
  7539. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7540. (read-from-minibuffer
  7541. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7542. ""))) ;No time shift
  7543. (doshift
  7544. (and (org-string-nw-p shift)
  7545. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7546. shift)
  7547. (user-error "Invalid shift specification %s" shift)))))
  7548. (goto-char end-of-tree)
  7549. (unless (bolp) (insert "\n"))
  7550. (let* ((end (point))
  7551. (template (buffer-substring beg end))
  7552. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7553. (shift-what (pcase (and doshift (match-string 2 shift))
  7554. (`nil nil)
  7555. ("d" 'day)
  7556. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7557. ("m" 'month)
  7558. ("y" 'year)
  7559. (_ (error "Unsupported time unit"))))
  7560. (nmin 1)
  7561. (nmax n)
  7562. (n-no-remove -1)
  7563. (idprop (org-entry-get nil "ID")))
  7564. (when (and doshift
  7565. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7566. template))
  7567. (delete-region beg end)
  7568. (setq end beg)
  7569. (setq nmin 0)
  7570. (setq nmax (1+ nmax))
  7571. (setq n-no-remove nmax))
  7572. (goto-char end)
  7573. (cl-loop for n from nmin to nmax do
  7574. (insert
  7575. ;; Prepare clone.
  7576. (with-temp-buffer
  7577. (insert template)
  7578. (org-mode)
  7579. (goto-char (point-min))
  7580. (org-show-subtree)
  7581. (and idprop (if org-clone-delete-id
  7582. (org-entry-delete nil "ID")
  7583. (org-id-get-create t)))
  7584. (unless (= n 0)
  7585. (while (re-search-forward org-clock-line-re nil t)
  7586. (delete-region (line-beginning-position)
  7587. (line-beginning-position 2)))
  7588. (goto-char (point-min))
  7589. (while (re-search-forward org-drawer-regexp nil t)
  7590. (org-remove-empty-drawer-at (point))))
  7591. (goto-char (point-min))
  7592. (when doshift
  7593. (while (re-search-forward org-ts-regexp-both nil t)
  7594. (org-timestamp-change (* n shift-n) shift-what))
  7595. (unless (= n n-no-remove)
  7596. (goto-char (point-min))
  7597. (while (re-search-forward org-ts-regexp nil t)
  7598. (save-excursion
  7599. (goto-char (match-beginning 0))
  7600. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7601. (delete-region (match-beginning 1) (match-end 1)))))))
  7602. (buffer-string)))))
  7603. (goto-char beg)))
  7604. ;;; Outline Sorting
  7605. (defun org-sort (&optional with-case)
  7606. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7607. Optional argument WITH-CASE means sort case-sensitively."
  7608. (interactive "P")
  7609. (org-call-with-arg
  7610. (cond ((org-at-table-p) #'org-table-sort-lines)
  7611. ((org-at-item-p) #'org-sort-list)
  7612. (t #'org-sort-entries))
  7613. with-case))
  7614. (defun org-sort-remove-invisible (s)
  7615. "Remove invisible part of links and emphasis markers from string S."
  7616. (remove-text-properties 0 (length s) org-rm-props s)
  7617. (replace-regexp-in-string
  7618. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7619. (replace-regexp-in-string
  7620. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7621. (org-link-display-format s)
  7622. t t) t t))
  7623. (defvar org-priority-regexp) ; defined later in the file
  7624. (defvar org-after-sorting-entries-or-items-hook nil
  7625. "Hook that is run after a bunch of entries or items have been sorted.
  7626. When children are sorted, the cursor is in the parent line when this
  7627. hook gets called. When a region or a plain list is sorted, the cursor
  7628. will be in the first entry of the sorted region/list.")
  7629. (defun org-sort-entries
  7630. (&optional with-case sorting-type getkey-func compare-func property
  7631. interactive?)
  7632. "Sort entries on a certain level of an outline tree.
  7633. If there is an active region, the entries in the region are sorted.
  7634. Else, if the cursor is before the first entry, sort the top-level items.
  7635. Else, the children of the entry at point are sorted.
  7636. Sorting can be alphabetically, numerically, by date/time as given by
  7637. a time stamp, by a property, by priority order, or by a custom function.
  7638. The command prompts for the sorting type unless it has been given to the
  7639. function through the SORTING-TYPE argument, which needs to be a character,
  7640. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7641. the precise meaning of each character:
  7642. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7643. c By creation time, which is assumed to be the first inactive time stamp
  7644. at the beginning of a line.
  7645. d By deadline date/time.
  7646. k By clocking time.
  7647. n Numerically, by converting the beginning of the entry/item to a number.
  7648. o By order of TODO keywords.
  7649. p By priority according to the cookie.
  7650. r By the value of a property.
  7651. s By scheduled date/time.
  7652. t By date/time, either the first active time stamp in the entry, or, if
  7653. none exist, by the first inactive one.
  7654. Capital letters will reverse the sort order.
  7655. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7656. called with point at the beginning of the record. It must return a
  7657. value that is compatible with COMPARE-FUNC, the function used to
  7658. compare entries.
  7659. Comparing entries ignores case by default. However, with an optional argument
  7660. WITH-CASE, the sorting considers case as well.
  7661. Sorting is done against the visible part of the headlines, it ignores hidden
  7662. links.
  7663. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7664. A non-nil value for INTERACTIVE? is used to signal that this
  7665. function is being called interactively."
  7666. (interactive (list current-prefix-arg nil nil nil nil t))
  7667. (let ((case-func (if with-case 'identity 'downcase))
  7668. start beg end stars re re2
  7669. txt what tmp)
  7670. ;; Find beginning and end of region to sort
  7671. (cond
  7672. ((org-region-active-p)
  7673. ;; we will sort the region
  7674. (setq end (region-end)
  7675. what "region")
  7676. (goto-char (region-beginning))
  7677. (unless (org-at-heading-p) (outline-next-heading))
  7678. (setq start (point)))
  7679. ((or (org-at-heading-p)
  7680. (ignore-errors (progn (org-back-to-heading) t)))
  7681. ;; we will sort the children of the current headline
  7682. (org-back-to-heading)
  7683. (setq start (point)
  7684. end (progn (org-end-of-subtree t t)
  7685. (or (bolp) (insert "\n"))
  7686. (when (>= (org-back-over-empty-lines) 1)
  7687. (forward-line 1))
  7688. (point))
  7689. what "children")
  7690. (goto-char start)
  7691. (outline-show-subtree)
  7692. (outline-next-heading))
  7693. (t
  7694. ;; we will sort the top-level entries in this file
  7695. (goto-char (point-min))
  7696. (or (org-at-heading-p) (outline-next-heading))
  7697. (setq start (point))
  7698. (goto-char (point-max))
  7699. (beginning-of-line 1)
  7700. (when (looking-at ".*?\\S-")
  7701. ;; File ends in a non-white line
  7702. (end-of-line 1)
  7703. (insert "\n"))
  7704. (setq end (point-max))
  7705. (setq what "top-level")
  7706. (goto-char start)
  7707. (org-show-all '(headings blocks))))
  7708. (setq beg (point))
  7709. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7710. (looking-at "\\(\\*+\\)")
  7711. (setq stars (match-string 1)
  7712. re (concat "^" (regexp-quote stars) " +")
  7713. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7714. txt (buffer-substring beg end))
  7715. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7716. (when (and (not (equal stars "*")) (string-match re2 txt))
  7717. (user-error "Region to sort contains a level above the first entry"))
  7718. (unless sorting-type
  7719. (message
  7720. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7721. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7722. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7723. what)
  7724. (setq sorting-type (read-char-exclusive)))
  7725. (unless getkey-func
  7726. (and (= (downcase sorting-type) ?f)
  7727. (setq getkey-func
  7728. (or (and interactive?
  7729. (org-read-function
  7730. "Function for extracting keys: "))
  7731. (error "Missing key extractor")))))
  7732. (and (= (downcase sorting-type) ?r)
  7733. (not property)
  7734. (setq property
  7735. (completing-read "Property: "
  7736. (mapcar #'list (org-buffer-property-keys t))
  7737. nil t)))
  7738. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7739. (message "Sorting entries...")
  7740. (save-restriction
  7741. (narrow-to-region start end)
  7742. (let ((restore-clock?
  7743. ;; The clock marker is lost when using `sort-subr'; mark
  7744. ;; the clock with temporary `:org-clock-marker-backup'
  7745. ;; text property.
  7746. (when (and (eq (org-clock-is-active) (current-buffer))
  7747. (<= start (marker-position org-clock-marker))
  7748. (>= end (marker-position org-clock-marker)))
  7749. (org-with-silent-modifications
  7750. (put-text-property (1- org-clock-marker) org-clock-marker
  7751. :org-clock-marker-backup t))
  7752. t))
  7753. (dcst (downcase sorting-type))
  7754. (case-fold-search nil)
  7755. (now (current-time)))
  7756. (org-preserve-local-variables
  7757. (sort-subr
  7758. (/= dcst sorting-type)
  7759. ;; This function moves to the beginning character of the
  7760. ;; "record" to be sorted.
  7761. (lambda nil
  7762. (if (re-search-forward re nil t)
  7763. (goto-char (match-beginning 0))
  7764. (goto-char (point-max))))
  7765. ;; This function moves to the last character of the "record" being
  7766. ;; sorted.
  7767. (lambda nil
  7768. (save-match-data
  7769. (condition-case nil
  7770. (outline-forward-same-level 1)
  7771. (error
  7772. (goto-char (point-max))))))
  7773. ;; This function returns the value that gets sorted against.
  7774. (lambda ()
  7775. (cond
  7776. ((= dcst ?n)
  7777. (if (looking-at org-complex-heading-regexp)
  7778. (string-to-number
  7779. (org-sort-remove-invisible (match-string 4)))
  7780. nil))
  7781. ((= dcst ?a)
  7782. (if (looking-at org-complex-heading-regexp)
  7783. (funcall case-func
  7784. (org-sort-remove-invisible (match-string 4)))
  7785. nil))
  7786. ((= dcst ?k)
  7787. (or (get-text-property (point) :org-clock-minutes) 0))
  7788. ((= dcst ?t)
  7789. (let ((end (save-excursion (outline-next-heading) (point))))
  7790. (if (or (re-search-forward org-ts-regexp end t)
  7791. (re-search-forward org-ts-regexp-both end t))
  7792. (org-time-string-to-seconds (match-string 0))
  7793. (float-time now))))
  7794. ((= dcst ?c)
  7795. (let ((end (save-excursion (outline-next-heading) (point))))
  7796. (if (re-search-forward
  7797. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7798. end t)
  7799. (org-time-string-to-seconds (match-string 0))
  7800. (float-time now))))
  7801. ((= dcst ?s)
  7802. (let ((end (save-excursion (outline-next-heading) (point))))
  7803. (if (re-search-forward org-scheduled-time-regexp end t)
  7804. (org-time-string-to-seconds (match-string 1))
  7805. (float-time now))))
  7806. ((= dcst ?d)
  7807. (let ((end (save-excursion (outline-next-heading) (point))))
  7808. (if (re-search-forward org-deadline-time-regexp end t)
  7809. (org-time-string-to-seconds (match-string 1))
  7810. (float-time now))))
  7811. ((= dcst ?p)
  7812. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7813. (string-to-char (match-string 2))
  7814. org-default-priority))
  7815. ((= dcst ?r)
  7816. (or (org-entry-get nil property) ""))
  7817. ((= dcst ?o)
  7818. (when (looking-at org-complex-heading-regexp)
  7819. (let* ((m (match-string 2))
  7820. (s (if (member m org-done-keywords) '- '+)))
  7821. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7822. ((= dcst ?f)
  7823. (if getkey-func
  7824. (progn
  7825. (setq tmp (funcall getkey-func))
  7826. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7827. tmp)
  7828. (error "Invalid key function `%s'" getkey-func)))
  7829. (t (error "Invalid sorting type `%c'" sorting-type))))
  7830. nil
  7831. (cond
  7832. ((= dcst ?a) 'string<)
  7833. ((= dcst ?f)
  7834. (or compare-func
  7835. (and interactive?
  7836. (org-read-function
  7837. (concat "Function for comparing keys "
  7838. "(empty for default `sort-subr' predicate): ")
  7839. 'allow-empty))))
  7840. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7841. (when restore-clock?
  7842. (move-marker org-clock-marker
  7843. (1+ (next-single-property-change
  7844. start :org-clock-marker-backup)))
  7845. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7846. '(:org-clock-marker-backup t)))))
  7847. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7848. (message "Sorting entries...done")))
  7849. (defun org-contextualize-keys (alist contexts)
  7850. "Return valid elements in ALIST depending on CONTEXTS.
  7851. `org-agenda-custom-commands' or `org-capture-templates' are the
  7852. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7853. or `org-capture-templates-contexts' are the associated contexts
  7854. definitions."
  7855. (let ((contexts
  7856. ;; normalize contexts
  7857. (mapcar
  7858. (lambda(c) (cond ((listp (cadr c))
  7859. (list (car c) (car c) (nth 1 c)))
  7860. ((string= "" (cadr c))
  7861. (list (car c) (car c) (nth 2 c)))
  7862. (t c)))
  7863. contexts))
  7864. (a alist) r s)
  7865. ;; loop over all commands or templates
  7866. (dolist (c a)
  7867. (let (vrules repl)
  7868. (cond
  7869. ((not (assoc (car c) contexts))
  7870. (push c r))
  7871. ((and (assoc (car c) contexts)
  7872. (setq vrules (org-contextualize-validate-key
  7873. (car c) contexts)))
  7874. (mapc (lambda (vr)
  7875. (unless (equal (car vr) (cadr vr))
  7876. (setq repl vr)))
  7877. vrules)
  7878. (if (not repl) (push c r)
  7879. (push (cadr repl) s)
  7880. (push
  7881. (cons (car c)
  7882. (cdr (or (assoc (cadr repl) alist)
  7883. (error "Undefined key `%s' as contextual replacement for `%s'"
  7884. (cadr repl) (car c)))))
  7885. r))))))
  7886. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7887. (delq
  7888. nil
  7889. (delete-dups
  7890. (mapcar (lambda (x)
  7891. (let ((tpl (car x)))
  7892. (unless (delq
  7893. nil
  7894. (mapcar (lambda (y)
  7895. (equal y tpl))
  7896. s))
  7897. x)))
  7898. (reverse r))))))
  7899. (defun org-contextualize-validate-key (key contexts)
  7900. "Check CONTEXTS for agenda or capture KEY."
  7901. (let (res)
  7902. (dolist (r contexts)
  7903. (dolist (rr (car (last r)))
  7904. (when
  7905. (and (equal key (car r))
  7906. (if (functionp rr) (funcall rr)
  7907. (or (and (eq (car rr) 'in-file)
  7908. (buffer-file-name)
  7909. (string-match (cdr rr) (buffer-file-name)))
  7910. (and (eq (car rr) 'in-mode)
  7911. (string-match (cdr rr) (symbol-name major-mode)))
  7912. (and (eq (car rr) 'in-buffer)
  7913. (string-match (cdr rr) (buffer-name)))
  7914. (when (and (eq (car rr) 'not-in-file)
  7915. (buffer-file-name))
  7916. (not (string-match (cdr rr) (buffer-file-name))))
  7917. (when (eq (car rr) 'not-in-mode)
  7918. (not (string-match (cdr rr) (symbol-name major-mode))))
  7919. (when (eq (car rr) 'not-in-buffer)
  7920. (not (string-match (cdr rr) (buffer-name)))))))
  7921. (push r res))))
  7922. (delete-dups (delq nil res))))
  7923. (defun org-context-p (&rest contexts)
  7924. "Check if local context is any of CONTEXTS.
  7925. Possible values in the list of contexts are `table', `headline', and `item'."
  7926. (let ((pos (point)))
  7927. (goto-char (point-at-bol))
  7928. (prog1 (or (and (memq 'table contexts)
  7929. (looking-at "[ \t]*|"))
  7930. (and (memq 'headline contexts)
  7931. (looking-at org-outline-regexp))
  7932. (and (memq 'item contexts)
  7933. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  7934. (and (memq 'item-body contexts)
  7935. (org-in-item-p)))
  7936. (goto-char pos))))
  7937. ;;;###autoload
  7938. (defun org-run-like-in-org-mode (cmd)
  7939. "Run a command, pretending that the current buffer is in Org mode.
  7940. This will temporarily bind local variables that are typically bound in
  7941. Org mode to the values they have in Org mode, and then interactively
  7942. call CMD."
  7943. (org-load-modules-maybe)
  7944. (let (binds)
  7945. (dolist (var (org-get-local-variables))
  7946. (when (or (not (boundp (car var)))
  7947. (eq (symbol-value (car var))
  7948. (default-value (car var))))
  7949. (push (list (car var) `(quote ,(cadr var))) binds)))
  7950. (eval `(let ,binds
  7951. (call-interactively (quote ,cmd))))))
  7952. (defun org-get-category (&optional pos force-refresh)
  7953. "Get the category applying to position POS."
  7954. (save-match-data
  7955. (when force-refresh (org-refresh-category-properties))
  7956. (let ((pos (or pos (point))))
  7957. (or (get-text-property pos 'org-category)
  7958. (progn (org-refresh-category-properties)
  7959. (get-text-property pos 'org-category))))))
  7960. ;;; Refresh properties
  7961. (defun org-refresh-properties (dprop tprop)
  7962. "Refresh buffer text properties.
  7963. DPROP is the drawer property and TPROP is either the
  7964. corresponding text property to set, or an alist with each element
  7965. being a text property (as a symbol) and a function to apply to
  7966. the value of the drawer property."
  7967. (let* ((case-fold-search t)
  7968. (inhibit-read-only t)
  7969. (inherit? (org-property-inherit-p dprop))
  7970. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7971. (global (and inherit? (org--property-global-value dprop nil))))
  7972. (org-with-silent-modifications
  7973. (org-with-point-at 1
  7974. ;; Set global values (e.g., values defined through
  7975. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7976. (when global (put-text-property (point-min) (point-max) tprop global))
  7977. ;; Set local values.
  7978. (while (re-search-forward property-re nil t)
  7979. (when (org-at-property-p)
  7980. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7981. (outline-next-heading))))))
  7982. (defun org-refresh-property (tprop p &optional inherit)
  7983. "Refresh the buffer text property TPROP from the drawer property P.
  7984. The refresh happens only for the current headline, or the whole
  7985. sub-tree if optional argument INHERIT is non-nil."
  7986. (unless (org-before-first-heading-p)
  7987. (save-excursion
  7988. (org-back-to-heading t)
  7989. (let ((start (point))
  7990. (end (save-excursion
  7991. (if inherit (org-end-of-subtree t t)
  7992. (or (outline-next-heading) (point-max))))))
  7993. (if (symbolp tprop)
  7994. ;; TPROP is a text property symbol.
  7995. (put-text-property start end tprop p)
  7996. ;; TPROP is an alist with (property . function) elements.
  7997. (pcase-dolist (`(,prop . ,f) tprop)
  7998. (put-text-property start end prop (funcall f p))))))))
  7999. (defun org-refresh-category-properties ()
  8000. "Refresh category text properties in the buffer."
  8001. (let ((case-fold-search t)
  8002. (inhibit-read-only t)
  8003. (default-category
  8004. (cond ((null org-category)
  8005. (if buffer-file-name
  8006. (file-name-sans-extension
  8007. (file-name-nondirectory buffer-file-name))
  8008. "???"))
  8009. ((symbolp org-category) (symbol-name org-category))
  8010. (t org-category))))
  8011. (org-with-silent-modifications
  8012. (org-with-wide-buffer
  8013. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8014. ;; This is the default category for the buffer. If none is
  8015. ;; found, fall-back to `org-category' or buffer file name.
  8016. (put-text-property
  8017. (point-min) (point-max)
  8018. 'org-category
  8019. (catch 'buffer-category
  8020. (goto-char (point-max))
  8021. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8022. (let ((element (org-element-at-point)))
  8023. (when (eq (org-element-type element) 'keyword)
  8024. (throw 'buffer-category
  8025. (org-element-property :value element)))))
  8026. default-category))
  8027. ;; Set sub-tree specific categories.
  8028. (goto-char (point-min))
  8029. (let ((regexp (org-re-property "CATEGORY")))
  8030. (while (re-search-forward regexp nil t)
  8031. (let ((value (match-string-no-properties 3)))
  8032. (when (org-at-property-p)
  8033. (put-text-property
  8034. (save-excursion (org-back-to-heading t) (point))
  8035. (save-excursion (org-end-of-subtree t t) (point))
  8036. 'org-category
  8037. value)))))))))
  8038. (defun org-refresh-stats-properties ()
  8039. "Refresh stats text properties in the buffer."
  8040. (org-with-silent-modifications
  8041. (org-with-point-at 1
  8042. (let ((regexp (concat org-outline-regexp-bol
  8043. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8044. (while (re-search-forward regexp nil t)
  8045. (let* ((numerator (string-to-number (match-string 1)))
  8046. (denominator (and (match-end 2)
  8047. (string-to-number (match-string 2))))
  8048. (stats (cond ((not denominator) numerator) ;percent
  8049. ((= denominator 0) 0)
  8050. (t (/ (* numerator 100) denominator)))))
  8051. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8052. 'org-stats stats)))))))
  8053. (defun org-refresh-effort-properties ()
  8054. "Refresh effort properties"
  8055. (org-refresh-properties
  8056. org-effort-property
  8057. '((effort . identity)
  8058. (effort-minutes . org-duration-to-minutes))))
  8059. ;;;; Link Stuff
  8060. ;;; Link abbreviations
  8061. (defun org-link-expand-abbrev (link)
  8062. "Apply replacements as defined in `org-link-abbrev-alist'."
  8063. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8064. (let* ((key (match-string 1 link))
  8065. (as (or (assoc key org-link-abbrev-alist-local)
  8066. (assoc key org-link-abbrev-alist)))
  8067. (tag (and (match-end 2) (match-string 3 link)))
  8068. rpl)
  8069. (if (not as)
  8070. link
  8071. (setq rpl (cdr as))
  8072. (cond
  8073. ((symbolp rpl) (funcall rpl tag))
  8074. ((string-match "%(\\([^)]+\\))" rpl)
  8075. (replace-match
  8076. (save-match-data
  8077. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8078. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8079. ((string-match "%h" rpl)
  8080. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8081. (t (concat rpl tag)))))
  8082. link))
  8083. ;;; Storing and inserting links
  8084. (defvar org-insert-link-history nil
  8085. "Minibuffer history for links inserted with `org-insert-link'.")
  8086. (defvar org-stored-links nil
  8087. "Contains the links stored with `org-store-link'.")
  8088. (defvar org-store-link-plist nil
  8089. "Plist with info about the most recently link created with `org-store-link'.")
  8090. (defun org-store-link-functions ()
  8091. "Return a list of functions that are called to create and store a link.
  8092. The functions defined in the :store property of
  8093. `org-link-parameters'.
  8094. Each function will be called in turn until one returns a non-nil
  8095. value. Each function should check if it is responsible for
  8096. creating this link (for example by looking at the major mode).
  8097. If not, it must exit and return nil. If yes, it should return
  8098. a non-nil value after calling `org-store-link-props' with a list
  8099. of properties and values. Special properties are:
  8100. :type The link prefix, like \"http\". This must be given.
  8101. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8102. This is obligatory as well.
  8103. :description Optional default description for the second pair
  8104. of brackets in an Org mode link. The user can still change
  8105. this when inserting this link into an Org mode buffer.
  8106. In addition to these, any additional properties can be specified
  8107. and then used in capture templates."
  8108. (cl-loop for link in org-link-parameters
  8109. with store-func
  8110. do (setq store-func (org-link-get-parameter (car link) :store))
  8111. if store-func
  8112. collect store-func))
  8113. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8114. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8115. ;;;###autoload
  8116. (defun org-store-link (arg &optional interactive?)
  8117. "Store an org-link to the current location.
  8118. \\<org-mode-map>
  8119. This link is added to `org-stored-links' and can later be inserted
  8120. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8121. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8122. A single
  8123. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8124. `org-gnus-prefer-web-links' for links to Usenet articles.
  8125. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8126. skipping storing functions that are not
  8127. part of Org core.
  8128. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8129. prefix ARG forces storing a link for each line in the
  8130. active region.
  8131. Assume the function is called interactively if INTERACTIVE? is
  8132. non-nil."
  8133. (interactive "P\np")
  8134. (org-load-modules-maybe)
  8135. (if (and (equal arg '(64)) (org-region-active-p))
  8136. (save-excursion
  8137. (let ((end (region-end)))
  8138. (goto-char (region-beginning))
  8139. (set-mark (point))
  8140. (while (< (point-at-eol) end)
  8141. (move-end-of-line 1) (activate-mark)
  8142. (let (current-prefix-arg)
  8143. (call-interactively 'org-store-link))
  8144. (move-beginning-of-line 2)
  8145. (set-mark (point)))))
  8146. (setq org-store-link-plist nil)
  8147. (let (link cpltxt desc description search txt custom-id agenda-link)
  8148. (cond
  8149. ;; Store a link using an external link type, if any function is
  8150. ;; available. If more than one can generate a link from current
  8151. ;; location, ask which one to use.
  8152. ((and (not (equal arg '(16)))
  8153. (let ((results-alist nil))
  8154. (dolist (f (org-store-link-functions))
  8155. (when (funcall f)
  8156. ;; XXX: return value is not link's plist, so we
  8157. ;; store the new value before it is modified. It
  8158. ;; would be cleaner to ask store link functions to
  8159. ;; return the plist instead.
  8160. (push (cons f (copy-sequence org-store-link-plist))
  8161. results-alist)))
  8162. (pcase results-alist
  8163. (`nil nil)
  8164. (`((,_ . ,_)) t) ;single choice: nothing to do
  8165. (`((,name . ,_) . ,_)
  8166. ;; Reinstate link plist associated to the chosen
  8167. ;; function.
  8168. (apply #'org-store-link-props
  8169. (cdr (assoc-string
  8170. (completing-read
  8171. "Which function for creating the link? "
  8172. (mapcar #'car results-alist)
  8173. nil t (symbol-name name))
  8174. results-alist)))
  8175. t))))
  8176. (setq link (plist-get org-store-link-plist :link))
  8177. (setq desc (or (plist-get org-store-link-plist :description)
  8178. link)))
  8179. ;; Store a link from a source code buffer.
  8180. ((org-src-edit-buffer-p)
  8181. (let ((coderef-format (org-src-coderef-format)))
  8182. (cond ((org-match-line (org-src-coderef-regexp coderef-format))
  8183. (setq link (format "(%s)" (match-string-no-properties 3))))
  8184. (interactive?
  8185. (let ((label (read-string "Code line label: ")))
  8186. (end-of-line)
  8187. (setq link (format coderef-format label))
  8188. (let ((gc (- 79 (length link))))
  8189. (if (< (current-column) gc)
  8190. (org-move-to-column gc t)
  8191. (insert " ")))
  8192. (insert link)
  8193. (setq link (concat "(" label ")"))
  8194. (setq desc nil)))
  8195. (t (setq link nil)))))
  8196. ;; We are in the agenda, link to referenced location
  8197. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8198. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8199. (get-text-property (point) 'org-marker))))
  8200. (when m
  8201. (org-with-point-at m
  8202. (setq agenda-link (org-store-link nil interactive?))))))
  8203. ((eq major-mode 'calendar-mode)
  8204. (let ((cd (calendar-cursor-to-date)))
  8205. (setq link
  8206. (format-time-string
  8207. (car org-time-stamp-formats)
  8208. (apply 'encode-time
  8209. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8210. nil nil nil))))
  8211. (org-store-link-props :type "calendar" :date cd)))
  8212. ((eq major-mode 'help-mode)
  8213. (setq link (concat "help:" (save-excursion
  8214. (goto-char (point-min))
  8215. (looking-at "^[^ ]+")
  8216. (match-string 0))))
  8217. (org-store-link-props :type "help"))
  8218. ((eq major-mode 'w3-mode)
  8219. (setq cpltxt (if (and (buffer-name)
  8220. (not (string-match "Untitled" (buffer-name))))
  8221. (buffer-name)
  8222. (url-view-url t))
  8223. link (url-view-url t))
  8224. (org-store-link-props :type "w3" :url (url-view-url t)))
  8225. ((eq major-mode 'image-mode)
  8226. (setq cpltxt (concat "file:"
  8227. (abbreviate-file-name buffer-file-name))
  8228. link cpltxt)
  8229. (org-store-link-props :type "image" :file buffer-file-name))
  8230. ;; In dired, store a link to the file of the current line
  8231. ((derived-mode-p 'dired-mode)
  8232. (let ((file (dired-get-filename nil t)))
  8233. (setq file (if file
  8234. (abbreviate-file-name
  8235. (expand-file-name (dired-get-filename nil t)))
  8236. ;; otherwise, no file so use current directory.
  8237. default-directory))
  8238. (setq cpltxt (concat "file:" file)
  8239. link cpltxt)))
  8240. ((setq search (run-hook-with-args-until-success
  8241. 'org-create-file-search-functions))
  8242. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8243. "::" search))
  8244. (setq cpltxt (or description link)))
  8245. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8246. (org-with-limited-levels
  8247. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8248. (cond
  8249. ;; Store a link using the target at point
  8250. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8251. (setq cpltxt
  8252. (concat "file:"
  8253. (abbreviate-file-name
  8254. (buffer-file-name (buffer-base-buffer)))
  8255. "::" (match-string 1))
  8256. link cpltxt))
  8257. ((and (featurep 'org-id)
  8258. (or (eq org-id-link-to-org-use-id t)
  8259. (and interactive?
  8260. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8261. (and (eq org-id-link-to-org-use-id
  8262. 'create-if-interactive-and-no-custom-id)
  8263. (not custom-id))))
  8264. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8265. ;; Store a link using the ID at point
  8266. (setq link (condition-case nil
  8267. (prog1 (org-id-store-link)
  8268. (setq desc (or (plist-get org-store-link-plist
  8269. :description)
  8270. "")))
  8271. (error
  8272. ;; Probably before first headline, link only to file
  8273. (concat "file:"
  8274. (abbreviate-file-name
  8275. (buffer-file-name (buffer-base-buffer))))))))
  8276. (t
  8277. ;; Just link to current headline
  8278. (setq cpltxt (concat "file:"
  8279. (abbreviate-file-name
  8280. (buffer-file-name (buffer-base-buffer)))))
  8281. ;; Add a context search string
  8282. (when (org-xor org-context-in-file-links
  8283. (equal arg '(4)))
  8284. (let* ((element (org-element-at-point))
  8285. (name (org-element-property :name element)))
  8286. (setq txt (cond
  8287. ((org-at-heading-p) nil)
  8288. (name)
  8289. ((org-region-active-p)
  8290. (buffer-substring (region-beginning) (region-end)))))
  8291. (when (or (null txt) (string-match "\\S-" txt))
  8292. (setq cpltxt
  8293. (concat cpltxt "::"
  8294. (condition-case nil
  8295. (org-make-org-heading-search-string txt)
  8296. (error "")))
  8297. desc (or name
  8298. (nth 4 (ignore-errors (org-heading-components)))
  8299. "NONE")))))
  8300. (when (string-match "::\\'" cpltxt)
  8301. (setq cpltxt (substring cpltxt 0 -2)))
  8302. (setq link cpltxt)))))
  8303. ((buffer-file-name (buffer-base-buffer))
  8304. ;; Just link to this file here.
  8305. (setq cpltxt (concat "file:"
  8306. (abbreviate-file-name
  8307. (buffer-file-name (buffer-base-buffer)))))
  8308. ;; Add a context string.
  8309. (when (org-xor org-context-in-file-links
  8310. (equal arg '(4)))
  8311. (setq txt (if (org-region-active-p)
  8312. (buffer-substring (region-beginning) (region-end))
  8313. (buffer-substring (point-at-bol) (point-at-eol))))
  8314. ;; Only use search option if there is some text.
  8315. (when (string-match "\\S-" txt)
  8316. (setq cpltxt
  8317. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8318. desc "NONE")))
  8319. (setq link cpltxt))
  8320. (interactive?
  8321. (user-error "No method for storing a link from this buffer"))
  8322. (t (setq link nil)))
  8323. ;; We're done setting link and desc, clean up
  8324. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8325. (setq link (or link cpltxt)
  8326. desc (or desc cpltxt))
  8327. (cond ((not desc))
  8328. ((equal desc "NONE") (setq desc nil))
  8329. (t (setq desc
  8330. (replace-regexp-in-string
  8331. org-bracket-link-analytic-regexp
  8332. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8333. desc))))
  8334. ;; Return the link
  8335. (if (not (and interactive? link))
  8336. (or agenda-link (and link (org-make-link-string link desc)))
  8337. (push (list link desc) org-stored-links)
  8338. (message "Stored: %s" (or desc link))
  8339. (when custom-id
  8340. (setq link (concat "file:" (abbreviate-file-name
  8341. (buffer-file-name)) "::#" custom-id))
  8342. (push (list link desc) org-stored-links))
  8343. (car org-stored-links)))))
  8344. (defun org-store-link-props (&rest plist)
  8345. "Store link properties.
  8346. The properties are pre-processed by extracting names, addresses
  8347. and dates."
  8348. (let ((x (plist-get plist :from)))
  8349. (when x
  8350. (let ((adr (mail-extract-address-components x)))
  8351. (setq plist (plist-put plist :fromname (car adr)))
  8352. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8353. (let ((x (plist-get plist :to)))
  8354. (when x
  8355. (let ((adr (mail-extract-address-components x)))
  8356. (setq plist (plist-put plist :toname (car adr)))
  8357. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8358. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8359. (when x
  8360. (setq plist (plist-put plist :date-timestamp
  8361. (format-time-string
  8362. (org-time-stamp-format t) x)))
  8363. (setq plist (plist-put plist :date-timestamp-inactive
  8364. (format-time-string
  8365. (org-time-stamp-format t t) x)))))
  8366. (let ((from (plist-get plist :from))
  8367. (to (plist-get plist :to)))
  8368. (when (and from to org-from-is-user-regexp)
  8369. (setq plist
  8370. (plist-put plist :fromto
  8371. (if (string-match org-from-is-user-regexp from)
  8372. (concat "to %t")
  8373. (concat "from %f"))))))
  8374. (setq org-store-link-plist plist))
  8375. (defun org-add-link-props (&rest plist)
  8376. "Add these properties to the link property list."
  8377. (let (key value)
  8378. (while plist
  8379. (setq key (pop plist) value (pop plist))
  8380. (setq org-store-link-plist
  8381. (plist-put org-store-link-plist key value)))))
  8382. (defun org-email-link-description (&optional fmt)
  8383. "Return the description part of an email link.
  8384. This takes information from `org-store-link-plist' and formats it
  8385. according to FMT (default from `org-email-link-description-format')."
  8386. (setq fmt (or fmt org-email-link-description-format))
  8387. (let* ((p org-store-link-plist)
  8388. (to (plist-get p :toaddress))
  8389. (from (plist-get p :fromaddress))
  8390. (table
  8391. (list
  8392. (cons "%c" (plist-get p :fromto))
  8393. (cons "%F" (plist-get p :from))
  8394. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8395. (cons "%T" (plist-get p :to))
  8396. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8397. (cons "%s" (plist-get p :subject))
  8398. (cons "%d" (plist-get p :date))
  8399. (cons "%m" (plist-get p :message-id)))))
  8400. (when (string-match "%c" fmt)
  8401. ;; Check if the user wrote this message
  8402. (if (and org-from-is-user-regexp from to
  8403. (save-match-data (string-match org-from-is-user-regexp from)))
  8404. (setq fmt (replace-match "to %t" t t fmt))
  8405. (setq fmt (replace-match "from %f" t t fmt))))
  8406. (org-replace-escapes fmt table)))
  8407. (defun org-make-org-heading-search-string (&optional string)
  8408. "Make search string for the current headline or STRING."
  8409. (let ((s (or string
  8410. (and (derived-mode-p 'org-mode)
  8411. (save-excursion
  8412. (org-back-to-heading t)
  8413. (org-element-property :raw-value (org-element-at-point))))))
  8414. (lines org-context-in-file-links))
  8415. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8416. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8417. (when (and string (integerp lines) (> lines 0))
  8418. (let ((slines (org-split-string s "\n")))
  8419. (when (< lines (length slines))
  8420. (setq s (mapconcat
  8421. 'identity
  8422. (reverse (nthcdr (- (length slines) lines)
  8423. (reverse slines))) "\n")))))
  8424. (mapconcat #'identity (split-string s) " ")))
  8425. (defconst org-link-escape-chars
  8426. ;;%20 %5B %5D %25
  8427. '(?\s ?\[ ?\] ?%)
  8428. "List of characters that should be escaped in a link when stored to Org.
  8429. This is the list that is used for internal purposes.")
  8430. (defun org-make-link-string (link &optional description)
  8431. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8432. (unless (org-string-nw-p link) (error "Empty link"))
  8433. (let ((uri (cond ((string-match org-link-types-re link)
  8434. (concat (match-string 1 link)
  8435. (org-link-escape (substring link (match-end 1)))))
  8436. ((or (file-name-absolute-p link)
  8437. (string-match-p "\\`\\.\\.?/" link))
  8438. (org-link-escape link))
  8439. ;; For readability, do not encode space characters
  8440. ;; in fuzzy links.
  8441. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8442. (description
  8443. (and (org-string-nw-p description)
  8444. ;; Remove brackets from description, as they are fatal.
  8445. (replace-regexp-in-string
  8446. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8447. (org-trim description)))))
  8448. (format "[[%s]%s]"
  8449. uri
  8450. (if description (format "[%s]" description) ""))))
  8451. (defun org-link-escape (text &optional table merge)
  8452. "Return percent escaped representation of TEXT.
  8453. TEXT is a string with the text to escape.
  8454. Optional argument TABLE is a list with characters that should be
  8455. escaped. When nil, `org-link-escape-chars' is used.
  8456. If optional argument MERGE is set, merge TABLE into
  8457. `org-link-escape-chars'."
  8458. (let ((characters-to-encode
  8459. (cond ((null table) org-link-escape-chars)
  8460. (merge (append org-link-escape-chars table))
  8461. (t table))))
  8462. (mapconcat
  8463. (lambda (c)
  8464. (if (or (memq c characters-to-encode)
  8465. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8466. (mapconcat (lambda (e) (format "%%%.2X" e))
  8467. (or (encode-coding-char c 'utf-8)
  8468. (error "Unable to percent escape character: %c" c))
  8469. "")
  8470. (char-to-string c)))
  8471. text "")))
  8472. (defun org-link-unescape (str)
  8473. "Unhex hexified Unicode parts in string STR.
  8474. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8475. reciprocal of `org-link-escape', which see."
  8476. (if (org-string-nw-p str)
  8477. (replace-regexp-in-string
  8478. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8479. str))
  8480. (defun org-link-unescape-compound (hex)
  8481. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8482. Note: this function also decodes single byte encodings like
  8483. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8484. (save-match-data
  8485. (let* ((bytes (cdr (split-string hex "%")))
  8486. (ret "")
  8487. (eat 0)
  8488. (sum 0))
  8489. (while bytes
  8490. (let* ((val (string-to-number (pop bytes) 16))
  8491. (shift-xor
  8492. (if (= 0 eat)
  8493. (cond
  8494. ((>= val 252) (cons 6 252))
  8495. ((>= val 248) (cons 5 248))
  8496. ((>= val 240) (cons 4 240))
  8497. ((>= val 224) (cons 3 224))
  8498. ((>= val 192) (cons 2 192))
  8499. (t (cons 0 0)))
  8500. (cons 6 128))))
  8501. (when (>= val 192) (setq eat (car shift-xor)))
  8502. (setq val (logxor val (cdr shift-xor)))
  8503. (setq sum (+ (lsh sum (car shift-xor)) val))
  8504. (when (> eat 0) (setq eat (- eat 1)))
  8505. (cond
  8506. ((= 0 eat) ;multi byte
  8507. (setq ret (concat ret (char-to-string sum)))
  8508. (setq sum 0))
  8509. ((not bytes) ; single byte(s)
  8510. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8511. ret)))
  8512. (defun org-link-unescape-single-byte-sequence (hex)
  8513. "Unhexify hex-encoded single byte character sequences."
  8514. (mapconcat (lambda (byte)
  8515. (char-to-string (string-to-number byte 16)))
  8516. (cdr (split-string hex "%")) ""))
  8517. (defun org-fixup-message-id-for-http (s)
  8518. "Replace special characters in a message id, so it can be used in an http query."
  8519. (when (string-match "%" s)
  8520. (setq s (mapconcat (lambda (c)
  8521. (if (eq c ?%)
  8522. "%25"
  8523. (char-to-string c)))
  8524. s "")))
  8525. (while (string-match "<" s)
  8526. (setq s (replace-match "%3C" t t s)))
  8527. (while (string-match ">" s)
  8528. (setq s (replace-match "%3E" t t s)))
  8529. (while (string-match "@" s)
  8530. (setq s (replace-match "%40" t t s)))
  8531. s)
  8532. (defun org-link-prettify (link)
  8533. "Return a human-readable representation of LINK.
  8534. The car of LINK must be a raw link.
  8535. The cdr of LINK must be either a link description or nil."
  8536. (let ((desc (or (cadr link) "<no description>")))
  8537. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8538. "<" (car link) ">")))
  8539. ;;;###autoload
  8540. (defun org-insert-link-global ()
  8541. "Insert a link like Org mode does.
  8542. This command can be called in any mode to insert a link in Org syntax."
  8543. (interactive)
  8544. (org-load-modules-maybe)
  8545. (org-run-like-in-org-mode 'org-insert-link))
  8546. (defun org-insert-all-links (arg &optional pre post)
  8547. "Insert all links in `org-stored-links'.
  8548. When a universal prefix, do not delete the links from `org-stored-links'.
  8549. When `ARG' is a number, insert the last N link(s).
  8550. `PRE' and `POST' are optional arguments to define a string to
  8551. prepend or to append."
  8552. (interactive "P")
  8553. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8554. (links (copy-sequence org-stored-links))
  8555. (pr (or pre "- "))
  8556. (po (or post "\n"))
  8557. (cnt 1) l)
  8558. (if (null org-stored-links)
  8559. (message "No link to insert")
  8560. (while (and (or (listp arg) (>= arg cnt))
  8561. (setq l (if (listp arg)
  8562. (pop links)
  8563. (pop org-stored-links))))
  8564. (setq cnt (1+ cnt))
  8565. (insert pr)
  8566. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8567. (insert po)))))
  8568. (defun org-insert-last-stored-link (arg)
  8569. "Insert the last link stored in `org-stored-links'."
  8570. (interactive "p")
  8571. (org-insert-all-links arg "" "\n"))
  8572. (defun org-link-fontify-links-to-this-file ()
  8573. "Fontify links to the current file in `org-stored-links'."
  8574. (let ((f (buffer-file-name)) a b)
  8575. (setq a (mapcar (lambda(l)
  8576. (let ((ll (car l)))
  8577. (when (and (string-match "^file:\\(.+\\)::" ll)
  8578. (equal f (expand-file-name (match-string 1 ll))))
  8579. ll)))
  8580. org-stored-links))
  8581. (when (featurep 'org-id)
  8582. (setq b (mapcar (lambda(l)
  8583. (let ((ll (car l)))
  8584. (when (and (string-match "^id:\\(.+\\)$" ll)
  8585. (equal f (expand-file-name
  8586. (or (org-id-find-id-file
  8587. (match-string 1 ll)) ""))))
  8588. ll)))
  8589. org-stored-links)))
  8590. (mapcar (lambda(l)
  8591. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8592. (delq nil (append a b)))))
  8593. (defvar org--links-history nil)
  8594. (defun org-insert-link (&optional complete-file link-location default-description)
  8595. "Insert a link. At the prompt, enter the link.
  8596. Completion can be used to insert any of the link protocol prefixes in use.
  8597. The history can be used to select a link previously stored with
  8598. `org-store-link'. When the empty string is entered (i.e. if you just
  8599. press `RET' at the prompt), the link defaults to the most recently
  8600. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8601. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8602. You will also be prompted for a description, and if one is given, it will
  8603. be displayed in the buffer instead of the link.
  8604. If there is already a link at point, this command will allow you to edit
  8605. link and description parts.
  8606. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8607. file name can be
  8608. selected using completion. The path to the file will be relative to the
  8609. current directory if the file is in the current directory or a subdirectory.
  8610. Otherwise, the link will be the absolute path as completed in the minibuffer
  8611. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8612. option `org-link-file-path-type'.
  8613. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8614. absolute path even if the file is in
  8615. the current directory or below.
  8616. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8617. prefix negates `org-keep-stored-link-after-insertion'.
  8618. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8619. the link location instead of reading one interactively.
  8620. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8621. be used as the default description. Otherwise, if
  8622. `org-make-link-description-function' is non-nil, this function
  8623. will be called with the link target, and the result will be the
  8624. default link description. When called non-interactivily, don't
  8625. allow to edit the default description."
  8626. (interactive "P")
  8627. (let* ((wcf (current-window-configuration))
  8628. (origbuf (current-buffer))
  8629. (region (when (org-region-active-p)
  8630. (buffer-substring (region-beginning) (region-end))))
  8631. (remove (and region (list (region-beginning) (region-end))))
  8632. (desc region)
  8633. (link link-location)
  8634. (abbrevs org-link-abbrev-alist-local)
  8635. entry all-prefixes auto-desc)
  8636. (cond
  8637. (link-location) ; specified by arg, just use it.
  8638. ((org-in-regexp org-bracket-link-regexp 1)
  8639. ;; We do have a link at point, and we are going to edit it.
  8640. (setq remove (list (match-beginning 0) (match-end 0)))
  8641. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8642. (setq link (read-string "Link: "
  8643. (org-link-unescape
  8644. (match-string-no-properties 1)))))
  8645. ((or (org-in-regexp org-angle-link-re)
  8646. (org-in-regexp org-plain-link-re))
  8647. ;; Convert to bracket link
  8648. (setq remove (list (match-beginning 0) (match-end 0))
  8649. link (read-string "Link: "
  8650. (org-unbracket-string "<" ">" (match-string 0)))))
  8651. ((member complete-file '((4) (16)))
  8652. ;; Completing read for file names.
  8653. (setq link (org-file-complete-link complete-file)))
  8654. (t
  8655. ;; Read link, with completion for stored links.
  8656. (org-link-fontify-links-to-this-file)
  8657. (org-switch-to-buffer-other-window "*Org Links*")
  8658. (with-current-buffer "*Org Links*"
  8659. (erase-buffer)
  8660. (insert "Insert a link.
  8661. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8662. (when org-stored-links
  8663. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8664. (insert (mapconcat 'org-link-prettify
  8665. (reverse org-stored-links) "\n")))
  8666. (goto-char (point-min)))
  8667. (let ((cw (selected-window)))
  8668. (select-window (get-buffer-window "*Org Links*" 'visible))
  8669. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8670. (unless (pos-visible-in-window-p (point-max))
  8671. (org-fit-window-to-buffer))
  8672. (and (window-live-p cw) (select-window cw)))
  8673. (setq all-prefixes (append (mapcar 'car abbrevs)
  8674. (mapcar 'car org-link-abbrev-alist)
  8675. (org-link-types)))
  8676. (unwind-protect
  8677. ;; Fake a link history, containing the stored links.
  8678. (let ((org--links-history
  8679. (append (mapcar #'car org-stored-links)
  8680. org-insert-link-history)))
  8681. (setq link
  8682. (org-completing-read
  8683. "Link: "
  8684. (append
  8685. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8686. (mapcar #'car org-stored-links))
  8687. nil nil nil
  8688. 'org--links-history
  8689. (caar org-stored-links)))
  8690. (unless (org-string-nw-p link) (user-error "No link selected"))
  8691. (dolist (l org-stored-links)
  8692. (when (equal link (cadr l))
  8693. (setq link (car l))
  8694. (setq auto-desc t)))
  8695. (when (or (member link all-prefixes)
  8696. (and (equal ":" (substring link -1))
  8697. (member (substring link 0 -1) all-prefixes)
  8698. (setq link (substring link 0 -1))))
  8699. (setq link (with-current-buffer origbuf
  8700. (org-link-try-special-completion link)))))
  8701. (set-window-configuration wcf)
  8702. (kill-buffer "*Org Links*"))
  8703. (setq entry (assoc link org-stored-links))
  8704. (or entry (push link org-insert-link-history))
  8705. (setq desc (or desc (nth 1 entry)))))
  8706. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8707. (not org-keep-stored-link-after-insertion))
  8708. (setq org-stored-links (delq (assoc link org-stored-links)
  8709. org-stored-links)))
  8710. (when (and (string-match org-plain-link-re link)
  8711. (not (string-match org-ts-regexp link)))
  8712. ;; URL-like link, normalize the use of angular brackets.
  8713. (setq link (org-unbracket-string "<" ">" link)))
  8714. ;; Check if we are linking to the current file with a search
  8715. ;; option If yes, simplify the link by using only the search
  8716. ;; option.
  8717. (when (and buffer-file-name
  8718. (let ((case-fold-search nil))
  8719. (string-match "\\`file:\\(.+?\\)::" link)))
  8720. (let ((path (match-string-no-properties 1 link))
  8721. (search (substring-no-properties link (match-end 0))))
  8722. (save-match-data
  8723. (when (equal (file-truename buffer-file-name) (file-truename path))
  8724. ;; We are linking to this same file, with a search option
  8725. (setq link search)))))
  8726. ;; Check if we can/should use a relative path. If yes, simplify
  8727. ;; the link.
  8728. (let ((case-fold-search nil))
  8729. (when (string-match "\\`\\(file\\|docview\\):" link)
  8730. (let* ((type (match-string-no-properties 0 link))
  8731. (path-start (match-end 0))
  8732. (search (and (string-match "::\\(.*\\)\\'" link)
  8733. (match-string 1 link)))
  8734. (path
  8735. (if search
  8736. (substring-no-properties
  8737. link path-start (match-beginning 0))
  8738. (substring-no-properties link (match-end 0))))
  8739. (origpath path))
  8740. (cond
  8741. ((or (eq org-link-file-path-type 'absolute)
  8742. (equal complete-file '(16)))
  8743. (setq path (abbreviate-file-name (expand-file-name path))))
  8744. ((eq org-link-file-path-type 'noabbrev)
  8745. (setq path (expand-file-name path)))
  8746. ((eq org-link-file-path-type 'relative)
  8747. (setq path (file-relative-name path)))
  8748. (t
  8749. (save-match-data
  8750. (if (string-match (concat "^" (regexp-quote
  8751. (expand-file-name
  8752. (file-name-as-directory
  8753. default-directory))))
  8754. (expand-file-name path))
  8755. ;; We are linking a file with relative path name.
  8756. (setq path (substring (expand-file-name path)
  8757. (match-end 0)))
  8758. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8759. (setq link (concat type path (and search (concat "::" search))))
  8760. (when (equal desc origpath)
  8761. (setq desc path)))))
  8762. (unless auto-desc
  8763. (let ((initial-input
  8764. (cond
  8765. (default-description)
  8766. ((not org-make-link-description-function) desc)
  8767. (t (condition-case nil
  8768. (funcall org-make-link-description-function link desc)
  8769. (error
  8770. (message "Can't get link description from `%s'"
  8771. (symbol-name org-make-link-description-function))
  8772. (sit-for 2)
  8773. nil))))))
  8774. (setq desc (if (called-interactively-p 'any)
  8775. (read-string "Description: " initial-input)
  8776. initial-input))))
  8777. (unless (string-match "\\S-" desc) (setq desc nil))
  8778. (when remove (apply 'delete-region remove))
  8779. (insert (org-make-link-string link desc))
  8780. ;; Redisplay so as the new link has proper invisible characters.
  8781. (sit-for 0)))
  8782. (defun org-link-try-special-completion (type)
  8783. "If there is completion support for link type TYPE, offer it."
  8784. (let ((fun (org-link-get-parameter type :complete)))
  8785. (if (functionp fun)
  8786. (funcall fun)
  8787. (read-string "Link (no completion support): " (concat type ":")))))
  8788. (defun org-file-complete-link (&optional arg)
  8789. "Create a file link using completion."
  8790. (let ((file (read-file-name "File: "))
  8791. (pwd (file-name-as-directory (expand-file-name ".")))
  8792. (pwd1 (file-name-as-directory (abbreviate-file-name
  8793. (expand-file-name ".")))))
  8794. (cond ((equal arg '(16))
  8795. (concat "file:"
  8796. (abbreviate-file-name (expand-file-name file))))
  8797. ((string-match
  8798. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8799. (concat "file:" (match-string 1 file)))
  8800. ((string-match
  8801. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8802. (expand-file-name file))
  8803. (concat "file:"
  8804. (match-string 1 (expand-file-name file))))
  8805. (t (concat "file:" file)))))
  8806. ;;; Opening/following a link
  8807. (defvar org-link-search-failed nil)
  8808. (defvar org-open-link-functions nil
  8809. "Hook for functions finding a plain text link.
  8810. These functions must take a single argument, the link content.
  8811. They will be called for links that look like [[link text][description]]
  8812. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8813. like a filename (e.g. \"./blue.png\").
  8814. These functions will be called *before* Org attempts to resolve the
  8815. link by doing text searches in the current buffer - so if you want a
  8816. link \"[[target]]\" to still find \"<<target>>\", your function should
  8817. handle this as a special case.
  8818. When the function does handle the link, it must return a non-nil value.
  8819. If it decides that it is not responsible for this link, it must return
  8820. nil to indicate that that Org can continue with other options like
  8821. exact and fuzzy text search.")
  8822. (defun org-next-link (&optional search-backward)
  8823. "Move forward to the next link.
  8824. If the link is in hidden text, expose it."
  8825. (interactive "P")
  8826. (when (and org-link-search-failed (eq this-command last-command))
  8827. (goto-char (point-min))
  8828. (message "Link search wrapped back to beginning of buffer"))
  8829. (setq org-link-search-failed nil)
  8830. (let* ((pos (point))
  8831. (ct (org-context))
  8832. (a (assq :link ct))
  8833. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8834. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8835. ((looking-at org-any-link-re)
  8836. ;; Don't stay stuck at link without an org-link face
  8837. (forward-char (if search-backward -1 1))))
  8838. (if (funcall srch-fun org-any-link-re nil t)
  8839. (progn
  8840. (goto-char (match-beginning 0))
  8841. (when (org-invisible-p) (org-show-context)))
  8842. (goto-char pos)
  8843. (setq org-link-search-failed t)
  8844. (message "No further link found"))))
  8845. (defun org-previous-link ()
  8846. "Move backward to the previous link.
  8847. If the link is in hidden text, expose it."
  8848. (interactive)
  8849. (funcall 'org-next-link t))
  8850. (defun org-translate-link (s)
  8851. "Translate a link string if a translation function has been defined."
  8852. (with-temp-buffer
  8853. (insert (org-trim s))
  8854. (org-trim (org-element-interpret-data (org-element-context)))))
  8855. (defun org-translate-link-from-planner (type path)
  8856. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8857. This is still an experimental function, your mileage may vary."
  8858. (cond
  8859. ((member type '("http" "https" "news" "ftp"))
  8860. ;; standard Internet links are the same.
  8861. nil)
  8862. ((and (equal type "irc") (string-match "^//" path))
  8863. ;; Planner has two / at the beginning of an irc link, we have 1.
  8864. ;; We should have zero, actually....
  8865. (setq path (substring path 1)))
  8866. ((and (equal type "lisp") (string-match "^/" path))
  8867. ;; Planner has a slash, we do not.
  8868. (setq type "elisp" path (substring path 1)))
  8869. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8870. ;; A typical message link. Planner has the id after the final slash,
  8871. ;; we separate it with a hash mark
  8872. (setq path (concat (match-string 1 path) "#"
  8873. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8874. (cons type path))
  8875. (defun org-find-file-at-mouse (ev)
  8876. "Open file link or URL at mouse."
  8877. (interactive "e")
  8878. (mouse-set-point ev)
  8879. (org-open-at-point 'in-emacs))
  8880. (defun org-open-at-mouse (ev)
  8881. "Open file link or URL at mouse.
  8882. See the docstring of `org-open-file' for details."
  8883. (interactive "e")
  8884. (mouse-set-point ev)
  8885. (when (eq major-mode 'org-agenda-mode)
  8886. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8887. (org-open-at-point))
  8888. (defvar org-window-config-before-follow-link nil
  8889. "The window configuration before following a link.
  8890. This is saved in case the need arises to restore it.")
  8891. ;;;###autoload
  8892. (defun org-open-at-point-global ()
  8893. "Follow a link or time-stamp like Org mode does.
  8894. This command can be called in any mode to follow an external link
  8895. or a time-stamp that has Org mode syntax. Its behavior is
  8896. undefined when called on internal links (e.g., fuzzy links).
  8897. Raise an error when there is nothing to follow. "
  8898. (interactive)
  8899. (cond ((org-in-regexp org-any-link-re)
  8900. (org-open-link-from-string (match-string-no-properties 0)))
  8901. ((or (org-in-regexp org-ts-regexp-both nil t)
  8902. (org-in-regexp org-tsr-regexp-both nil t))
  8903. (org-follow-timestamp-link))
  8904. (t (user-error "No link found"))))
  8905. ;;;###autoload
  8906. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8907. "Open a link in the string S, as if it was in Org mode."
  8908. (interactive "sLink: \nP")
  8909. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8910. (with-temp-buffer
  8911. (let ((org-inhibit-startup (not reference-buffer)))
  8912. (org-mode)
  8913. (insert s)
  8914. (goto-char (point-min))
  8915. (when reference-buffer
  8916. (setq org-link-abbrev-alist-local
  8917. (with-current-buffer reference-buffer
  8918. org-link-abbrev-alist-local)))
  8919. (org-open-at-point arg reference-buffer)))))
  8920. (defvar org-open-at-point-functions nil
  8921. "Hook that is run when following a link at point.
  8922. Functions in this hook must return t if they identify and follow
  8923. a link at point. If they don't find anything interesting at point,
  8924. they must return nil.")
  8925. (defvar org-link-search-inhibit-query nil)
  8926. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8927. (defun org--open-doi-link (path)
  8928. "Open a \"doi\" type link.
  8929. PATH is a the path to search for, as a string."
  8930. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8931. (defun org--open-elisp-link (path)
  8932. "Open a \"elisp\" type link.
  8933. PATH is the sexp to evaluate, as a string."
  8934. (let ((cmd path))
  8935. (if (or (and (org-string-nw-p
  8936. org-confirm-elisp-link-not-regexp)
  8937. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8938. (not org-confirm-elisp-link-function)
  8939. (funcall org-confirm-elisp-link-function
  8940. (format "Execute \"%s\" as elisp? "
  8941. (org-add-props cmd nil 'face 'org-warning))))
  8942. (message "%s => %s" cmd
  8943. (if (eq (string-to-char cmd) ?\()
  8944. (eval (read cmd))
  8945. (call-interactively (read cmd))))
  8946. (user-error "Abort"))))
  8947. (defun org--open-help-link (path)
  8948. "Open a \"help\" type link.
  8949. PATH is a symbol name, as a string."
  8950. (pcase (intern path)
  8951. ((and (pred fboundp) variable) (describe-function variable))
  8952. ((and (pred boundp) function) (describe-variable function))
  8953. (name (user-error "Unknown function or variable: %s" name))))
  8954. (defun org--open-shell-link (path)
  8955. "Open a \"shell\" type link.
  8956. PATH is the command to execute, as a string."
  8957. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  8958. (cmd path))
  8959. (if (or (and (org-string-nw-p
  8960. org-confirm-shell-link-not-regexp)
  8961. (string-match
  8962. org-confirm-shell-link-not-regexp cmd))
  8963. (not org-confirm-shell-link-function)
  8964. (funcall org-confirm-shell-link-function
  8965. (format "Execute \"%s\" in shell? "
  8966. (org-add-props cmd nil
  8967. 'face 'org-warning))))
  8968. (progn
  8969. (message "Executing %s" cmd)
  8970. (shell-command cmd buf)
  8971. (when (featurep 'midnight)
  8972. (setq clean-buffer-list-kill-buffer-names
  8973. (cons (buffer-name buf)
  8974. clean-buffer-list-kill-buffer-names))))
  8975. (user-error "Abort"))))
  8976. (defun org-open-at-point (&optional arg reference-buffer)
  8977. "Open link, timestamp, footnote or tags at point.
  8978. When point is on a link, follow it. Normally, files will be
  8979. opened by an appropriate application. If the optional prefix
  8980. argument ARG is non-nil, Emacs will visit the file. With
  8981. a double prefix argument, try to open outside of Emacs, in the
  8982. application the system uses for this file type.
  8983. When point is on a timestamp, open the agenda at the day
  8984. specified.
  8985. When point is a footnote definition, move to the first reference
  8986. found. If it is on a reference, move to the associated
  8987. definition.
  8988. When point is on a headline, display a list of every link in the
  8989. entry, so it is possible to pick one, or all, of them. If point
  8990. is on a tag, call `org-tags-view' instead.
  8991. When optional argument REFERENCE-BUFFER is non-nil, it should
  8992. specify a buffer from where the link search should happen. This
  8993. is used internally by `org-open-link-from-string'.
  8994. On top of syntactically correct links, this function will also
  8995. try to open links and time-stamps in comments, example
  8996. blocks... i.e., whenever point is on something looking like
  8997. a timestamp or a link."
  8998. (interactive "P")
  8999. ;; On a code block, open block's results.
  9000. (unless (call-interactively 'org-babel-open-src-block-result)
  9001. (org-load-modules-maybe)
  9002. (setq org-window-config-before-follow-link (current-window-configuration))
  9003. (org-remove-occur-highlights nil nil t)
  9004. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9005. (let* ((context
  9006. ;; Only consider supported types, even if they are not
  9007. ;; the closest one.
  9008. (org-element-lineage
  9009. (org-element-context)
  9010. '(clock footnote-definition footnote-reference headline
  9011. inlinetask link timestamp)
  9012. t))
  9013. (type (org-element-type context))
  9014. (value (org-element-property :value context)))
  9015. (cond
  9016. ;; On a headline or an inlinetask, but not on a timestamp,
  9017. ;; a link, a footnote reference.
  9018. ((memq type '(headline inlinetask))
  9019. (org-match-line org-complex-heading-regexp)
  9020. (if (and (match-beginning 5)
  9021. (>= (point) (match-beginning 5))
  9022. (< (point) (match-end 5)))
  9023. ;; On tags.
  9024. (org-tags-view arg (substring (match-string 5) 0 -1))
  9025. ;; Not on tags.
  9026. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9027. (`(nil . ,_)
  9028. (require 'org-attach)
  9029. (org-attach-reveal 'if-exists))
  9030. (`(,links . ,links-end)
  9031. (dolist (link (if (stringp links) (list links) links))
  9032. (search-forward link nil links-end)
  9033. (goto-char (match-beginning 0))
  9034. (org-open-at-point))))))
  9035. ;; On a footnote reference or at definition's label.
  9036. ((or (eq type 'footnote-reference)
  9037. (and (eq type 'footnote-definition)
  9038. (save-excursion
  9039. ;; Do not validate action when point is on the
  9040. ;; spaces right after the footnote label, in
  9041. ;; order to be on par with behaviour on links.
  9042. (skip-chars-forward " \t")
  9043. (let ((begin
  9044. (org-element-property :contents-begin context)))
  9045. (if begin (< (point) begin)
  9046. (= (org-element-property :post-affiliated context)
  9047. (line-beginning-position)))))))
  9048. (org-footnote-action))
  9049. ;; No valid context. Ignore catch-all types like `headline'.
  9050. ;; If point is on something looking like a link or
  9051. ;; a time-stamp, try opening it. It may be useful in
  9052. ;; comments, example blocks...
  9053. ((memq type '(footnote-definition headline inlinetask nil))
  9054. (call-interactively #'org-open-at-point-global))
  9055. ;; On a clock line, make sure point is on the timestamp
  9056. ;; before opening it.
  9057. ((and (eq type 'clock)
  9058. value
  9059. (>= (point) (org-element-property :begin value))
  9060. (<= (point) (org-element-property :end value)))
  9061. (org-follow-timestamp-link))
  9062. ;; Do nothing on white spaces after an object.
  9063. ((>= (point)
  9064. (save-excursion
  9065. (goto-char (org-element-property :end context))
  9066. (skip-chars-backward " \t")
  9067. (point)))
  9068. (user-error "No link found"))
  9069. ((eq type 'timestamp) (org-follow-timestamp-link))
  9070. ((eq type 'link)
  9071. (let ((type (org-element-property :type context))
  9072. (path (org-link-unescape (org-element-property :path context))))
  9073. ;; Switch back to REFERENCE-BUFFER needed when called in
  9074. ;; a temporary buffer through `org-open-link-from-string'.
  9075. (with-current-buffer (or reference-buffer (current-buffer))
  9076. (cond
  9077. ((equal type "file")
  9078. (if (string-match "[*?{]" (file-name-nondirectory path))
  9079. (dired path)
  9080. ;; Look into `org-link-parameters' in order to find
  9081. ;; a DEDICATED-FUNCTION to open file. The function
  9082. ;; will be applied on raw link instead of parsed
  9083. ;; link due to the limitation in `org-add-link-type'
  9084. ;; ("open" function called with a single argument).
  9085. ;; If no such function is found, fallback to
  9086. ;; `org-open-file'.
  9087. (let* ((option (org-element-property :search-option context))
  9088. (app (org-element-property :application context))
  9089. (dedicated-function
  9090. (org-link-get-parameter
  9091. (if app (concat type "+" app) type)
  9092. :follow)))
  9093. (if dedicated-function
  9094. (funcall dedicated-function
  9095. (concat path
  9096. (and option (concat "::" option))))
  9097. (apply #'org-open-file
  9098. path
  9099. (cond (arg)
  9100. ((equal app "emacs") 'emacs)
  9101. ((equal app "sys") 'system))
  9102. (cond ((not option) nil)
  9103. ((string-match-p "\\`[0-9]+\\'" option)
  9104. (list (string-to-number option)))
  9105. (t (list nil
  9106. (org-link-unescape option)))))))))
  9107. ((functionp (org-link-get-parameter type :follow))
  9108. (funcall (org-link-get-parameter type :follow) path))
  9109. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9110. (unless (run-hook-with-args-until-success
  9111. 'org-open-link-functions path)
  9112. (if (not arg) (org-mark-ring-push)
  9113. (switch-to-buffer-other-window
  9114. (org-get-buffer-for-internal-link (current-buffer))))
  9115. (let ((destination
  9116. (org-with-wide-buffer
  9117. (if (equal type "radio")
  9118. (org-search-radio-target
  9119. (org-element-property :path context))
  9120. (org-link-search
  9121. (if (member type '("custom-id" "coderef"))
  9122. (org-element-property :raw-link context)
  9123. path)
  9124. ;; Prevent fuzzy links from matching
  9125. ;; themselves.
  9126. (and (equal type "fuzzy")
  9127. (+ 2 (org-element-property :begin context)))))
  9128. (point))))
  9129. (unless (and (<= (point-min) destination)
  9130. (>= (point-max) destination))
  9131. (widen))
  9132. (goto-char destination))))
  9133. (t (browse-url-at-point))))))
  9134. (t (user-error "No link found")))))
  9135. (run-hook-with-args 'org-follow-link-hook)))
  9136. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9137. "Offer links in the current entry and return the selected link.
  9138. If there is only one link, return it.
  9139. If NTH is an integer, return the NTH link found.
  9140. If ZERO is a string, check also this string for a link, and if
  9141. there is one, return it."
  9142. (with-current-buffer buffer
  9143. (org-with-wide-buffer
  9144. (goto-char marker)
  9145. (let ((cnt ?0)
  9146. have-zero end links link c)
  9147. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9148. (push (match-string 0 zero) links)
  9149. (setq cnt (1- cnt) have-zero t))
  9150. (save-excursion
  9151. (org-back-to-heading t)
  9152. (setq end (save-excursion (outline-next-heading) (point)))
  9153. (while (re-search-forward org-any-link-re end t)
  9154. (push (match-string 0) links))
  9155. (setq links (org-uniquify (reverse links))))
  9156. (cond
  9157. ((null links)
  9158. (message "No links"))
  9159. ((equal (length links) 1)
  9160. (setq link (car links)))
  9161. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9162. (setq link (nth (if have-zero nth (1- nth)) links)))
  9163. (t ; we have to select a link
  9164. (save-excursion
  9165. (save-window-excursion
  9166. (delete-other-windows)
  9167. (with-output-to-temp-buffer "*Select Link*"
  9168. (dolist (l links)
  9169. (cond
  9170. ((not (string-match org-bracket-link-regexp l))
  9171. (princ (format "[%c] %s\n" (cl-incf cnt)
  9172. (org-unbracket-string "<" ">" l))))
  9173. ((match-end 3)
  9174. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9175. (match-string 3 l) (match-string 1 l))))
  9176. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9177. (match-string 1 l)))))))
  9178. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9179. (message "Select link to open, RET to open all:")
  9180. (setq c (read-char-exclusive))
  9181. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9182. (when (equal c ?q) (user-error "Abort"))
  9183. (if (equal c ?\C-m)
  9184. (setq link links)
  9185. (setq nth (- c ?0))
  9186. (when have-zero (setq nth (1+ nth)))
  9187. (unless (and (integerp nth) (>= (length links) nth))
  9188. (user-error "Invalid link selection"))
  9189. (setq link (nth (1- nth) links)))))
  9190. (cons link end)))))
  9191. ;; TODO: These functions are deprecated since `org-open-at-point'
  9192. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9193. (defun org-open-file-with-system (path)
  9194. "Open file at PATH using the system way of opening it."
  9195. (org-open-file path 'system))
  9196. (defun org-open-file-with-emacs (path)
  9197. "Open file at PATH in Emacs."
  9198. (org-open-file path 'emacs))
  9199. ;;; File search
  9200. (defvar org-create-file-search-functions nil
  9201. "List of functions to construct the right search string for a file link.
  9202. These functions are called in turn with point at the location to
  9203. which the link should point.
  9204. A function in the hook should first test if it would like to
  9205. handle this file type, for example by checking the `major-mode'
  9206. or the file extension. If it decides not to handle this file, it
  9207. should just return nil to give other functions a chance. If it
  9208. does handle the file, it must return the search string to be used
  9209. when following the link. The search string will be part of the
  9210. file link, given after a double colon, and `org-open-at-point'
  9211. will automatically search for it. If special measures must be
  9212. taken to make the search successful, another function should be
  9213. added to the companion hook `org-execute-file-search-functions',
  9214. which see.
  9215. A function in this hook may also use `setq' to set the variable
  9216. `description' to provide a suggestion for the descriptive text to
  9217. be used for this link when it gets inserted into an Org buffer
  9218. with \\[org-insert-link].")
  9219. (defvar org-execute-file-search-functions nil
  9220. "List of functions to execute a file search triggered by a link.
  9221. Functions added to this hook must accept a single argument, the
  9222. search string that was part of the file link, the part after the
  9223. double colon. The function must first check if it would like to
  9224. handle this search, for example by checking the `major-mode' or
  9225. the file extension. If it decides not to handle this search, it
  9226. should just return nil to give other functions a chance. If it
  9227. does handle the search, it must return a non-nil value to keep
  9228. other functions from trying.
  9229. Each function can access the current prefix argument through the
  9230. variable `current-prefix-arg'. Note that a single prefix is used
  9231. to force opening a link in Emacs, so it may be good to only use a
  9232. numeric or double prefix to guide the search function.
  9233. In case this is needed, a function in this hook can also restore
  9234. the window configuration before `org-open-at-point' was called using:
  9235. (set-window-configuration org-window-config-before-follow-link)")
  9236. (defun org-search-radio-target (target)
  9237. "Search a radio target matching TARGET in current buffer.
  9238. White spaces are not significant."
  9239. (let ((re (format "<<<%s>>>"
  9240. (mapconcat #'regexp-quote
  9241. (split-string target)
  9242. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9243. (origin (point)))
  9244. (goto-char (point-min))
  9245. (catch :radio-match
  9246. (while (re-search-forward re nil t)
  9247. (backward-char)
  9248. (let ((object (org-element-context)))
  9249. (when (eq (org-element-type object) 'radio-target)
  9250. (goto-char (org-element-property :begin object))
  9251. (org-show-context 'link-search)
  9252. (throw :radio-match nil))))
  9253. (goto-char origin)
  9254. (user-error "No match for radio target: %s" target))))
  9255. (defun org-link-search (s &optional avoid-pos stealth)
  9256. "Search for a search string S.
  9257. If S starts with \"#\", it triggers a custom ID search.
  9258. If S is enclosed within parenthesis, it initiates a coderef
  9259. search.
  9260. If S is surrounded by forward slashes, it is interpreted as
  9261. a regular expression. In Org mode files, this will create an
  9262. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9263. to list matches. If the current buffer is in `dired-mode', grep
  9264. will be used to search in all files.
  9265. When AVOID-POS is given, ignore matches near that position.
  9266. When optional argument STEALTH is non-nil, do not modify
  9267. visibility around point, thus ignoring `org-show-context-detail'
  9268. variable.
  9269. Search is case-insensitive and ignores white spaces. Return type
  9270. of matched result, which is either `dedicated' or `fuzzy'."
  9271. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9272. (let* ((case-fold-search t)
  9273. (origin (point))
  9274. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9275. (starred (eq (string-to-char normalized) ?*))
  9276. (words (split-string (if starred (substring s 1) s)))
  9277. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9278. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9279. type)
  9280. (cond
  9281. ;; Check if there are any special search functions.
  9282. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9283. ((eq (string-to-char s) ?#)
  9284. ;; Look for a custom ID S if S starts with "#".
  9285. (let* ((id (substring normalized 1))
  9286. (match (org-find-property "CUSTOM_ID" id)))
  9287. (if match (progn (goto-char match) (setf type 'dedicated))
  9288. (error "No match for custom ID: %s" id))))
  9289. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9290. ;; Look for coderef targets if S is enclosed within parenthesis.
  9291. (let ((coderef (match-string-no-properties 1 normalized))
  9292. (re (substring s-single-re 1 -1)))
  9293. (goto-char (point-min))
  9294. (catch :coderef-match
  9295. (while (re-search-forward re nil t)
  9296. (let ((element (org-element-at-point)))
  9297. (when (and (memq (org-element-type element)
  9298. '(example-block src-block))
  9299. ;; Build proper regexp according to current
  9300. ;; block's label format.
  9301. (let ((label-fmt
  9302. (regexp-quote
  9303. (or (org-element-property :label-fmt element)
  9304. org-coderef-label-format))))
  9305. (save-excursion
  9306. (beginning-of-line)
  9307. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9308. (format label-fmt coderef))))))
  9309. (setq type 'dedicated)
  9310. (goto-char (match-beginning 1))
  9311. (throw :coderef-match nil))))
  9312. (goto-char origin)
  9313. (error "No match for coderef: %s" coderef))))
  9314. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9315. ;; Look for a regular expression.
  9316. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9317. (match-string 1 s)))
  9318. ;; From here, we handle fuzzy links.
  9319. ;;
  9320. ;; Look for targets, only if not in a headline search.
  9321. ((and (not starred)
  9322. (let ((target (format "<<%s>>" s-multi-re)))
  9323. (catch :target-match
  9324. (goto-char (point-min))
  9325. (while (re-search-forward target nil t)
  9326. (backward-char)
  9327. (let ((context (org-element-context)))
  9328. (when (eq (org-element-type context) 'target)
  9329. (setq type 'dedicated)
  9330. (goto-char (org-element-property :begin context))
  9331. (throw :target-match t))))
  9332. nil))))
  9333. ;; Look for elements named after S, only if not in a headline
  9334. ;; search.
  9335. ((and (not starred)
  9336. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9337. (catch :name-match
  9338. (goto-char (point-min))
  9339. (while (re-search-forward name nil t)
  9340. (let ((element (org-element-at-point)))
  9341. (when (equal words
  9342. (split-string
  9343. (org-element-property :name element)))
  9344. (setq type 'dedicated)
  9345. (beginning-of-line)
  9346. (throw :name-match t))))
  9347. nil))))
  9348. ;; Regular text search. Prefer headlines in Org mode buffers.
  9349. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9350. ;; statistics cookies and tags.
  9351. ((and (derived-mode-p 'org-mode)
  9352. (let ((title-re
  9353. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9354. org-outline-regexp-bol
  9355. org-comment-string
  9356. (mapconcat #'regexp-quote words ".+")))
  9357. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9358. (comment-re (eval-when-compile
  9359. (format "\\`%s[ \t]+" org-comment-string))))
  9360. (goto-char (point-min))
  9361. (catch :found
  9362. (while (re-search-forward title-re nil t)
  9363. (when (equal words
  9364. (split-string
  9365. (replace-regexp-in-string
  9366. cookie-re ""
  9367. (replace-regexp-in-string
  9368. comment-re "" (org-get-heading t t t)))))
  9369. (throw :found t)))
  9370. nil)))
  9371. (beginning-of-line)
  9372. (setq type 'dedicated))
  9373. ;; Offer to create non-existent headline depending on
  9374. ;; `org-link-search-must-match-exact-headline'.
  9375. ((and (derived-mode-p 'org-mode)
  9376. (not org-link-search-inhibit-query)
  9377. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9378. (yes-or-no-p "No match - create this as a new heading? "))
  9379. (goto-char (point-max))
  9380. (unless (bolp) (newline))
  9381. (org-insert-heading nil t t)
  9382. (insert s "\n")
  9383. (beginning-of-line 0))
  9384. ;; Only headlines are looked after. No need to process
  9385. ;; further: throw an error.
  9386. ((and (derived-mode-p 'org-mode)
  9387. (or starred org-link-search-must-match-exact-headline))
  9388. (goto-char origin)
  9389. (error "No match for fuzzy expression: %s" normalized))
  9390. ;; Regular text search.
  9391. ((catch :fuzzy-match
  9392. (goto-char (point-min))
  9393. (while (re-search-forward s-multi-re nil t)
  9394. ;; Skip match if it contains AVOID-POS or it is included in
  9395. ;; a link with a description but outside the description.
  9396. (unless (or (and avoid-pos
  9397. (<= (match-beginning 0) avoid-pos)
  9398. (> (match-end 0) avoid-pos))
  9399. (and (save-match-data
  9400. (org-in-regexp org-bracket-link-regexp))
  9401. (match-beginning 3)
  9402. (or (> (match-beginning 3) (point))
  9403. (<= (match-end 3) (point)))
  9404. (org-element-lineage
  9405. (save-match-data (org-element-context))
  9406. '(link) t)))
  9407. (goto-char (match-beginning 0))
  9408. (setq type 'fuzzy)
  9409. (throw :fuzzy-match t)))
  9410. nil))
  9411. ;; All failed. Throw an error.
  9412. (t (goto-char origin)
  9413. (error "No match for fuzzy expression: %s" normalized)))
  9414. ;; Disclose surroundings of match, if appropriate.
  9415. (when (and (derived-mode-p 'org-mode) (not stealth))
  9416. (org-show-context 'link-search))
  9417. type))
  9418. (defun org-get-buffer-for-internal-link (buffer)
  9419. "Return a buffer to be used for displaying the link target of internal links."
  9420. (cond
  9421. ((not org-display-internal-link-with-indirect-buffer)
  9422. buffer)
  9423. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9424. (message "Buffer is already a clone, not making another one")
  9425. ;; we also do not modify visibility in this case
  9426. buffer)
  9427. (t ; make a new indirect buffer for displaying the link
  9428. (let* ((bn (buffer-name buffer))
  9429. (ibn (concat bn "(Clone)"))
  9430. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9431. (with-current-buffer ib (org-overview))
  9432. ib))))
  9433. (defun org-do-occur (regexp &optional cleanup)
  9434. "Call the Emacs command `occur'.
  9435. If CLEANUP is non-nil, remove the printout of the regular expression
  9436. in the *Occur* buffer. This is useful if the regex is long and not useful
  9437. to read."
  9438. (occur regexp)
  9439. (when cleanup
  9440. (let ((cwin (selected-window)) win beg end)
  9441. (when (setq win (get-buffer-window "*Occur*"))
  9442. (select-window win))
  9443. (goto-char (point-min))
  9444. (when (re-search-forward "match[a-z]+" nil t)
  9445. (setq beg (match-end 0))
  9446. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9447. (setq end (1- (match-beginning 0)))))
  9448. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9449. (goto-char (point-min))
  9450. (select-window cwin))))
  9451. ;;; The mark ring for links jumps
  9452. (defvar org-mark-ring nil
  9453. "Mark ring for positions before jumps in Org mode.")
  9454. (defvar org-mark-ring-last-goto nil
  9455. "Last position in the mark ring used to go back.")
  9456. ;; Fill and close the ring
  9457. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9458. (dotimes (_ org-mark-ring-length)
  9459. (push (make-marker) org-mark-ring))
  9460. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9461. org-mark-ring)
  9462. (defun org-mark-ring-push (&optional pos buffer)
  9463. "Put the current position or POS into the mark ring and rotate it."
  9464. (interactive)
  9465. (setq pos (or pos (point)))
  9466. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9467. (move-marker (car org-mark-ring)
  9468. (or pos (point))
  9469. (or buffer (current-buffer)))
  9470. (message "%s"
  9471. (substitute-command-keys
  9472. "Position saved to mark ring, go back with \
  9473. `\\[org-mark-ring-goto]'.")))
  9474. (defun org-mark-ring-goto (&optional n)
  9475. "Jump to the previous position in the mark ring.
  9476. With prefix arg N, jump back that many stored positions. When
  9477. called several times in succession, walk through the entire ring.
  9478. Org mode commands jumping to a different position in the current file,
  9479. or to another Org file, automatically push the old position onto the ring."
  9480. (interactive "p")
  9481. (let (p m)
  9482. (if (eq last-command this-command)
  9483. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9484. (setq p org-mark-ring))
  9485. (setq org-mark-ring-last-goto p)
  9486. (setq m (car p))
  9487. (pop-to-buffer-same-window (marker-buffer m))
  9488. (goto-char m)
  9489. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9490. (defun org-add-angle-brackets (s)
  9491. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9492. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9493. s)
  9494. ;;; Following specific links
  9495. (defvar org-agenda-buffer-tmp-name)
  9496. (defvar org-agenda-start-on-weekday)
  9497. (defun org-follow-timestamp-link ()
  9498. "Open an agenda view for the time-stamp date/range at point."
  9499. (cond
  9500. ((org-at-date-range-p t)
  9501. (let ((org-agenda-start-on-weekday)
  9502. (t1 (match-string 1))
  9503. (t2 (match-string 2)) tt1 tt2)
  9504. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9505. tt2 (time-to-days (org-time-string-to-time t2)))
  9506. (let ((org-agenda-buffer-tmp-name
  9507. (format "*Org Agenda(a:%s)"
  9508. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9509. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9510. ((org-at-timestamp-p 'lax)
  9511. (let ((org-agenda-buffer-tmp-name
  9512. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9513. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9514. (substring (match-string 1) 0 10)))
  9515. 1)))
  9516. (t (error "This should not happen"))))
  9517. ;;; Following file links
  9518. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9519. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9520. (declare-function mailcap-mime-info
  9521. "mailcap" (string &optional request no-decode))
  9522. (defvar org-wait nil)
  9523. (defun org-open-file (path &optional in-emacs line search)
  9524. "Open the file at PATH.
  9525. First, this expands any special file name abbreviations. Then the
  9526. configuration variable `org-file-apps' is checked if it contains an
  9527. entry for this file type, and if yes, the corresponding command is launched.
  9528. If no application is found, Emacs simply visits the file.
  9529. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9530. With a double \\[universal-argument] \\[universal-argument] \
  9531. prefix arg, Org tries to avoid opening in Emacs
  9532. and to use an external application to visit the file.
  9533. Optional LINE specifies a line to go to, optional SEARCH a string
  9534. to search for. If LINE or SEARCH is given, the file will be
  9535. opened in Emacs, unless an entry from org-file-apps that makes
  9536. use of groups in a regexp matches.
  9537. If you want to change the way frames are used when following a
  9538. link, please customize `org-link-frame-setup'.
  9539. If the file does not exist, an error is thrown."
  9540. (let* ((file (if (equal path "")
  9541. buffer-file-name
  9542. (substitute-in-file-name (expand-file-name path))))
  9543. (file-apps (append org-file-apps (org-default-apps)))
  9544. (apps (cl-remove-if
  9545. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9546. (apps-dlink (cl-remove-if-not
  9547. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9548. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  9549. (dirp (unless remp (file-directory-p file)))
  9550. (file (if (and dirp org-open-directory-means-index-dot-org)
  9551. (concat (file-name-as-directory file) "index.org")
  9552. file))
  9553. (a-m-a-p (assq 'auto-mode apps))
  9554. (dfile (downcase file))
  9555. ;; Reconstruct the original link from the PATH, LINE and
  9556. ;; SEARCH args.
  9557. (link (cond (line (concat file "::" (number-to-string line)))
  9558. (search (concat file "::" search))
  9559. (t file)))
  9560. (dlink (downcase link))
  9561. (ext
  9562. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9563. (match-string 1 dfile)))
  9564. (save-position-maybe
  9565. (let ((old-buffer (current-buffer))
  9566. (old-pos (point))
  9567. (old-mode major-mode))
  9568. (lambda ()
  9569. (and (derived-mode-p 'org-mode)
  9570. (eq old-mode 'org-mode)
  9571. (or (not (eq old-buffer (current-buffer)))
  9572. (not (eq old-pos (point))))
  9573. (org-mark-ring-push old-pos old-buffer)))))
  9574. cmd link-match-data)
  9575. (cond
  9576. ((member in-emacs '((16) system))
  9577. (setq cmd (cdr (assq 'system apps))))
  9578. (in-emacs (setq cmd 'emacs))
  9579. (t
  9580. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9581. (and dirp (cdr (assq 'directory apps)))
  9582. ;; First, try matching against apps-dlink if we
  9583. ;; get a match here, store the match data for
  9584. ;; later.
  9585. (let ((match (assoc-default dlink apps-dlink
  9586. 'string-match)))
  9587. (if match
  9588. (progn (setq link-match-data (match-data))
  9589. match)
  9590. (progn (setq in-emacs (or in-emacs line search))
  9591. nil))) ; if we have no match in apps-dlink,
  9592. ; always open the file in emacs if line or search
  9593. ; is given (for backwards compatibility)
  9594. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9595. 'string-match)
  9596. (cdr (assoc ext apps))
  9597. (cdr (assq t apps))))))
  9598. (when (eq cmd 'system)
  9599. (setq cmd (cdr (assq 'system apps))))
  9600. (when (eq cmd 'default)
  9601. (setq cmd (cdr (assoc t apps))))
  9602. (when (eq cmd 'mailcap)
  9603. (require 'mailcap)
  9604. (mailcap-parse-mailcaps)
  9605. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9606. (command (mailcap-mime-info mime-type)))
  9607. (if (stringp command)
  9608. (setq cmd command)
  9609. (setq cmd 'emacs))))
  9610. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9611. (not (file-exists-p file))
  9612. (not org-open-non-existing-files))
  9613. (user-error "No such file: %s" file))
  9614. (cond
  9615. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9616. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9617. (while (string-match "['\"]%s['\"]" cmd)
  9618. (setq cmd (replace-match "%s" t t cmd)))
  9619. (setq cmd (replace-regexp-in-string
  9620. "%s"
  9621. (shell-quote-argument (convert-standard-filename file))
  9622. cmd
  9623. nil t))
  9624. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9625. (save-match-data
  9626. (let ((match-index 1)
  9627. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9628. (set-match-data link-match-data)
  9629. (while (<= match-index number-of-groups)
  9630. (let ((regex (concat "%" (number-to-string match-index)))
  9631. (replace-with (match-string match-index dlink)))
  9632. (while (string-match regex cmd)
  9633. (setq cmd (replace-match replace-with t t cmd))))
  9634. (setq match-index (+ match-index 1)))))
  9635. (save-window-excursion
  9636. (message "Running %s...done" cmd)
  9637. (start-process-shell-command cmd nil cmd)
  9638. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9639. ((or (stringp cmd)
  9640. (eq cmd 'emacs))
  9641. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9642. (widen)
  9643. (cond (line (org-goto-line line)
  9644. (when (derived-mode-p 'org-mode) (org-reveal)))
  9645. (search (condition-case err
  9646. (org-link-search search)
  9647. ;; Save position before error-ing out so user
  9648. ;; can easily move back to the original buffer.
  9649. (error (funcall save-position-maybe)
  9650. (error (nth 1 err)))))))
  9651. ((functionp cmd)
  9652. (save-match-data
  9653. (set-match-data link-match-data)
  9654. (condition-case nil
  9655. (funcall cmd file link)
  9656. ;; FIXME: Remove this check when most default installations
  9657. ;; of Emacs have at least Org 9.0.
  9658. ((debug wrong-number-of-arguments wrong-type-argument
  9659. invalid-function)
  9660. (user-error "Please see Org News for version 9.0 about \
  9661. `org-file-apps'--Lisp error: %S" cmd)))))
  9662. ((consp cmd)
  9663. ;; FIXME: Remove this check when most default installations of
  9664. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9665. ;; fall back to `org-link-frame-setup' for an old usage of
  9666. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9667. (user-error "Please see Org News for version 9.0 about \
  9668. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9669. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9670. (funcall save-position-maybe)))
  9671. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9672. "This function returns non-nil if `entry' uses a regular
  9673. expression which should be matched against the whole link by
  9674. org-open-file.
  9675. It assumes that is the case when the entry uses a regular
  9676. expression which has at least one grouping construct and the
  9677. action is either a lisp form or a command string containing
  9678. `%1', i.e. using at least one subexpression match as a
  9679. parameter."
  9680. (let ((selector (car entry))
  9681. (action (cdr entry)))
  9682. (if (stringp selector)
  9683. (and (> (regexp-opt-depth selector) 0)
  9684. (or (and (stringp action)
  9685. (string-match "%[0-9]" action))
  9686. (consp action)))
  9687. nil)))
  9688. (defun org-default-apps ()
  9689. "Return the default applications for this operating system."
  9690. (cond
  9691. ((eq system-type 'darwin)
  9692. org-file-apps-defaults-macosx)
  9693. ((eq system-type 'windows-nt)
  9694. org-file-apps-defaults-windowsnt)
  9695. (t org-file-apps-defaults-gnu)))
  9696. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9697. "Convert extensions to regular expressions in the cars of LIST.
  9698. Also, weed out any non-string entries, because the return value is used
  9699. only for regexp matching.
  9700. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9701. point to the symbol `emacs', indicating that the file should
  9702. be opened in Emacs."
  9703. (append
  9704. (delq nil
  9705. (mapcar (lambda (x)
  9706. (unless (not (stringp (car x)))
  9707. (if (string-match "\\W" (car x))
  9708. x
  9709. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9710. list))
  9711. (when add-auto-mode
  9712. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9713. (defvar ange-ftp-name-format)
  9714. (defun org-file-remote-p (file)
  9715. "Test whether FILE specifies a location on a remote system.
  9716. Return non-nil if the location is indeed remote.
  9717. For example, the filename \"/user@host:/foo\" specifies a location
  9718. on the system \"/user@host:\"."
  9719. (cond ((fboundp 'file-remote-p)
  9720. (file-remote-p file))
  9721. ((fboundp 'tramp-handle-file-remote-p)
  9722. (tramp-handle-file-remote-p file))
  9723. ((and (boundp 'ange-ftp-name-format)
  9724. (string-match (car ange-ftp-name-format) file))
  9725. t)))
  9726. ;;;; Refiling
  9727. (defun org-get-org-file ()
  9728. "Read a filename, with default directory `org-directory'."
  9729. (let ((default (or org-default-notes-file remember-data-file)))
  9730. (read-file-name (format "File name [%s]: " default)
  9731. (file-name-as-directory org-directory)
  9732. default)))
  9733. (defun org-notes-order-reversed-p ()
  9734. "Check if the current file should receive notes in reversed order."
  9735. (cond
  9736. ((not org-reverse-note-order) nil)
  9737. ((eq t org-reverse-note-order) t)
  9738. ((not (listp org-reverse-note-order)) nil)
  9739. (t (catch 'exit
  9740. (dolist (entry org-reverse-note-order)
  9741. (when (string-match (car entry) buffer-file-name)
  9742. (throw 'exit (cdr entry))))))))
  9743. (defvar org-refile-target-table nil
  9744. "The list of refile targets, created by `org-refile'.")
  9745. (defvar org-agenda-new-buffers nil
  9746. "Buffers created to visit agenda files.")
  9747. (defvar org-refile-cache nil
  9748. "Cache for refile targets.")
  9749. (defvar org-refile-markers nil
  9750. "All the markers used for caching refile locations.")
  9751. (defun org-refile-marker (pos)
  9752. "Get a new refile marker, but only if caching is in use."
  9753. (if (not org-refile-use-cache)
  9754. pos
  9755. (let ((m (make-marker)))
  9756. (move-marker m pos)
  9757. (push m org-refile-markers)
  9758. m)))
  9759. (defun org-refile-cache-clear ()
  9760. "Clear the refile cache and disable all the markers."
  9761. (dolist (m org-refile-markers) (move-marker m nil))
  9762. (setq org-refile-markers nil)
  9763. (setq org-refile-cache nil)
  9764. (message "Refile cache has been cleared"))
  9765. (defun org-refile-cache-check-set (set)
  9766. "Check if all the markers in the cache still have live buffers."
  9767. (let (marker)
  9768. (catch 'exit
  9769. (while (and set (setq marker (nth 3 (pop set))))
  9770. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9771. (when (and marker (null (marker-buffer marker)))
  9772. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9773. (sit-for 3)
  9774. (throw 'exit nil)))
  9775. t)))
  9776. (defun org-refile-cache-put (set &rest identifiers)
  9777. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9778. (let* ((key (sha1 (prin1-to-string identifiers)))
  9779. (entry (assoc key org-refile-cache)))
  9780. (if entry
  9781. (setcdr entry set)
  9782. (push (cons key set) org-refile-cache))))
  9783. (defun org-refile-cache-get (&rest identifiers)
  9784. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9785. (cond
  9786. ((not org-refile-cache) nil)
  9787. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9788. (t
  9789. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9790. org-refile-cache))))
  9791. (and set (org-refile-cache-check-set set) set)))))
  9792. (defvar org-outline-path-cache nil
  9793. "Alist between buffer positions and outline paths.
  9794. It value is an alist (POSITION . PATH) where POSITION is the
  9795. buffer position at the beginning of an entry and PATH is a list
  9796. of strings describing the outline path for that entry, in reverse
  9797. order.")
  9798. (defun org-refile-get-targets (&optional default-buffer)
  9799. "Produce a table with refile targets."
  9800. (let ((case-fold-search nil)
  9801. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9802. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9803. targets tgs files desc descre)
  9804. (message "Getting targets...")
  9805. (with-current-buffer (or default-buffer (current-buffer))
  9806. (dolist (entry entries)
  9807. (setq files (car entry) desc (cdr entry))
  9808. (cond
  9809. ((null files) (setq files (list (current-buffer))))
  9810. ((eq files 'org-agenda-files)
  9811. (setq files (org-agenda-files 'unrestricted)))
  9812. ((and (symbolp files) (fboundp files))
  9813. (setq files (funcall files)))
  9814. ((and (symbolp files) (boundp files))
  9815. (setq files (symbol-value files))))
  9816. (when (stringp files) (setq files (list files)))
  9817. (cond
  9818. ((eq (car desc) :tag)
  9819. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9820. ((eq (car desc) :todo)
  9821. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9822. ((eq (car desc) :regexp)
  9823. (setq descre (cdr desc)))
  9824. ((eq (car desc) :level)
  9825. (setq descre (concat "^\\*\\{" (number-to-string
  9826. (if org-odd-levels-only
  9827. (1- (* 2 (cdr desc)))
  9828. (cdr desc)))
  9829. "\\}[ \t]")))
  9830. ((eq (car desc) :maxlevel)
  9831. (setq descre (concat "^\\*\\{1," (number-to-string
  9832. (if org-odd-levels-only
  9833. (1- (* 2 (cdr desc)))
  9834. (cdr desc)))
  9835. "\\}[ \t]")))
  9836. (t (error "Bad refiling target description %s" desc)))
  9837. (dolist (f files)
  9838. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9839. (or
  9840. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9841. (progn
  9842. (when (bufferp f)
  9843. (setq f (buffer-file-name (buffer-base-buffer f))))
  9844. (setq f (and f (expand-file-name f)))
  9845. (when (eq org-refile-use-outline-path 'file)
  9846. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9847. (when (eq org-refile-use-outline-path 'buffer-name)
  9848. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9849. (when (eq org-refile-use-outline-path 'full-file-path)
  9850. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9851. (org-with-wide-buffer
  9852. (goto-char (point-min))
  9853. (setq org-outline-path-cache nil)
  9854. (while (re-search-forward descre nil t)
  9855. (beginning-of-line)
  9856. (let ((case-fold-search nil))
  9857. (looking-at org-complex-heading-regexp))
  9858. (let ((begin (point))
  9859. (heading (match-string-no-properties 4)))
  9860. (unless (or (and
  9861. org-refile-target-verify-function
  9862. (not
  9863. (funcall org-refile-target-verify-function)))
  9864. (not heading))
  9865. (let ((re (format org-complex-heading-regexp-format
  9866. (regexp-quote heading)))
  9867. (target
  9868. (if (not org-refile-use-outline-path) heading
  9869. (mapconcat
  9870. #'identity
  9871. (append
  9872. (pcase org-refile-use-outline-path
  9873. (`file (list (file-name-nondirectory
  9874. (buffer-file-name
  9875. (buffer-base-buffer)))))
  9876. (`full-file-path
  9877. (list (buffer-file-name
  9878. (buffer-base-buffer))))
  9879. (`buffer-name
  9880. (list (buffer-name
  9881. (buffer-base-buffer))))
  9882. (_ nil))
  9883. (mapcar (lambda (s) (replace-regexp-in-string
  9884. "/" "\\/" s nil t))
  9885. (org-get-outline-path t t)))
  9886. "/"))))
  9887. (push (list target f re (org-refile-marker (point)))
  9888. tgs)))
  9889. (when (= (point) begin)
  9890. ;; Verification function has not moved point.
  9891. (end-of-line)))))))
  9892. (when org-refile-use-cache
  9893. (org-refile-cache-put tgs (buffer-file-name) descre))
  9894. (setq targets (append tgs targets))))))
  9895. (message "Getting targets...done")
  9896. (delete-dups (nreverse targets))))
  9897. (defun org--get-outline-path-1 (&optional use-cache)
  9898. "Return outline path to current headline.
  9899. Outline path is a list of strings, in reverse order. When
  9900. optional argument USE-CACHE is non-nil, make use of a cache. See
  9901. `org-get-outline-path' for details.
  9902. Assume buffer is widened and point is on a headline."
  9903. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9904. (let ((p (point))
  9905. (heading (let ((case-fold-search nil))
  9906. (looking-at org-complex-heading-regexp)
  9907. (if (not (match-end 4)) ""
  9908. ;; Remove statistics cookies.
  9909. (org-trim
  9910. (org-link-display-format
  9911. (replace-regexp-in-string
  9912. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9913. (match-string-no-properties 4))))))))
  9914. (if (org-up-heading-safe)
  9915. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9916. (when use-cache
  9917. (push (cons p path) org-outline-path-cache))
  9918. path)
  9919. ;; This is a new root node. Since we assume we are moving
  9920. ;; forward, we can drop previous cache so as to limit number
  9921. ;; of associations there.
  9922. (let ((path (list heading)))
  9923. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9924. path)))))
  9925. (defun org-get-outline-path (&optional with-self use-cache)
  9926. "Return the outline path to the current entry.
  9927. An outline path is a list of ancestors for current headline, as
  9928. a list of strings. Statistics cookies are removed and links are
  9929. replaced with their description, if any, or their path otherwise.
  9930. When optional argument WITH-SELF is non-nil, the path also
  9931. includes the current headline.
  9932. When optional argument USE-CACHE is non-nil, cache outline paths
  9933. between calls to this function so as to avoid backtracking. This
  9934. argument is useful when planning to find more than one outline
  9935. path in the same document. In that case, there are two
  9936. conditions to satisfy:
  9937. - `org-outline-path-cache' is set to nil before starting the
  9938. process;
  9939. - outline paths are computed by increasing buffer positions."
  9940. (org-with-wide-buffer
  9941. (and (or (and with-self (org-back-to-heading t))
  9942. (org-up-heading-safe))
  9943. (reverse (org--get-outline-path-1 use-cache)))))
  9944. (defun org-format-outline-path (path &optional width prefix separator)
  9945. "Format the outline path PATH for display.
  9946. WIDTH is the maximum number of characters that is available.
  9947. PREFIX is a prefix to be included in the returned string,
  9948. such as the file name.
  9949. SEPARATOR is inserted between the different parts of the path,
  9950. the default is \"/\"."
  9951. (setq width (or width 79))
  9952. (setq path (delq nil path))
  9953. (unless (> width 0)
  9954. (user-error "Argument `width' must be positive"))
  9955. (setq separator (or separator "/"))
  9956. (let* ((org-odd-levels-only nil)
  9957. (fpath (concat
  9958. prefix (and prefix path separator)
  9959. (mapconcat
  9960. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  9961. (cl-loop for head in path
  9962. for n from 0
  9963. collect (org-add-props
  9964. head nil 'face
  9965. (nth (% n org-n-level-faces) org-level-faces)))
  9966. separator))))
  9967. (when (> (length fpath) width)
  9968. (if (< width 7)
  9969. ;; It's unlikely that `width' will be this small, but don't
  9970. ;; waste characters by adding ".." if it is.
  9971. (setq fpath (substring fpath 0 width))
  9972. (setf (substring fpath (- width 2)) "..")))
  9973. fpath))
  9974. (defun org-display-outline-path (&optional file current separator just-return-string)
  9975. "Display the current outline path in the echo area.
  9976. If FILE is non-nil, prepend the output with the file name.
  9977. If CURRENT is non-nil, append the current heading to the output.
  9978. SEPARATOR is passed through to `org-format-outline-path'. It separates
  9979. the different parts of the path and defaults to \"/\".
  9980. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  9981. (interactive "P")
  9982. (let* (case-fold-search
  9983. (bfn (buffer-file-name (buffer-base-buffer)))
  9984. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  9985. res)
  9986. (when current (setq path (append path
  9987. (save-excursion
  9988. (org-back-to-heading t)
  9989. (when (looking-at org-complex-heading-regexp)
  9990. (list (match-string 4)))))))
  9991. (setq res
  9992. (org-format-outline-path
  9993. path
  9994. (1- (frame-width))
  9995. (and file bfn (concat (file-name-nondirectory bfn) separator))
  9996. separator))
  9997. (if just-return-string
  9998. (org-no-properties res)
  9999. (org-unlogged-message "%s" res))))
  10000. (defvar org-refile-history nil
  10001. "History for refiling operations.")
  10002. (defvar org-after-refile-insert-hook nil
  10003. "Hook run after `org-refile' has inserted its stuff at the new location.
  10004. Note that this is still *before* the stuff will be removed from
  10005. the *old* location.")
  10006. (defvar org-capture-last-stored-marker)
  10007. (defvar org-refile-keep nil
  10008. "Non-nil means `org-refile' will copy instead of refile.")
  10009. (defun org-copy ()
  10010. "Like `org-refile', but copy."
  10011. (interactive)
  10012. (let ((org-refile-keep t))
  10013. (funcall 'org-refile nil nil nil "Copy")))
  10014. (defun org-refile (&optional arg default-buffer rfloc msg)
  10015. "Move the entry or entries at point to another heading.
  10016. The list of target headings is compiled using the information in
  10017. `org-refile-targets', which see.
  10018. At the target location, the entry is filed as a subitem of the
  10019. target heading. Depending on `org-reverse-note-order', the new
  10020. subitem will either be the first or the last subitem.
  10021. If there is an active region, all entries in that region will be
  10022. refiled. However, the region must fulfill the requirement that
  10023. the first heading sets the top-level of the moved text.
  10024. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10025. location
  10026. and not actually move anything.
  10027. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10028. location where the last
  10029. refiling operation has put the subtree.
  10030. With a numeric prefix argument of `2', refile to the running clock.
  10031. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10032. being set to t and copy to the target location, don't move it.
  10033. Beware that keeping refiled entries may result in duplicated ID
  10034. properties.
  10035. RFLOC can be a refile location obtained in a different way.
  10036. MSG is a string to replace \"Refile\" in the default prompt with
  10037. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10038. See also `org-refile-use-outline-path'.
  10039. If you are using target caching (see `org-refile-use-cache'), you
  10040. have to clear the target cache in order to find new targets.
  10041. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10042. prefix argument (`C-u C-u C-u C-c C-w')."
  10043. (interactive "P")
  10044. (if (member arg '(0 (64)))
  10045. (org-refile-cache-clear)
  10046. (let* ((actionmsg (cond (msg msg)
  10047. ((equal arg 3) "Refile (and keep)")
  10048. (t "Refile")))
  10049. (regionp (org-region-active-p))
  10050. (region-start (and regionp (region-beginning)))
  10051. (region-end (and regionp (region-end)))
  10052. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10053. pos it nbuf file level reversed)
  10054. (setq last-command nil)
  10055. (when regionp
  10056. (goto-char region-start)
  10057. (or (bolp) (goto-char (point-at-bol)))
  10058. (setq region-start (point))
  10059. (unless (or (org-kill-is-subtree-p
  10060. (buffer-substring region-start region-end))
  10061. (prog1 org-refile-active-region-within-subtree
  10062. (let ((s (point-at-eol)))
  10063. (org-toggle-heading)
  10064. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10065. (user-error "The region is not a (sequence of) subtree(s)")))
  10066. (if (equal arg '(16))
  10067. (org-refile-goto-last-stored)
  10068. (when (or
  10069. (and (equal arg 2)
  10070. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10071. (prog1
  10072. (setq it (list (or org-clock-heading "running clock")
  10073. (buffer-file-name
  10074. (marker-buffer org-clock-hd-marker))
  10075. ""
  10076. (marker-position org-clock-hd-marker)))
  10077. (setq arg nil)))
  10078. (setq it
  10079. (or rfloc
  10080. (let (heading-text)
  10081. (save-excursion
  10082. (unless (and arg (listp arg))
  10083. (org-back-to-heading t)
  10084. (setq heading-text
  10085. (replace-regexp-in-string
  10086. org-bracket-link-regexp
  10087. "\\3"
  10088. (or (nth 4 (org-heading-components))
  10089. ""))))
  10090. (org-refile-get-location
  10091. (cond ((and arg (listp arg)) "Goto")
  10092. (regionp (concat actionmsg " region to"))
  10093. (t (concat actionmsg " subtree \""
  10094. heading-text "\" to")))
  10095. default-buffer
  10096. (and (not (equal '(4) arg))
  10097. org-refile-allow-creating-parent-nodes)))))))
  10098. (setq file (nth 1 it)
  10099. pos (nth 3 it))
  10100. (when (and (not arg)
  10101. pos
  10102. (equal (buffer-file-name) file)
  10103. (if regionp
  10104. (and (>= pos region-start)
  10105. (<= pos region-end))
  10106. (and (>= pos (point))
  10107. (< pos (save-excursion
  10108. (org-end-of-subtree t t))))))
  10109. (error "Cannot refile to position inside the tree or region"))
  10110. (setq nbuf (or (find-buffer-visiting file)
  10111. (find-file-noselect file)))
  10112. (if (and arg (not (equal arg 3)))
  10113. (progn
  10114. (pop-to-buffer-same-window nbuf)
  10115. (goto-char (cond (pos)
  10116. ((org-notes-order-reversed-p) (point-min))
  10117. (t (point-max))))
  10118. (org-show-context 'org-goto))
  10119. (if regionp
  10120. (progn
  10121. (org-kill-new (buffer-substring region-start region-end))
  10122. (org-save-markers-in-region region-start region-end))
  10123. (org-copy-subtree 1 nil t))
  10124. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10125. (find-file-noselect file)))
  10126. (setq reversed (org-notes-order-reversed-p))
  10127. (org-with-wide-buffer
  10128. (if pos
  10129. (progn
  10130. (goto-char pos)
  10131. (setq level (org-get-valid-level (funcall outline-level) 1))
  10132. (goto-char
  10133. (if reversed
  10134. (or (outline-next-heading) (point-max))
  10135. (or (save-excursion (org-get-next-sibling))
  10136. (org-end-of-subtree t t)
  10137. (point-max)))))
  10138. (setq level 1)
  10139. (if (not reversed)
  10140. (goto-char (point-max))
  10141. (goto-char (point-min))
  10142. (or (outline-next-heading) (goto-char (point-max)))))
  10143. (unless (bolp) (newline))
  10144. (org-paste-subtree level nil nil t)
  10145. (when org-log-refile
  10146. (org-add-log-setup 'refile nil nil org-log-refile)
  10147. (unless (eq org-log-refile 'note)
  10148. (save-excursion (org-add-log-note))))
  10149. (and org-auto-align-tags
  10150. (let ((org-loop-over-headlines-in-active-region nil))
  10151. (org-set-tags nil t)))
  10152. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10153. :last-refile)))
  10154. (when bookmark-name
  10155. (with-demoted-errors
  10156. (bookmark-set bookmark-name))))
  10157. ;; If we are refiling for capture, make sure that the
  10158. ;; last-capture pointers point here
  10159. (when (bound-and-true-p org-capture-is-refiling)
  10160. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10161. :last-capture-marker)))
  10162. (when bookmark-name
  10163. (with-demoted-errors
  10164. (bookmark-set bookmark-name))))
  10165. (move-marker org-capture-last-stored-marker (point)))
  10166. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10167. (run-hooks 'org-after-refile-insert-hook)))
  10168. (unless org-refile-keep
  10169. (if regionp
  10170. (delete-region (point) (+ (point) (- region-end region-start)))
  10171. (org-preserve-local-variables
  10172. (delete-region
  10173. (and (org-back-to-heading t) (point))
  10174. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10175. (when (featurep 'org-inlinetask)
  10176. (org-inlinetask-remove-END-maybe))
  10177. (setq org-markers-to-move nil)
  10178. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10179. (defun org-refile-goto-last-stored ()
  10180. "Go to the location where the last refile was stored."
  10181. (interactive)
  10182. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10183. (message "This is the location of the last refile"))
  10184. (defun org-refile--get-location (refloc tbl)
  10185. "When user refile to REFLOC, find the associated target in TBL.
  10186. Also check `org-refile-target-table'."
  10187. (car (delq
  10188. nil
  10189. (mapcar
  10190. (lambda (r) (or (assoc r tbl)
  10191. (assoc r org-refile-target-table)))
  10192. (list (replace-regexp-in-string "/$" "" refloc)
  10193. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10194. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10195. "Prompt the user for a refile location, using PROMPT.
  10196. PROMPT should not be suffixed with a colon and a space, because
  10197. this function appends the default value from
  10198. `org-refile-history' automatically, if that is not empty."
  10199. (let ((org-refile-targets org-refile-targets)
  10200. (org-refile-use-outline-path org-refile-use-outline-path))
  10201. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10202. (unless org-refile-target-table
  10203. (user-error "No refile targets"))
  10204. (let* ((cbuf (current-buffer))
  10205. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10206. (cfunc (if (and org-refile-use-outline-path
  10207. org-outline-path-complete-in-steps)
  10208. #'org-olpath-completing-read
  10209. #'completing-read))
  10210. (extra (if org-refile-use-outline-path "/" ""))
  10211. (cbnex (concat (buffer-name) extra))
  10212. (filename (and cfn (expand-file-name cfn)))
  10213. (tbl (mapcar
  10214. (lambda (x)
  10215. (if (and (not (member org-refile-use-outline-path
  10216. '(file full-file-path)))
  10217. (not (equal filename (nth 1 x))))
  10218. (cons (concat (car x) extra " ("
  10219. (file-name-nondirectory (nth 1 x)) ")")
  10220. (cdr x))
  10221. (cons (concat (car x) extra) (cdr x))))
  10222. org-refile-target-table))
  10223. (completion-ignore-case t)
  10224. cdef
  10225. (prompt (concat prompt
  10226. (or (and (car org-refile-history)
  10227. (concat " (default " (car org-refile-history) ")"))
  10228. (and (assoc cbnex tbl) (setq cdef cbnex)
  10229. (concat " (default " cbnex ")"))) ": "))
  10230. pa answ parent-target child parent old-hist)
  10231. (setq old-hist org-refile-history)
  10232. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10233. nil 'org-refile-history (or cdef (car org-refile-history))))
  10234. (if (setq pa (org-refile--get-location answ tbl))
  10235. (progn
  10236. (org-refile-check-position pa)
  10237. (when (or (not org-refile-history)
  10238. (not (eq old-hist org-refile-history))
  10239. (not (equal (car pa) (car org-refile-history))))
  10240. (setq org-refile-history
  10241. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10242. org-refile-history
  10243. (cdr org-refile-history))))
  10244. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10245. (pop org-refile-history)))
  10246. pa)
  10247. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10248. (progn
  10249. (setq parent (match-string 1 answ)
  10250. child (match-string 2 answ))
  10251. (setq parent-target (org-refile--get-location parent tbl))
  10252. (when (and parent-target
  10253. (or (eq new-nodes t)
  10254. (and (eq new-nodes 'confirm)
  10255. (y-or-n-p (format "Create new node \"%s\"? "
  10256. child)))))
  10257. (org-refile-new-child parent-target child)))
  10258. (user-error "Invalid target location")))))
  10259. (declare-function org-string-nw-p "org-macs" (s))
  10260. (defun org-refile-check-position (refile-pointer)
  10261. "Check if the refile pointer matches the headline to which it points."
  10262. (let* ((file (nth 1 refile-pointer))
  10263. (re (nth 2 refile-pointer))
  10264. (pos (nth 3 refile-pointer))
  10265. buffer)
  10266. (if (and (not (markerp pos)) (not file))
  10267. (user-error "Please indicate a target file in the refile path")
  10268. (when (org-string-nw-p re)
  10269. (setq buffer (if (markerp pos)
  10270. (marker-buffer pos)
  10271. (or (find-buffer-visiting file)
  10272. (find-file-noselect file))))
  10273. (with-current-buffer buffer
  10274. (org-with-wide-buffer
  10275. (goto-char pos)
  10276. (beginning-of-line 1)
  10277. (unless (looking-at-p re)
  10278. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10279. (defun org-refile-new-child (parent-target child)
  10280. "Use refile target PARENT-TARGET to add new CHILD below it."
  10281. (unless parent-target
  10282. (error "Cannot find parent for new node"))
  10283. (let ((file (nth 1 parent-target))
  10284. (pos (nth 3 parent-target))
  10285. level)
  10286. (with-current-buffer (or (find-buffer-visiting file)
  10287. (find-file-noselect file))
  10288. (org-with-wide-buffer
  10289. (if pos
  10290. (goto-char pos)
  10291. (goto-char (point-max))
  10292. (unless (bolp) (newline)))
  10293. (when (looking-at org-outline-regexp)
  10294. (setq level (funcall outline-level))
  10295. (org-end-of-subtree t t))
  10296. (org-back-over-empty-lines)
  10297. (insert "\n" (make-string
  10298. (if pos (org-get-valid-level level 1) 1) ?*)
  10299. " " child "\n")
  10300. (beginning-of-line 0)
  10301. (list (concat (car parent-target) "/" child) file "" (point))))))
  10302. (defun org-olpath-completing-read (prompt collection &rest args)
  10303. "Read an outline path like a file name."
  10304. (let ((thetable collection))
  10305. (apply #'completing-read
  10306. prompt
  10307. (lambda (string predicate &optional flag)
  10308. (cond
  10309. ((eq flag nil) (try-completion string thetable))
  10310. ((eq flag t)
  10311. (let ((l (length string)))
  10312. (mapcar (lambda (x)
  10313. (let ((r (substring x l))
  10314. (f (if (string-match " ([^)]*)$" x)
  10315. (match-string 0 x)
  10316. "")))
  10317. (if (string-match "/" r)
  10318. (concat string (substring r 0 (match-end 0)) f)
  10319. x)))
  10320. (all-completions string thetable predicate))))
  10321. ;; Exact match?
  10322. ((eq flag 'lambda) (assoc string thetable))))
  10323. args)))
  10324. ;;;; Dynamic blocks
  10325. (defun org-find-dblock (name)
  10326. "Find the first dynamic block with name NAME in the buffer.
  10327. If not found, stay at current position and return nil."
  10328. (let ((case-fold-search t) pos)
  10329. (save-excursion
  10330. (goto-char (point-min))
  10331. (setq pos (and (re-search-forward
  10332. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10333. (match-beginning 0))))
  10334. (when pos (goto-char pos))
  10335. pos))
  10336. (defun org-create-dblock (plist)
  10337. "Create a dynamic block section, with parameters taken from PLIST.
  10338. PLIST must contain a :name entry which is used as the name of the block."
  10339. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10340. (end-of-line 1)
  10341. (newline))
  10342. (let ((col (current-column))
  10343. (name (plist-get plist :name)))
  10344. (insert "#+BEGIN: " name)
  10345. (while plist
  10346. (if (eq (car plist) :name)
  10347. (setq plist (cddr plist))
  10348. (insert " " (prin1-to-string (pop plist)))))
  10349. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10350. (beginning-of-line -2)))
  10351. (defun org-prepare-dblock ()
  10352. "Prepare dynamic block for refresh.
  10353. This empties the block, puts the cursor at the insert position and returns
  10354. the property list including an extra property :name with the block name."
  10355. (unless (looking-at org-dblock-start-re)
  10356. (user-error "Not at a dynamic block"))
  10357. (let* ((begdel (1+ (match-end 0)))
  10358. (name (org-no-properties (match-string 1)))
  10359. (params (append (list :name name)
  10360. (read (concat "(" (match-string 3) ")")))))
  10361. (save-excursion
  10362. (beginning-of-line 1)
  10363. (skip-chars-forward " \t")
  10364. (setq params (plist-put params :indentation-column (current-column))))
  10365. (unless (re-search-forward org-dblock-end-re nil t)
  10366. (error "Dynamic block not terminated"))
  10367. (setq params
  10368. (append params
  10369. (list :content (buffer-substring
  10370. begdel (match-beginning 0)))))
  10371. (delete-region begdel (match-beginning 0))
  10372. (goto-char begdel)
  10373. (open-line 1)
  10374. params))
  10375. (defun org-map-dblocks (&optional command)
  10376. "Apply COMMAND to all dynamic blocks in the current buffer.
  10377. If COMMAND is not given, use `org-update-dblock'."
  10378. (let ((cmd (or command 'org-update-dblock)))
  10379. (save-excursion
  10380. (goto-char (point-min))
  10381. (while (re-search-forward org-dblock-start-re nil t)
  10382. (goto-char (match-beginning 0))
  10383. (save-excursion
  10384. (condition-case nil
  10385. (funcall cmd)
  10386. (error (message "Error during update of dynamic block"))))
  10387. (unless (re-search-forward org-dblock-end-re nil t)
  10388. (error "Dynamic block not terminated"))))))
  10389. (defun org-dblock-update (&optional arg)
  10390. "User command for updating dynamic blocks.
  10391. Update the dynamic block at point. With prefix ARG, update all dynamic
  10392. blocks in the buffer."
  10393. (interactive "P")
  10394. (if arg
  10395. (org-update-all-dblocks)
  10396. (or (looking-at org-dblock-start-re)
  10397. (org-beginning-of-dblock))
  10398. (org-update-dblock)))
  10399. (defun org-update-dblock ()
  10400. "Update the dynamic block at point.
  10401. This means to empty the block, parse for parameters and then call
  10402. the correct writing function."
  10403. (interactive)
  10404. (save-excursion
  10405. (let* ((win (selected-window))
  10406. (pos (point))
  10407. (line (org-current-line))
  10408. (params (org-prepare-dblock))
  10409. (name (plist-get params :name))
  10410. (indent (plist-get params :indentation-column))
  10411. (cmd (intern (concat "org-dblock-write:" name))))
  10412. (message "Updating dynamic block `%s' at line %d..." name line)
  10413. (funcall cmd params)
  10414. (message "Updating dynamic block `%s' at line %d...done" name line)
  10415. (goto-char pos)
  10416. (when (and indent (> indent 0))
  10417. (setq indent (make-string indent ?\ ))
  10418. (save-excursion
  10419. (select-window win)
  10420. (org-beginning-of-dblock)
  10421. (forward-line 1)
  10422. (while (not (looking-at org-dblock-end-re))
  10423. (insert indent)
  10424. (beginning-of-line 2))
  10425. (when (looking-at org-dblock-end-re)
  10426. (and (looking-at "[ \t]+")
  10427. (replace-match ""))
  10428. (insert indent)))))))
  10429. (defun org-beginning-of-dblock ()
  10430. "Find the beginning of the dynamic block at point.
  10431. Error if there is no such block at point."
  10432. (let ((pos (point))
  10433. beg)
  10434. (end-of-line 1)
  10435. (if (and (re-search-backward org-dblock-start-re nil t)
  10436. (setq beg (match-beginning 0))
  10437. (re-search-forward org-dblock-end-re nil t)
  10438. (> (match-end 0) pos))
  10439. (goto-char beg)
  10440. (goto-char pos)
  10441. (error "Not in a dynamic block"))))
  10442. (defun org-update-all-dblocks ()
  10443. "Update all dynamic blocks in the buffer.
  10444. This function can be used in a hook."
  10445. (interactive)
  10446. (when (derived-mode-p 'org-mode)
  10447. (org-map-dblocks 'org-update-dblock)))
  10448. ;;;; Completion
  10449. (declare-function org-export-backend-options "ox" (cl-x) t)
  10450. (defun org-get-export-keywords ()
  10451. "Return a list of all currently understood export keywords.
  10452. Export keywords include options, block names, attributes and
  10453. keywords relative to each registered export back-end."
  10454. (let (keywords)
  10455. (dolist (backend
  10456. (bound-and-true-p org-export-registered-backends)
  10457. (delq nil keywords))
  10458. ;; Back-end name (for keywords, like #+LATEX:)
  10459. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10460. (dolist (option-entry (org-export-backend-options backend))
  10461. ;; Back-end options.
  10462. (push (nth 1 option-entry) keywords)))))
  10463. (defconst org-options-keywords
  10464. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10465. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10466. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10467. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10468. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10469. (defcustom org-structure-template-alist
  10470. '((?a . "export ascii")
  10471. (?c . "center")
  10472. (?C . "comment")
  10473. (?e . "example")
  10474. (?E . "export")
  10475. (?h . "export html")
  10476. (?l . "export latex")
  10477. (?q . "quote")
  10478. (?s . "src")
  10479. (?v . "verse"))
  10480. "Structure completion elements.
  10481. This is an alist of characters and values. When
  10482. `org-insert-structure-template' is called, an additional key is
  10483. read. The key is first looked up in this alist, and the
  10484. corresponding structure is inserted, with \"#+BEGIN_\" and
  10485. \"#+END_\" added automatically."
  10486. :group 'org-edit-structure
  10487. :type '(repeat
  10488. (cons (character :tag "Key")
  10489. (string :tag "Template")))
  10490. :package-version '(Org . "9.2"))
  10491. (defun org-insert-structure-template (type)
  10492. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10493. First read a character, which can be one of the keys in
  10494. `org-structure-template-alist'. When it is <TAB>, prompt the
  10495. user for a string to use. With an active region, wrap the region
  10496. in the block. Otherwise, insert an empty block."
  10497. (interactive
  10498. (list
  10499. (let* ((key (read-key "Key: "))
  10500. (struct-string
  10501. (or (cdr (assq key org-structure-template-alist))
  10502. (and (= key ?\t)
  10503. (read-string "Structure type: "))
  10504. (user-error "`%c' has no structure definition" key))))
  10505. struct-string)))
  10506. (let* ((region? (use-region-p))
  10507. (s (if region? (region-beginning) (point)))
  10508. (e (copy-marker (if region? (region-end) (point)) t))
  10509. column)
  10510. (when (string-match-p
  10511. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10512. type)
  10513. (org-escape-code-in-region s e))
  10514. (goto-char s)
  10515. (setq column (current-indentation))
  10516. (beginning-of-line)
  10517. (indent-to column)
  10518. (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
  10519. (goto-char e)
  10520. (if (bolp)
  10521. (progn
  10522. (skip-chars-backward " \n\t")
  10523. (forward-line))
  10524. (end-of-line)
  10525. (insert "\n"))
  10526. (indent-to column)
  10527. (insert (format "#+end_%s\n"
  10528. (car (split-string type))))
  10529. (when (or (not region?)
  10530. (string-match-p "src\\|\\`export\\'" type))
  10531. (goto-char s)
  10532. (end-of-line))
  10533. (set-marker e nil)))
  10534. ;;;; TODO, DEADLINE, Comments
  10535. (defun org-toggle-comment ()
  10536. "Change the COMMENT state of an entry."
  10537. (interactive)
  10538. (save-excursion
  10539. (org-back-to-heading)
  10540. (let ((case-fold-search nil))
  10541. (looking-at org-complex-heading-regexp))
  10542. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10543. (skip-chars-forward " \t")
  10544. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10545. (if (org-in-commented-heading-p t)
  10546. (delete-region (point)
  10547. (progn (search-forward " " (line-end-position) 'move)
  10548. (skip-chars-forward " \t")
  10549. (point)))
  10550. (insert org-comment-string)
  10551. (unless (eolp) (insert " ")))))
  10552. (defvar org-last-todo-state-is-todo nil
  10553. "This is non-nil when the last TODO state change led to a TODO state.
  10554. If the last change removed the TODO tag or switched to DONE, then
  10555. this is nil.")
  10556. (defvar org-setting-tags nil) ; dynamically skipped
  10557. (defvar org-todo-setup-filter-hook nil
  10558. "Hook for functions that pre-filter todo specs.
  10559. Each function takes a todo spec and returns either nil or the spec
  10560. transformed into canonical form." )
  10561. (defvar org-todo-get-default-hook nil
  10562. "Hook for functions that get a default item for todo.
  10563. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10564. nil or a string to be used for the todo mark." )
  10565. (defvar org-agenda-headline-snapshot-before-repeat)
  10566. (defun org-current-effective-time ()
  10567. "Return current time adjusted for `org-extend-today-until' variable."
  10568. (let* ((ct (org-current-time))
  10569. (dct (decode-time ct))
  10570. (ct1
  10571. (cond
  10572. (org-use-last-clock-out-time-as-effective-time
  10573. (or (org-clock-get-last-clock-out-time) ct))
  10574. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10575. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10576. (t ct))))
  10577. ct1))
  10578. (defun org-todo-yesterday (&optional arg)
  10579. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10580. (interactive "P")
  10581. (if (eq major-mode 'org-agenda-mode)
  10582. (apply 'org-agenda-todo-yesterday arg)
  10583. (let* ((org-use-effective-time t)
  10584. (hour (nth 2 (decode-time (org-current-time))))
  10585. (org-extend-today-until (1+ hour)))
  10586. (org-todo arg))))
  10587. (defvar org-block-entry-blocking ""
  10588. "First entry preventing the TODO state change.")
  10589. (defun org-cancel-repeater ()
  10590. "Cancel a repeater by setting its numeric value to zero."
  10591. (interactive)
  10592. (save-excursion
  10593. (org-back-to-heading t)
  10594. (let ((bound1 (point))
  10595. (bound0 (save-excursion (outline-next-heading) (point))))
  10596. (when (and (re-search-forward
  10597. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10598. org-deadline-time-regexp "\\)\\|\\("
  10599. org-ts-regexp "\\)")
  10600. bound0 t)
  10601. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10602. bound1 t))
  10603. (replace-match "0" t nil nil 1)))))
  10604. (defvar org-state)
  10605. (defvar org-blocked-by-checkboxes)
  10606. (defun org-todo (&optional arg)
  10607. "Change the TODO state of an item.
  10608. The state of an item is given by a keyword at the start of the heading,
  10609. like
  10610. *** TODO Write paper
  10611. *** DONE Call mom
  10612. The different keywords are specified in the variable `org-todo-keywords'.
  10613. By default the available states are \"TODO\" and \"DONE\". So, for this
  10614. example: when the item starts with TODO, it is changed to DONE.
  10615. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10616. DONE are present, add TODO at the beginning of the heading.
  10617. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10618. state.
  10619. With numeric prefix ARG, switch to that state.
  10620. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10621. next set of TODO \
  10622. keywords (nextset).
  10623. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10624. prefix, circumvent any state blocking.
  10625. With a numeric prefix arg of 0, inhibit note taking for the change.
  10626. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10627. When called through ELisp, arg is also interpreted in the following way:
  10628. `none' -> empty state
  10629. \"\" -> switch to empty state
  10630. `done' -> switch to DONE
  10631. `nextset' -> switch to the next set of keywords
  10632. `previousset' -> switch to the previous set of keywords
  10633. \"WAITING\" -> switch to the specified keyword, but only if it
  10634. really is a member of `org-todo-keywords'."
  10635. (interactive "P")
  10636. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10637. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10638. 'region-start-level 'region))
  10639. org-loop-over-headlines-in-active-region)
  10640. (org-map-entries
  10641. `(org-todo ,arg)
  10642. org-loop-over-headlines-in-active-region
  10643. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10644. (when (equal arg '(16)) (setq arg 'nextset))
  10645. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10646. (let ((org-blocker-hook org-blocker-hook)
  10647. commentp
  10648. case-fold-search)
  10649. (when (equal arg '(64))
  10650. (setq arg nil org-blocker-hook nil))
  10651. (when (and org-blocker-hook
  10652. (or org-inhibit-blocking
  10653. (org-entry-get nil "NOBLOCKING")))
  10654. (setq org-blocker-hook nil))
  10655. (save-excursion
  10656. (catch 'exit
  10657. (org-back-to-heading t)
  10658. (when (org-in-commented-heading-p t)
  10659. (org-toggle-comment)
  10660. (setq commentp t))
  10661. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10662. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10663. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10664. (let* ((match-data (match-data))
  10665. (startpos (copy-marker (line-beginning-position)))
  10666. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10667. (org-log-done org-log-done)
  10668. (org-log-repeat org-log-repeat)
  10669. (org-todo-log-states org-todo-log-states)
  10670. (org-inhibit-logging
  10671. (if (equal arg 0)
  10672. (progn (setq arg nil) 'note) org-inhibit-logging))
  10673. (this (match-string 1))
  10674. (hl-pos (match-beginning 0))
  10675. (head (org-get-todo-sequence-head this))
  10676. (ass (assoc head org-todo-kwd-alist))
  10677. (interpret (nth 1 ass))
  10678. (done-word (nth 3 ass))
  10679. (final-done-word (nth 4 ass))
  10680. (org-last-state (or this ""))
  10681. (completion-ignore-case t)
  10682. (member (member this org-todo-keywords-1))
  10683. (tail (cdr member))
  10684. (org-state (cond
  10685. ((and org-todo-key-trigger
  10686. (or (and (equal arg '(4))
  10687. (eq org-use-fast-todo-selection 'prefix))
  10688. (and (not arg) org-use-fast-todo-selection
  10689. (not (eq org-use-fast-todo-selection
  10690. 'prefix)))))
  10691. ;; Use fast selection.
  10692. (org-fast-todo-selection))
  10693. ((and (equal arg '(4))
  10694. (or (not org-use-fast-todo-selection)
  10695. (not org-todo-key-trigger)))
  10696. ;; Read a state with completion.
  10697. (completing-read
  10698. "State: " (mapcar #'list org-todo-keywords-1)
  10699. nil t))
  10700. ((eq arg 'right)
  10701. (if this
  10702. (if tail (car tail) nil)
  10703. (car org-todo-keywords-1)))
  10704. ((eq arg 'left)
  10705. (unless (equal member org-todo-keywords-1)
  10706. (if this
  10707. (nth (- (length org-todo-keywords-1)
  10708. (length tail) 2)
  10709. org-todo-keywords-1)
  10710. (org-last org-todo-keywords-1))))
  10711. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10712. (setq arg nil))) ;hack to fall back to cycling
  10713. (arg
  10714. ;; User or caller requests a specific state.
  10715. (cond
  10716. ((equal arg "") nil)
  10717. ((eq arg 'none) nil)
  10718. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10719. ((eq arg 'nextset)
  10720. (or (car (cdr (member head org-todo-heads)))
  10721. (car org-todo-heads)))
  10722. ((eq arg 'previousset)
  10723. (let ((org-todo-heads (reverse org-todo-heads)))
  10724. (or (car (cdr (member head org-todo-heads)))
  10725. (car org-todo-heads))))
  10726. ((car (member arg org-todo-keywords-1)))
  10727. ((stringp arg)
  10728. (user-error "State `%s' not valid in this file" arg))
  10729. ((nth (1- (prefix-numeric-value arg))
  10730. org-todo-keywords-1))))
  10731. ((null member) (or head (car org-todo-keywords-1)))
  10732. ((equal this final-done-word) nil) ;-> make empty
  10733. ((null tail) nil) ;-> first entry
  10734. ((memq interpret '(type priority))
  10735. (if (eq this-command last-command)
  10736. (car tail)
  10737. (if (> (length tail) 0)
  10738. (or done-word (car org-done-keywords))
  10739. nil)))
  10740. (t
  10741. (car tail))))
  10742. (org-state (or
  10743. (run-hook-with-args-until-success
  10744. 'org-todo-get-default-hook org-state org-last-state)
  10745. org-state))
  10746. (next (if org-state (concat " " org-state " ") " "))
  10747. (change-plist (list :type 'todo-state-change :from this :to org-state
  10748. :position startpos))
  10749. dolog now-done-p)
  10750. (when org-blocker-hook
  10751. (let (org-blocked-by-checkboxes block-reason)
  10752. (setq org-last-todo-state-is-todo
  10753. (not (member this org-done-keywords)))
  10754. (unless (save-excursion
  10755. (save-match-data
  10756. (org-with-wide-buffer
  10757. (run-hook-with-args-until-failure
  10758. 'org-blocker-hook change-plist))))
  10759. (setq block-reason (if org-blocked-by-checkboxes
  10760. "contained checkboxes"
  10761. (format "\"%s\"" org-block-entry-blocking)))
  10762. (if (called-interactively-p 'interactive)
  10763. (user-error "TODO state change from %s to %s blocked (by %s)"
  10764. this org-state block-reason)
  10765. ;; Fail silently.
  10766. (message "TODO state change from %s to %s blocked (by %s)"
  10767. this org-state block-reason)
  10768. (throw 'exit nil)))))
  10769. (store-match-data match-data)
  10770. (replace-match next t t)
  10771. (cond ((equal this org-state)
  10772. (message "TODO state was already %s" (org-trim next)))
  10773. ((not (pos-visible-in-window-p hl-pos))
  10774. (message "TODO state changed to %s" (org-trim next))))
  10775. (unless head
  10776. (setq head (org-get-todo-sequence-head org-state)
  10777. ass (assoc head org-todo-kwd-alist)
  10778. interpret (nth 1 ass)
  10779. done-word (nth 3 ass)
  10780. final-done-word (nth 4 ass)))
  10781. (when (memq arg '(nextset previousset))
  10782. (message "Keyword-Set %d/%d: %s"
  10783. (- (length org-todo-sets) -1
  10784. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10785. (length org-todo-sets)
  10786. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10787. (setq org-last-todo-state-is-todo
  10788. (not (member org-state org-done-keywords)))
  10789. (setq now-done-p (and (member org-state org-done-keywords)
  10790. (not (member this org-done-keywords))))
  10791. (and logging (org-local-logging logging))
  10792. (when (and (or org-todo-log-states org-log-done)
  10793. (not (eq org-inhibit-logging t))
  10794. (not (memq arg '(nextset previousset))))
  10795. ;; We need to look at recording a time and note.
  10796. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10797. (nth 2 (assoc this org-todo-log-states))))
  10798. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10799. (setq dolog 'time))
  10800. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10801. (and org-state
  10802. (member org-state org-not-done-keywords)
  10803. (not (member this org-not-done-keywords))))
  10804. ;; This is now a todo state and was not one before
  10805. ;; If there was a CLOSED time stamp, get rid of it.
  10806. (org-add-planning-info nil nil 'closed))
  10807. (when (and now-done-p org-log-done)
  10808. ;; It is now done, and it was not done before.
  10809. (org-add-planning-info 'closed (org-current-effective-time))
  10810. (when (and (not dolog) (eq 'note org-log-done))
  10811. (org-add-log-setup 'done org-state this 'note)))
  10812. (when (and org-state dolog)
  10813. ;; This is a non-nil state, and we need to log it.
  10814. (org-add-log-setup 'state org-state this dolog)))
  10815. ;; Fixup tag positioning.
  10816. (org-todo-trigger-tag-changes org-state)
  10817. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  10818. (when org-provide-todo-statistics
  10819. (org-update-parent-todo-statistics))
  10820. (run-hooks 'org-after-todo-state-change-hook)
  10821. (when (and arg (not (member org-state org-done-keywords)))
  10822. (setq head (org-get-todo-sequence-head org-state)))
  10823. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10824. ;; Do we need to trigger a repeat?
  10825. (when now-done-p
  10826. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10827. ;; This is for the agenda, take a snapshot of the headline.
  10828. (save-match-data
  10829. (setq org-agenda-headline-snapshot-before-repeat
  10830. (org-get-heading))))
  10831. (org-auto-repeat-maybe org-state))
  10832. ;; Fixup cursor location if close to the keyword.
  10833. (when (and (outline-on-heading-p)
  10834. (not (bolp))
  10835. (save-excursion (beginning-of-line 1)
  10836. (looking-at org-todo-line-regexp))
  10837. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10838. (goto-char (or (match-end 2) (match-end 1)))
  10839. (and (looking-at " ") (just-one-space)))
  10840. (when org-trigger-hook
  10841. (save-excursion
  10842. (run-hook-with-args 'org-trigger-hook change-plist)))
  10843. (when commentp (org-toggle-comment))))))))
  10844. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10845. "Block turning an entry into a TODO, using the hierarchy.
  10846. This checks whether the current task should be blocked from state
  10847. changes. Such blocking occurs when:
  10848. 1. The task has children which are not all in a completed state.
  10849. 2. A task has a parent with the property :ORDERED:, and there
  10850. are siblings prior to the current task with incomplete
  10851. status.
  10852. 3. The parent of the task is blocked because it has siblings that should
  10853. be done first, or is child of a block grandparent TODO entry."
  10854. (if (not org-enforce-todo-dependencies)
  10855. t ; if locally turned off don't block
  10856. (catch 'dont-block
  10857. ;; If this is not a todo state change, or if this entry is already DONE,
  10858. ;; do not block
  10859. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10860. (member (plist-get change-plist :from)
  10861. (cons 'done org-done-keywords))
  10862. (member (plist-get change-plist :to)
  10863. (cons 'todo org-not-done-keywords))
  10864. (not (plist-get change-plist :to)))
  10865. (throw 'dont-block t))
  10866. ;; If this task has children, and any are undone, it's blocked
  10867. (save-excursion
  10868. (org-back-to-heading t)
  10869. (let ((this-level (funcall outline-level)))
  10870. (outline-next-heading)
  10871. (let ((child-level (funcall outline-level)))
  10872. (while (and (not (eobp))
  10873. (> child-level this-level))
  10874. ;; this todo has children, check whether they are all
  10875. ;; completed
  10876. (when (and (not (org-entry-is-done-p))
  10877. (org-entry-is-todo-p))
  10878. (setq org-block-entry-blocking (org-get-heading))
  10879. (throw 'dont-block nil))
  10880. (outline-next-heading)
  10881. (setq child-level (funcall outline-level))))))
  10882. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  10883. ;; any previous siblings are undone, it's blocked
  10884. (save-excursion
  10885. (org-back-to-heading t)
  10886. (let* ((pos (point))
  10887. (parent-pos (and (org-up-heading-safe) (point)))
  10888. (case-fold-search nil))
  10889. (unless parent-pos (throw 'dont-block t)) ; no parent
  10890. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10891. (forward-line 1)
  10892. (re-search-forward org-not-done-heading-regexp pos t))
  10893. (setq org-block-entry-blocking (match-string 0))
  10894. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  10895. ;; Search further up the hierarchy, to see if an ancestor is blocked
  10896. (while t
  10897. (goto-char parent-pos)
  10898. (unless (looking-at org-not-done-heading-regexp)
  10899. (throw 'dont-block t)) ; do not block, parent is not a TODO
  10900. (setq pos (point))
  10901. (setq parent-pos (and (org-up-heading-safe) (point)))
  10902. (unless parent-pos (throw 'dont-block t)) ; no parent
  10903. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10904. (forward-line 1)
  10905. (re-search-forward org-not-done-heading-regexp pos t)
  10906. (setq org-block-entry-blocking (org-get-heading)))
  10907. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  10908. (defcustom org-track-ordered-property-with-tag nil
  10909. "Should the ORDERED property also be shown as a tag?
  10910. The ORDERED property decides if an entry should require subtasks to be
  10911. completed in sequence. Since a property is not very visible, setting
  10912. this option means that toggling the ORDERED property with the command
  10913. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  10914. not relevant for the behavior, but it makes things more visible.
  10915. Note that toggling the tag with tags commands will not change the property
  10916. and therefore not influence behavior!
  10917. This can be t, meaning the tag ORDERED should be used, It can also be a
  10918. string to select a different tag for this task."
  10919. :group 'org-todo
  10920. :type '(choice
  10921. (const :tag "No tracking" nil)
  10922. (const :tag "Track with ORDERED tag" t)
  10923. (string :tag "Use other tag")))
  10924. (defun org-toggle-ordered-property ()
  10925. "Toggle the ORDERED property of the current entry.
  10926. For better visibility, you can track the value of this property with a tag.
  10927. See variable `org-track-ordered-property-with-tag'."
  10928. (interactive)
  10929. (let* ((t1 org-track-ordered-property-with-tag)
  10930. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  10931. (save-excursion
  10932. (org-back-to-heading)
  10933. (if (org-entry-get nil "ORDERED")
  10934. (progn
  10935. (org-delete-property "ORDERED")
  10936. (and tag (org-toggle-tag tag 'off))
  10937. (message "Subtasks can be completed in arbitrary order"))
  10938. (org-entry-put nil "ORDERED" "t")
  10939. (and tag (org-toggle-tag tag 'on))
  10940. (message "Subtasks must be completed in sequence")))))
  10941. (defun org-block-todo-from-checkboxes (change-plist)
  10942. "Block turning an entry into a TODO, using checkboxes.
  10943. This checks whether the current task should be blocked from state
  10944. changes because there are unchecked boxes in this entry."
  10945. (if (not org-enforce-todo-checkbox-dependencies)
  10946. t ; if locally turned off don't block
  10947. (catch 'dont-block
  10948. ;; If this is not a todo state change, or if this entry is already DONE,
  10949. ;; do not block
  10950. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10951. (member (plist-get change-plist :from)
  10952. (cons 'done org-done-keywords))
  10953. (member (plist-get change-plist :to)
  10954. (cons 'todo org-not-done-keywords))
  10955. (not (plist-get change-plist :to)))
  10956. (throw 'dont-block t))
  10957. ;; If this task has checkboxes that are not checked, it's blocked
  10958. (save-excursion
  10959. (org-back-to-heading t)
  10960. (let ((beg (point)) end)
  10961. (outline-next-heading)
  10962. (setq end (point))
  10963. (goto-char beg)
  10964. (when (org-list-search-forward
  10965. (concat (org-item-beginning-re)
  10966. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  10967. "\\[[- ]\\]")
  10968. end t)
  10969. (when (boundp 'org-blocked-by-checkboxes)
  10970. (setq org-blocked-by-checkboxes t))
  10971. (throw 'dont-block nil))))
  10972. t))) ; do not block
  10973. (defun org-entry-blocked-p ()
  10974. "Non-nil if entry at point is blocked."
  10975. (and (not (org-entry-get nil "NOBLOCKING"))
  10976. (member (org-entry-get nil "TODO") org-not-done-keywords)
  10977. (not (run-hook-with-args-until-failure
  10978. 'org-blocker-hook
  10979. (list :type 'todo-state-change
  10980. :position (point)
  10981. :from 'todo
  10982. :to 'done)))))
  10983. (defun org-update-statistics-cookies (all)
  10984. "Update the statistics cookie, either from TODO or from checkboxes.
  10985. This should be called with the cursor in a line with a statistics
  10986. cookie. When called with a \\[universal-argument] prefix, update
  10987. all statistics cookies in the buffer."
  10988. (interactive "P")
  10989. (if all
  10990. (progn
  10991. (org-update-checkbox-count 'all)
  10992. (org-map-entries 'org-update-parent-todo-statistics))
  10993. (if (not (org-at-heading-p))
  10994. (org-update-checkbox-count)
  10995. (let ((pos (point-marker))
  10996. end l1 l2)
  10997. (ignore-errors (org-back-to-heading t))
  10998. (if (not (org-at-heading-p))
  10999. (org-update-checkbox-count)
  11000. (setq l1 (org-outline-level))
  11001. (setq end (save-excursion
  11002. (outline-next-heading)
  11003. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11004. (point)))
  11005. (if (and (save-excursion
  11006. (re-search-forward
  11007. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11008. (not (save-excursion (re-search-forward
  11009. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11010. (org-update-checkbox-count)
  11011. (if (and l2 (> l2 l1))
  11012. (progn
  11013. (goto-char end)
  11014. (org-update-parent-todo-statistics))
  11015. (goto-char pos)
  11016. (beginning-of-line 1)
  11017. (while (re-search-forward
  11018. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11019. (point-at-eol) t)
  11020. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11021. (goto-char pos)
  11022. (move-marker pos nil)))))
  11023. (defvar org-entry-property-inherited-from) ;; defined below
  11024. (defun org-update-parent-todo-statistics ()
  11025. "Update any statistics cookie in the parent of the current headline.
  11026. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11027. the entire subtree and this will travel up the hierarchy and update
  11028. statistics everywhere."
  11029. (let* ((prop (save-excursion (org-up-heading-safe)
  11030. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11031. (recursive (or (not org-hierarchical-todo-statistics)
  11032. (and prop (string-match "\\<recursive\\>" prop))))
  11033. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11034. 0))
  11035. (first t)
  11036. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11037. level ltoggle l1 new ndel
  11038. (cnt-all 0) (cnt-done 0) is-percent kwd
  11039. checkbox-beg cookie-present)
  11040. (catch 'exit
  11041. (save-excursion
  11042. (beginning-of-line 1)
  11043. (setq ltoggle (funcall outline-level))
  11044. ;; Three situations are to consider:
  11045. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11046. ;; to the top-level ancestor on the headline;
  11047. ;; 2. If parent has "recursive" property, repeat up to the
  11048. ;; headline setting that property, taking inheritance into
  11049. ;; account;
  11050. ;; 3. Else, move up to direct parent and proceed only once.
  11051. (while (and (setq level (org-up-heading-safe))
  11052. (or recursive first)
  11053. (>= (point) lim))
  11054. (setq first nil cookie-present nil)
  11055. (unless (and level
  11056. (not (string-match
  11057. "\\<checkbox\\>"
  11058. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11059. "")))))
  11060. (throw 'exit nil))
  11061. (while (re-search-forward box-re (point-at-eol) t)
  11062. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11063. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11064. (save-match-data
  11065. (unless (outline-next-heading) (throw 'exit nil))
  11066. (while (and (looking-at org-complex-heading-regexp)
  11067. (> (setq l1 (length (match-string 1))) level))
  11068. (setq kwd (and (or recursive (= l1 ltoggle))
  11069. (match-string 2)))
  11070. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11071. (and (eq org-provide-todo-statistics t)
  11072. (or (member kwd org-done-keywords)))
  11073. (and (listp org-provide-todo-statistics)
  11074. (stringp (car org-provide-todo-statistics))
  11075. (or (member kwd org-provide-todo-statistics)
  11076. (member kwd org-done-keywords)))
  11077. (and (listp org-provide-todo-statistics)
  11078. (listp (car org-provide-todo-statistics))
  11079. (or (member kwd (car org-provide-todo-statistics))
  11080. (and (member kwd org-done-keywords)
  11081. (member kwd (cadr org-provide-todo-statistics))))))
  11082. (setq cnt-all (1+ cnt-all))
  11083. (and (eq org-provide-todo-statistics t)
  11084. kwd
  11085. (setq cnt-all (1+ cnt-all))))
  11086. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11087. (member kwd org-done-keywords))
  11088. (and (listp org-provide-todo-statistics)
  11089. (listp (car org-provide-todo-statistics))
  11090. (member kwd org-done-keywords)
  11091. (member kwd (cadr org-provide-todo-statistics)))
  11092. (and (listp org-provide-todo-statistics)
  11093. (stringp (car org-provide-todo-statistics))
  11094. (member kwd org-done-keywords)))
  11095. (setq cnt-done (1+ cnt-done)))
  11096. (outline-next-heading)))
  11097. (setq new
  11098. (if is-percent
  11099. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11100. (max 1 cnt-all)))
  11101. (format "[%d/%d]" cnt-done cnt-all))
  11102. ndel (- (match-end 0) checkbox-beg))
  11103. (goto-char checkbox-beg)
  11104. (insert new)
  11105. (delete-region (point) (+ (point) ndel))
  11106. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11107. (when cookie-present
  11108. (run-hook-with-args 'org-after-todo-statistics-hook
  11109. cnt-done (- cnt-all cnt-done))))))
  11110. (run-hooks 'org-todo-statistics-hook)))
  11111. (defvar org-after-todo-statistics-hook nil
  11112. "Hook that is called after a TODO statistics cookie has been updated.
  11113. Each function is called with two arguments: the number of not-done entries
  11114. and the number of done entries.
  11115. For example, the following function, when added to this hook, will switch
  11116. an entry to DONE when all children are done, and back to TODO when new
  11117. entries are set to a TODO status. Note that this hook is only called
  11118. when there is a statistics cookie in the headline!
  11119. (defun org-summary-todo (n-done n-not-done)
  11120. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11121. (let (org-log-done org-log-states) ; turn off logging
  11122. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11123. ")
  11124. (defvar org-todo-statistics-hook nil
  11125. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11126. This hook runs even if there is no statistics cookie present, in which case
  11127. `org-after-todo-statistics-hook' would not run.")
  11128. (defun org-todo-trigger-tag-changes (state)
  11129. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11130. (let ((l org-todo-state-tags-triggers)
  11131. changes)
  11132. (when (or (not state) (equal state ""))
  11133. (setq changes (append changes (cdr (assoc "" l)))))
  11134. (when (and (stringp state) (> (length state) 0))
  11135. (setq changes (append changes (cdr (assoc state l)))))
  11136. (when (member state org-not-done-keywords)
  11137. (setq changes (append changes (cdr (assq 'todo l)))))
  11138. (when (member state org-done-keywords)
  11139. (setq changes (append changes (cdr (assq 'done l)))))
  11140. (dolist (c changes)
  11141. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11142. (defun org-local-logging (value)
  11143. "Get logging settings from a property VALUE."
  11144. ;; Directly set the variables, they are already local.
  11145. (setq org-log-done nil
  11146. org-log-repeat nil
  11147. org-todo-log-states nil)
  11148. (dolist (w (split-string value))
  11149. (let (a)
  11150. (cond
  11151. ((setq a (assoc w org-startup-options))
  11152. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11153. (set (nth 1 a) (nth 2 a))))
  11154. ((setq a (org-extract-log-state-settings w))
  11155. (and (member (car a) org-todo-keywords-1)
  11156. (push a org-todo-log-states)))))))
  11157. (defun org-get-todo-sequence-head (kwd)
  11158. "Return the head of the TODO sequence to which KWD belongs.
  11159. If KWD is not set, check if there is a text property remembering the
  11160. right sequence."
  11161. (let (p)
  11162. (cond
  11163. ((not kwd)
  11164. (or (get-text-property (point-at-bol) 'org-todo-head)
  11165. (progn
  11166. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11167. nil (point-at-eol)))
  11168. (get-text-property p 'org-todo-head))))
  11169. ((not (member kwd org-todo-keywords-1))
  11170. (car org-todo-keywords-1))
  11171. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11172. (defun org-fast-todo-selection ()
  11173. "Fast TODO keyword selection with single keys.
  11174. Returns the new TODO keyword, or nil if no state change should occur."
  11175. (let* ((fulltable org-todo-key-alist)
  11176. (done-keywords org-done-keywords) ;; needed for the faces.
  11177. (maxlen (apply 'max (mapcar
  11178. (lambda (x)
  11179. (if (stringp (car x)) (string-width (car x)) 0))
  11180. fulltable)))
  11181. (expert nil)
  11182. (fwidth (+ maxlen 3 1 3))
  11183. (ncol (/ (- (window-width) 4) fwidth))
  11184. tg cnt e c tbl
  11185. groups ingroup)
  11186. (save-excursion
  11187. (save-window-excursion
  11188. (if expert
  11189. (set-buffer (get-buffer-create " *Org todo*"))
  11190. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11191. (erase-buffer)
  11192. (setq-local org-done-keywords done-keywords)
  11193. (setq tbl fulltable cnt 0)
  11194. (while (setq e (pop tbl))
  11195. (cond
  11196. ((equal e '(:startgroup))
  11197. (push '() groups) (setq ingroup t)
  11198. (unless (= cnt 0)
  11199. (setq cnt 0)
  11200. (insert "\n"))
  11201. (insert "{ "))
  11202. ((equal e '(:endgroup))
  11203. (setq ingroup nil cnt 0)
  11204. (insert "}\n"))
  11205. ((equal e '(:newline))
  11206. (unless (= cnt 0)
  11207. (setq cnt 0)
  11208. (insert "\n")
  11209. (setq e (car tbl))
  11210. (while (equal (car tbl) '(:newline))
  11211. (insert "\n")
  11212. (setq tbl (cdr tbl)))))
  11213. (t
  11214. (setq tg (car e) c (cdr e))
  11215. (when ingroup (push tg (car groups)))
  11216. (setq tg (org-add-props tg nil 'face
  11217. (org-get-todo-face tg)))
  11218. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11219. (insert "[" c "] " tg (make-string
  11220. (- fwidth 4 (length tg)) ?\ ))
  11221. (when (= (setq cnt (1+ cnt)) ncol)
  11222. (insert "\n")
  11223. (when ingroup (insert " "))
  11224. (setq cnt 0)))))
  11225. (insert "\n")
  11226. (goto-char (point-min))
  11227. (unless expert (org-fit-window-to-buffer))
  11228. (message "[a-z..]:Set [SPC]:clear")
  11229. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11230. (cond
  11231. ((or (= c ?\C-g)
  11232. (and (= c ?q) (not (rassoc c fulltable))))
  11233. (setq quit-flag t))
  11234. ((= c ?\ ) nil)
  11235. ((setq e (rassoc c fulltable) tg (car e))
  11236. tg)
  11237. (t (setq quit-flag t)))))))
  11238. (defun org-entry-is-todo-p ()
  11239. (member (org-get-todo-state) org-not-done-keywords))
  11240. (defun org-entry-is-done-p ()
  11241. (member (org-get-todo-state) org-done-keywords))
  11242. (defun org-get-todo-state ()
  11243. "Return the TODO keyword of the current subtree."
  11244. (save-excursion
  11245. (org-back-to-heading t)
  11246. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11247. (match-end 2)
  11248. (match-string 2))))
  11249. (defun org-at-date-range-p (&optional inactive-ok)
  11250. "Non-nil if point is inside a date range.
  11251. When optional argument INACTIVE-OK is non-nil, also consider
  11252. inactive time ranges.
  11253. When this function returns a non-nil value, match data is set
  11254. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11255. on INACTIVE-OK."
  11256. (interactive)
  11257. (save-excursion
  11258. (catch 'exit
  11259. (let ((pos (point)))
  11260. (skip-chars-backward "^[<\r\n")
  11261. (skip-chars-backward "<[")
  11262. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11263. (>= (match-end 0) pos)
  11264. (throw 'exit t))
  11265. (skip-chars-backward "^<[\r\n")
  11266. (skip-chars-backward "<[")
  11267. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11268. (>= (match-end 0) pos)
  11269. (throw 'exit t)))
  11270. nil)))
  11271. (defun org-get-repeat (&optional timestamp)
  11272. "Check if there is a time-stamp with repeater in this entry.
  11273. Return the repeater, as a string, or nil. Also return nil when
  11274. this function is called before first heading.
  11275. When optional argument TIMESTAMP is a string, extract the
  11276. repeater from there instead."
  11277. (save-match-data
  11278. (cond (timestamp
  11279. (and (string-match org-repeat-re timestamp)
  11280. (match-string-no-properties 1 timestamp)))
  11281. ((org-before-first-heading-p) nil)
  11282. (t
  11283. (save-excursion
  11284. (org-back-to-heading t)
  11285. (let ((end (org-entry-end-position)))
  11286. (catch :repeat
  11287. (while (re-search-forward org-repeat-re end t)
  11288. (when (save-match-data (org-at-timestamp-p 'agenda))
  11289. (throw :repeat (match-string-no-properties 1)))))))))))
  11290. (defvar org-last-changed-timestamp)
  11291. (defvar org-last-inserted-timestamp)
  11292. (defvar org-log-post-message)
  11293. (defvar org-log-note-purpose)
  11294. (defvar org-log-note-how nil)
  11295. (defvar org-log-note-extra)
  11296. (defun org-auto-repeat-maybe (done-word)
  11297. "Check if the current headline contains a repeated time-stamp.
  11298. If yes, set TODO state back to what it was and change the base date
  11299. of repeating deadline/scheduled time stamps to new date.
  11300. This function is run automatically after each state change to a DONE state."
  11301. (let* ((repeat (org-get-repeat))
  11302. (aa (assoc org-last-state org-todo-kwd-alist))
  11303. (interpret (nth 1 aa))
  11304. (head (nth 2 aa))
  11305. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11306. (msg "Entry repeats: ")
  11307. (org-log-done nil)
  11308. (org-todo-log-states nil)
  11309. (end (copy-marker (org-entry-end-position))))
  11310. (unwind-protect
  11311. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11312. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11313. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11314. (and (stringp org-todo-repeat-to-state)
  11315. org-todo-repeat-to-state)
  11316. (and org-todo-repeat-to-state org-last-state))))
  11317. (org-todo (cond
  11318. ((and to-state (member to-state org-todo-keywords-1))
  11319. to-state)
  11320. ((eq interpret 'type) org-last-state)
  11321. (head)
  11322. (t 'none))))
  11323. (org-back-to-heading t)
  11324. (org-add-planning-info nil nil 'closed)
  11325. ;; When `org-log-repeat' is non-nil or entry contains
  11326. ;; a clock, set LAST_REPEAT property.
  11327. (when (or org-log-repeat
  11328. (catch :clock
  11329. (save-excursion
  11330. (while (re-search-forward org-clock-line-re end t)
  11331. (when (org-at-clock-log-p) (throw :clock t))))))
  11332. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11333. (org-time-stamp-format t t)
  11334. (current-time))))
  11335. (when org-log-repeat
  11336. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11337. (memq 'org-add-log-note post-command-hook))
  11338. ;; We are already setup for some record.
  11339. (when (eq org-log-repeat 'note)
  11340. ;; Make sure we take a note, not only a time stamp.
  11341. (setq org-log-note-how 'note))
  11342. ;; Set up for taking a record.
  11343. (org-add-log-setup 'state
  11344. (or done-word (car org-done-keywords))
  11345. org-last-state
  11346. org-log-repeat)))
  11347. (let ((planning-re (regexp-opt
  11348. (list org-scheduled-string org-deadline-string))))
  11349. (while (re-search-forward org-ts-regexp end t)
  11350. (let* ((ts (match-string 0))
  11351. (planning? (org-at-planning-p))
  11352. (type (if (not planning?) "Plain:"
  11353. (save-excursion
  11354. (re-search-backward
  11355. planning-re (line-beginning-position) t)
  11356. (match-string 0)))))
  11357. (cond
  11358. ;; Ignore fake time-stamps (e.g., within comments).
  11359. ((not (org-at-timestamp-p 'agenda)))
  11360. ;; Time-stamps without a repeater are usually
  11361. ;; skipped. However, a SCHEDULED time-stamp without
  11362. ;; one is removed, as they are no longer relevant.
  11363. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11364. ts))
  11365. (when (equal type org-scheduled-string)
  11366. (org-remove-timestamp-with-keyword type)))
  11367. (t
  11368. (let ((n (string-to-number (match-string 2 ts)))
  11369. (what (match-string 3 ts)))
  11370. (when (equal what "w") (setq n (* n 7) what "d"))
  11371. (when (and (equal what "h")
  11372. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11373. ts)))
  11374. (user-error
  11375. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11376. has been set"
  11377. n))
  11378. ;; Preparation, see if we need to modify the start
  11379. ;; date for the change.
  11380. (when (match-end 1)
  11381. (let ((time (save-match-data
  11382. (org-time-string-to-time ts))))
  11383. (cond
  11384. ((equal (match-string 1 ts) ".")
  11385. ;; Shift starting date to today
  11386. (org-timestamp-change
  11387. (- (org-today) (time-to-days time))
  11388. 'day))
  11389. ((equal (match-string 1 ts) "+")
  11390. (let ((nshiftmax 10)
  11391. (nshift 0))
  11392. (while (or (= nshift 0)
  11393. (not (time-less-p (current-time) time)))
  11394. (when (= (cl-incf nshift) nshiftmax)
  11395. (or (y-or-n-p
  11396. (format "%d repeater intervals were not \
  11397. enough to shift date past today. Continue? "
  11398. nshift))
  11399. (user-error "Abort")))
  11400. (org-timestamp-change n (cdr (assoc what whata)))
  11401. (org-in-regexp org-ts-regexp3)
  11402. (setq ts (match-string 1))
  11403. (setq time
  11404. (save-match-data
  11405. (org-time-string-to-time ts)))))
  11406. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11407. ;; Rematch, so that we have everything in place
  11408. ;; for the real shift.
  11409. (org-in-regexp org-ts-regexp3)
  11410. (setq ts (match-string 1))
  11411. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11412. ts)))))
  11413. (save-excursion
  11414. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11415. (setq msg
  11416. (concat
  11417. msg type " " org-last-changed-timestamp " "))))))))
  11418. (setq org-log-post-message msg)
  11419. (message "%s" msg))
  11420. (set-marker end nil))))
  11421. (defun org-show-todo-tree (arg)
  11422. "Make a compact tree which shows all headlines marked with TODO.
  11423. The tree will show the lines where the regexp matches, and all higher
  11424. headlines above the match.
  11425. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11426. With a numeric prefix N, construct a sparse tree for the Nth element
  11427. of `org-todo-keywords-1'."
  11428. (interactive "P")
  11429. (let ((case-fold-search nil)
  11430. (kwd-re
  11431. (cond ((null arg) org-not-done-regexp)
  11432. ((equal arg '(4))
  11433. (let ((kwd
  11434. (completing-read "Keyword (or KWD1|KWD2|...): "
  11435. (mapcar #'list org-todo-keywords-1))))
  11436. (concat "\\("
  11437. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11438. "\\)\\>")))
  11439. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11440. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11441. org-todo-keywords-1)))
  11442. (t (user-error "Invalid prefix argument: %s" arg)))))
  11443. (message "%d TODO entries found"
  11444. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11445. (defun org--deadline-or-schedule (arg type time)
  11446. "Insert DEADLINE or SCHEDULE information in current entry.
  11447. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11448. `org-schedule' for information about ARG and TIME arguments."
  11449. (let* ((deadline? (eq type 'deadline))
  11450. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11451. (log (if deadline? org-log-redeadline org-log-reschedule))
  11452. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11453. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11454. ;; Save repeater cookie from either TIME or current scheduled
  11455. ;; time stamp. We are going to insert it back at the end of
  11456. ;; the process.
  11457. (repeater (or (and (org-string-nw-p time)
  11458. ;; We use `org-repeat-re' because we need
  11459. ;; to tell the difference between a real
  11460. ;; repeater and a time delta, e.g. "+2d".
  11461. (string-match org-repeat-re time)
  11462. (match-string 1 time))
  11463. (and (org-string-nw-p old-date)
  11464. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11465. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11466. old-date)
  11467. (match-string 1 old-date)))))
  11468. (pcase arg
  11469. (`(4)
  11470. (when (and old-date log)
  11471. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11472. nil old-date log))
  11473. (org-remove-timestamp-with-keyword keyword)
  11474. (message (if deadline? "Item no longer has a deadline."
  11475. "Item is no longer scheduled.")))
  11476. (`(16)
  11477. (save-excursion
  11478. (org-back-to-heading t)
  11479. (let ((regexp (if deadline? org-deadline-time-regexp
  11480. org-scheduled-time-regexp)))
  11481. (if (not (re-search-forward regexp (line-end-position 2) t))
  11482. (user-error (if deadline? "No deadline information to update"
  11483. "No scheduled information to update"))
  11484. (let* ((rpl0 (match-string 1))
  11485. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11486. (msg (if deadline? "Warn starting from" "Delay until")))
  11487. (replace-match
  11488. (concat keyword
  11489. " <" rpl
  11490. (format " -%dd"
  11491. (abs (- (time-to-days
  11492. (save-match-data
  11493. (org-read-date
  11494. nil t nil msg old-date-time)))
  11495. (time-to-days old-date-time))))
  11496. ">") t t))))))
  11497. (_
  11498. (org-add-planning-info type time 'closed)
  11499. (when (and old-date
  11500. log
  11501. (not (equal old-date org-last-inserted-timestamp)))
  11502. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11503. org-last-inserted-timestamp
  11504. old-date
  11505. log))
  11506. (when repeater
  11507. (save-excursion
  11508. (org-back-to-heading t)
  11509. (when (re-search-forward
  11510. (concat keyword " " org-last-inserted-timestamp)
  11511. (line-end-position 2)
  11512. t)
  11513. (goto-char (1- (match-end 0)))
  11514. (insert " " repeater)
  11515. (setq org-last-inserted-timestamp
  11516. (concat (substring org-last-inserted-timestamp 0 -1)
  11517. " " repeater
  11518. (substring org-last-inserted-timestamp -1))))))
  11519. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11520. org-last-inserted-timestamp)))))
  11521. (defun org-deadline (arg &optional time)
  11522. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11523. With one universal prefix argument, remove any deadline from the item.
  11524. With two universal prefix arguments, prompt for a warning delay.
  11525. With argument TIME, set the deadline at the corresponding date. TIME
  11526. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11527. (interactive "P")
  11528. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11529. (org-map-entries
  11530. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11531. nil
  11532. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11533. 'region-start-level
  11534. 'region)
  11535. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11536. (org--deadline-or-schedule arg 'deadline time)))
  11537. (defun org-schedule (arg &optional time)
  11538. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11539. With one universal prefix argument, remove any scheduling date from the item.
  11540. With two universal prefix arguments, prompt for a delay cookie.
  11541. With argument TIME, scheduled at the corresponding date. TIME can
  11542. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11543. (interactive "P")
  11544. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11545. (org-map-entries
  11546. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11547. nil
  11548. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11549. 'region-start-level
  11550. 'region)
  11551. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11552. (org--deadline-or-schedule arg 'scheduled time)))
  11553. (defun org-get-scheduled-time (pom &optional inherit)
  11554. "Get the scheduled time as a time tuple, of a format suitable
  11555. for calling org-schedule with, or if there is no scheduling,
  11556. returns nil."
  11557. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11558. (when time
  11559. (apply 'encode-time (org-parse-time-string time)))))
  11560. (defun org-get-deadline-time (pom &optional inherit)
  11561. "Get the deadline as a time tuple, of a format suitable for
  11562. calling org-deadline with, or if there is no scheduling, returns
  11563. nil."
  11564. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11565. (when time
  11566. (apply 'encode-time (org-parse-time-string time)))))
  11567. (defun org-remove-timestamp-with-keyword (keyword)
  11568. "Remove all time stamps with KEYWORD in the current entry."
  11569. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11570. beg)
  11571. (save-excursion
  11572. (org-back-to-heading t)
  11573. (setq beg (point))
  11574. (outline-next-heading)
  11575. (while (re-search-backward re beg t)
  11576. (replace-match "")
  11577. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11578. (equal (char-before) ?\ ))
  11579. (backward-delete-char 1)
  11580. (when (string-match "^[ \t]*$" (buffer-substring
  11581. (point-at-bol) (point-at-eol)))
  11582. (delete-region (point-at-bol)
  11583. (min (point-max) (1+ (point-at-eol))))))))))
  11584. (defvar org-time-was-given) ; dynamically scoped parameter
  11585. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11586. (defun org-at-planning-p ()
  11587. "Non-nil when point is on a planning info line."
  11588. ;; This is as accurate and faster than `org-element-at-point' since
  11589. ;; planning info location is fixed in the section.
  11590. (org-with-wide-buffer
  11591. (beginning-of-line)
  11592. (and (looking-at-p org-planning-line-re)
  11593. (eq (point)
  11594. (ignore-errors
  11595. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11596. (org-back-to-heading t)
  11597. (org-with-limited-levels (org-back-to-heading t)))
  11598. (line-beginning-position 2))))))
  11599. (defun org-add-planning-info (what &optional time &rest remove)
  11600. "Insert new timestamp with keyword in the planning line.
  11601. WHAT indicates what kind of time stamp to add. It is a symbol
  11602. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11603. the time to use. If none is given, the user is prompted for
  11604. a date. REMOVE indicates what kind of entries to remove. An old
  11605. WHAT entry will also be removed."
  11606. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11607. (catch 'exit
  11608. (when (and (memq what '(scheduled deadline))
  11609. (or (not time)
  11610. (and (stringp time)
  11611. (string-match "^[-+]+[0-9]" time))))
  11612. ;; Try to get a default date/time from existing timestamp
  11613. (save-excursion
  11614. (org-back-to-heading t)
  11615. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11616. (when (re-search-forward (if (eq what 'scheduled)
  11617. org-scheduled-time-regexp
  11618. org-deadline-time-regexp)
  11619. end t)
  11620. (setq ts (match-string 1)
  11621. default-time (apply 'encode-time (org-parse-time-string ts))
  11622. default-input (and ts (org-get-compact-tod ts)))))))
  11623. (when what
  11624. (setq time
  11625. (if (stringp time)
  11626. ;; This is a string (relative or absolute), set
  11627. ;; proper date.
  11628. (apply #'encode-time
  11629. (org-read-date-analyze
  11630. time default-time (decode-time default-time)))
  11631. ;; If necessary, get the time from the user
  11632. (or time (org-read-date nil 'to-time nil nil
  11633. default-time default-input)))))
  11634. (org-with-wide-buffer
  11635. (org-back-to-heading t)
  11636. (forward-line)
  11637. (unless (bolp) (insert "\n"))
  11638. (cond ((looking-at-p org-planning-line-re)
  11639. ;; Move to current indentation.
  11640. (skip-chars-forward " \t")
  11641. ;; Check if we have to remove something.
  11642. (dolist (type (if what (cons what remove) remove))
  11643. (save-excursion
  11644. (when (re-search-forward
  11645. (cl-case type
  11646. (closed org-closed-time-regexp)
  11647. (deadline org-deadline-time-regexp)
  11648. (scheduled org-scheduled-time-regexp)
  11649. (otherwise
  11650. (error "Invalid planning type: %s" type)))
  11651. (line-end-position) t)
  11652. ;; Delete until next keyword or end of line.
  11653. (delete-region
  11654. (match-beginning 0)
  11655. (if (re-search-forward org-keyword-time-not-clock-regexp
  11656. (line-end-position)
  11657. t)
  11658. (match-beginning 0)
  11659. (line-end-position))))))
  11660. ;; If there is nothing more to add and no more keyword
  11661. ;; is left, remove the line completely.
  11662. (if (and (looking-at-p "[ \t]*$") (not what))
  11663. (delete-region (line-beginning-position)
  11664. (line-beginning-position 2))
  11665. ;; If we removed last keyword, do not leave trailing
  11666. ;; white space at the end of line.
  11667. (let ((p (point)))
  11668. (save-excursion
  11669. (end-of-line)
  11670. (unless (= (skip-chars-backward " \t" p) 0)
  11671. (delete-region (point) (line-end-position)))))))
  11672. ((not what) (throw 'exit nil)) ; Nothing to do.
  11673. (t (insert-before-markers "\n")
  11674. (backward-char 1)
  11675. (when org-adapt-indentation
  11676. (indent-to-column (1+ (org-outline-level))))))
  11677. (when what
  11678. ;; Insert planning keyword.
  11679. (insert (cl-case what
  11680. (closed org-closed-string)
  11681. (deadline org-deadline-string)
  11682. (scheduled org-scheduled-string)
  11683. (otherwise (error "Invalid planning type: %s" what)))
  11684. " ")
  11685. ;; Insert associated timestamp.
  11686. (let ((ts (org-insert-time-stamp
  11687. time
  11688. (or org-time-was-given
  11689. (and (eq what 'closed) org-log-done-with-time))
  11690. (eq what 'closed)
  11691. nil nil (list org-end-time-was-given))))
  11692. (unless (eolp) (insert " "))
  11693. ts))))))
  11694. (defvar org-log-note-marker (make-marker)
  11695. "Marker pointing at the entry where the note is to be inserted.")
  11696. (defvar org-log-note-purpose nil)
  11697. (defvar org-log-note-state nil)
  11698. (defvar org-log-note-previous-state nil)
  11699. (defvar org-log-note-extra nil)
  11700. (defvar org-log-note-window-configuration nil)
  11701. (defvar org-log-note-return-to (make-marker))
  11702. (defvar org-log-note-effective-time nil
  11703. "Remembered current time so that dynamically scoped
  11704. `org-extend-today-until' affects timestamps in state change log")
  11705. (defvar org-log-post-message nil
  11706. "Message to be displayed after a log note has been stored.
  11707. The auto-repeater uses this.")
  11708. (defun org-add-note ()
  11709. "Add a note to the current entry.
  11710. This is done in the same way as adding a state change note."
  11711. (interactive)
  11712. (org-add-log-setup 'note))
  11713. (defun org-log-beginning (&optional create)
  11714. "Return expected start of log notes in current entry.
  11715. When optional argument CREATE is non-nil, the function creates
  11716. a drawer to store notes, if necessary. Returned position ignores
  11717. narrowing."
  11718. (org-with-wide-buffer
  11719. (let ((drawer (org-log-into-drawer)))
  11720. (cond
  11721. (drawer
  11722. (org-end-of-meta-data)
  11723. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11724. (end (if (org-at-heading-p) (point)
  11725. (save-excursion (outline-next-heading) (point))))
  11726. (case-fold-search t))
  11727. (catch 'exit
  11728. ;; Try to find existing drawer.
  11729. (while (re-search-forward regexp end t)
  11730. (let ((element (org-element-at-point)))
  11731. (when (eq (org-element-type element) 'drawer)
  11732. (let ((cend (org-element-property :contents-end element)))
  11733. (when (and (not org-log-states-order-reversed) cend)
  11734. (goto-char cend)))
  11735. (throw 'exit nil))))
  11736. ;; No drawer found. Create one, if permitted.
  11737. (when create
  11738. (unless (bolp) (insert "\n"))
  11739. (let ((beg (point)))
  11740. (insert ":" drawer ":\n:END:\n")
  11741. (org-indent-region beg (point))
  11742. (org-flag-region
  11743. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11744. (end-of-line -1)))))
  11745. (t
  11746. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11747. (skip-chars-forward " \t\n")
  11748. (beginning-of-line)
  11749. (unless org-log-states-order-reversed
  11750. (org-skip-over-state-notes)
  11751. (skip-chars-backward " \t\n")
  11752. (forward-line)))))
  11753. (if (bolp) (point) (line-beginning-position 2))))
  11754. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11755. "Set up the post command hook to take a note.
  11756. If this is about to TODO state change, the new state is expected in STATE.
  11757. HOW is an indicator what kind of note should be created.
  11758. EXTRA is additional text that will be inserted into the notes buffer."
  11759. (move-marker org-log-note-marker (point))
  11760. (setq org-log-note-purpose purpose
  11761. org-log-note-state state
  11762. org-log-note-previous-state prev-state
  11763. org-log-note-how how
  11764. org-log-note-extra extra
  11765. org-log-note-effective-time (org-current-effective-time))
  11766. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11767. (defun org-skip-over-state-notes ()
  11768. "Skip past the list of State notes in an entry."
  11769. (when (ignore-errors (goto-char (org-in-item-p)))
  11770. (let* ((struct (org-list-struct))
  11771. (prevs (org-list-prevs-alist struct))
  11772. (regexp
  11773. (concat "[ \t]*- +"
  11774. (replace-regexp-in-string
  11775. " +" " +"
  11776. (org-replace-escapes
  11777. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11778. `(("%d" . ,org-ts-regexp-inactive)
  11779. ("%D" . ,org-ts-regexp)
  11780. ("%s" . "\"\\S-+\"")
  11781. ("%S" . "\"\\S-+\"")
  11782. ("%t" . ,org-ts-regexp-inactive)
  11783. ("%T" . ,org-ts-regexp)
  11784. ("%u" . ".*?")
  11785. ("%U" . ".*?")))))))
  11786. (while (looking-at-p regexp)
  11787. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11788. (org-list-get-item-end (point) struct)))))))
  11789. (defun org-add-log-note (&optional _purpose)
  11790. "Pop up a window for taking a note, and add this note later."
  11791. (remove-hook 'post-command-hook 'org-add-log-note)
  11792. (setq org-log-note-window-configuration (current-window-configuration))
  11793. (delete-other-windows)
  11794. (move-marker org-log-note-return-to (point))
  11795. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11796. (goto-char org-log-note-marker)
  11797. (org-switch-to-buffer-other-window "*Org Note*")
  11798. (erase-buffer)
  11799. (if (memq org-log-note-how '(time state))
  11800. (org-store-log-note)
  11801. (let ((org-inhibit-startup t)) (org-mode))
  11802. (insert (format "# Insert note for %s.
  11803. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11804. (cond
  11805. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  11806. ((eq org-log-note-purpose 'done) "closed todo item")
  11807. ((eq org-log-note-purpose 'state)
  11808. (format "state change from \"%s\" to \"%s\""
  11809. (or org-log-note-previous-state "")
  11810. (or org-log-note-state "")))
  11811. ((eq org-log-note-purpose 'reschedule)
  11812. "rescheduling")
  11813. ((eq org-log-note-purpose 'delschedule)
  11814. "no longer scheduled")
  11815. ((eq org-log-note-purpose 'redeadline)
  11816. "changing deadline")
  11817. ((eq org-log-note-purpose 'deldeadline)
  11818. "removing deadline")
  11819. ((eq org-log-note-purpose 'refile)
  11820. "refiling")
  11821. ((eq org-log-note-purpose 'note)
  11822. "this entry")
  11823. (t (error "This should not happen")))))
  11824. (when org-log-note-extra (insert org-log-note-extra))
  11825. (setq-local org-finish-function 'org-store-log-note)
  11826. (run-hooks 'org-log-buffer-setup-hook)))
  11827. (defvar org-note-abort nil) ; dynamically scoped
  11828. (defun org-store-log-note ()
  11829. "Finish taking a log note, and insert it to where it belongs."
  11830. (let ((txt (prog1 (buffer-string)
  11831. (kill-buffer)))
  11832. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11833. lines)
  11834. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11835. (setq txt (replace-match "" t t txt)))
  11836. (when (string-match "\\s-+\\'" txt)
  11837. (setq txt (replace-match "" t t txt)))
  11838. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11839. (when (org-string-nw-p note)
  11840. (setq note
  11841. (org-replace-escapes
  11842. note
  11843. (list (cons "%u" (user-login-name))
  11844. (cons "%U" user-full-name)
  11845. (cons "%t" (format-time-string
  11846. (org-time-stamp-format 'long 'inactive)
  11847. org-log-note-effective-time))
  11848. (cons "%T" (format-time-string
  11849. (org-time-stamp-format 'long nil)
  11850. org-log-note-effective-time))
  11851. (cons "%d" (format-time-string
  11852. (org-time-stamp-format nil 'inactive)
  11853. org-log-note-effective-time))
  11854. (cons "%D" (format-time-string
  11855. (org-time-stamp-format nil nil)
  11856. org-log-note-effective-time))
  11857. (cons "%s" (cond
  11858. ((not org-log-note-state) "")
  11859. ((string-match-p org-ts-regexp
  11860. org-log-note-state)
  11861. (format "\"[%s]\""
  11862. (substring org-log-note-state 1 -1)))
  11863. (t (format "\"%s\"" org-log-note-state))))
  11864. (cons "%S"
  11865. (cond
  11866. ((not org-log-note-previous-state) "")
  11867. ((string-match-p org-ts-regexp
  11868. org-log-note-previous-state)
  11869. (format "\"[%s]\""
  11870. (substring
  11871. org-log-note-previous-state 1 -1)))
  11872. (t (format "\"%s\""
  11873. org-log-note-previous-state)))))))
  11874. (when lines (setq note (concat note " \\\\")))
  11875. (push note lines))
  11876. (when (and lines (not org-note-abort))
  11877. (with-current-buffer (marker-buffer org-log-note-marker)
  11878. (org-with-wide-buffer
  11879. ;; Find location for the new note.
  11880. (goto-char org-log-note-marker)
  11881. (set-marker org-log-note-marker nil)
  11882. ;; Note associated to a clock is to be located right after
  11883. ;; the clock. Do not move point.
  11884. (unless (eq org-log-note-purpose 'clock-out)
  11885. (goto-char (org-log-beginning t)))
  11886. ;; Make sure point is at the beginning of an empty line.
  11887. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  11888. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  11889. ;; In an existing list, add a new item at the top level.
  11890. ;; Otherwise, indent line like a regular one.
  11891. (let ((itemp (org-in-item-p)))
  11892. (if itemp
  11893. (indent-line-to
  11894. (let ((struct (save-excursion
  11895. (goto-char itemp) (org-list-struct))))
  11896. (org-list-get-ind (org-list-get-top-point struct) struct)))
  11897. (org-indent-line)))
  11898. (insert (org-list-bullet-string "-") (pop lines))
  11899. (let ((ind (org-list-item-body-column (line-beginning-position))))
  11900. (dolist (line lines)
  11901. (insert "\n")
  11902. (indent-line-to ind)
  11903. (insert line)))
  11904. (message "Note stored")
  11905. (org-back-to-heading t))
  11906. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  11907. ;; from within `org-add-log-note' because `buffer-undo-list'
  11908. ;; is then modified outside of `org-with-remote-undo'.
  11909. (when (eq this-command 'org-agenda-todo)
  11910. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  11911. ;; Don't add undo information when called from `org-agenda-todo'.
  11912. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  11913. (set-window-configuration org-log-note-window-configuration)
  11914. (with-current-buffer (marker-buffer org-log-note-return-to)
  11915. (goto-char org-log-note-return-to))
  11916. (move-marker org-log-note-return-to nil)
  11917. (when org-log-post-message (message "%s" org-log-post-message))))
  11918. (defun org-remove-empty-drawer-at (pos)
  11919. "Remove an empty drawer at position POS.
  11920. POS may also be a marker."
  11921. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  11922. (org-with-wide-buffer
  11923. (goto-char pos)
  11924. (let ((drawer (org-element-at-point)))
  11925. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  11926. (not (org-element-property :contents-begin drawer)))
  11927. (delete-region (org-element-property :begin drawer)
  11928. (progn (goto-char (org-element-property :end drawer))
  11929. (skip-chars-backward " \r\t\n")
  11930. (forward-line)
  11931. (point))))))))
  11932. (defvar org-ts-type nil)
  11933. (defun org-sparse-tree (&optional arg type)
  11934. "Create a sparse tree, prompt for the details.
  11935. This command can create sparse trees. You first need to select the type
  11936. of match used to create the tree:
  11937. t Show all TODO entries.
  11938. T Show entries with a specific TODO keyword.
  11939. m Show entries selected by a tags/property match.
  11940. p Enter a property name and its value (both with completion on existing
  11941. names/values) and show entries with that property.
  11942. r Show entries matching a regular expression (`/' can be used as well).
  11943. b Show deadlines and scheduled items before a date.
  11944. a Show deadlines and scheduled items after a date.
  11945. d Show deadlines due within `org-deadline-warning-days'.
  11946. D Show deadlines and scheduled items between a date range."
  11947. (interactive "P")
  11948. (setq type (or type org-sparse-tree-default-date-type))
  11949. (setq org-ts-type type)
  11950. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  11951. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  11952. \[c]ycle through date types: %s"
  11953. (cl-case type
  11954. (all "all timestamps")
  11955. (scheduled "only scheduled")
  11956. (deadline "only deadline")
  11957. (active "only active timestamps")
  11958. (inactive "only inactive timestamps")
  11959. (closed "with a closed time-stamp")
  11960. (otherwise "scheduled/deadline")))
  11961. (let ((answer (read-char-exclusive)))
  11962. (cl-case answer
  11963. (?c
  11964. (org-sparse-tree
  11965. arg
  11966. (cadr
  11967. (memq type '(nil all scheduled deadline active inactive closed)))))
  11968. (?d (call-interactively 'org-check-deadlines))
  11969. (?b (call-interactively 'org-check-before-date))
  11970. (?a (call-interactively 'org-check-after-date))
  11971. (?D (call-interactively 'org-check-dates-range))
  11972. (?t (call-interactively 'org-show-todo-tree))
  11973. (?T (org-show-todo-tree '(4)))
  11974. (?m (call-interactively 'org-match-sparse-tree))
  11975. ((?p ?P)
  11976. (let* ((kwd (completing-read
  11977. "Property: " (mapcar #'list (org-buffer-property-keys))))
  11978. (value (completing-read
  11979. "Value: " (mapcar #'list (org-property-values kwd)))))
  11980. (unless (string-match "\\`{.*}\\'" value)
  11981. (setq value (concat "\"" value "\"")))
  11982. (org-match-sparse-tree arg (concat kwd "=" value))))
  11983. ((?r ?R ?/) (call-interactively 'org-occur))
  11984. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  11985. (defvar-local org-occur-highlights nil
  11986. "List of overlays used for occur matches.")
  11987. (defvar-local org-occur-parameters nil
  11988. "Parameters of the active org-occur calls.
  11989. This is a list, each call to org-occur pushes as cons cell,
  11990. containing the regular expression and the callback, onto the list.
  11991. The list can contain several entries if `org-occur' has been called
  11992. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  11993. will only contain one set of parameters. When the highlights are
  11994. removed (for example with `C-c C-c', or with the next edit (depending
  11995. on `org-remove-highlights-with-change'), this variable is emptied
  11996. as well.")
  11997. (defun org-occur (regexp &optional keep-previous callback)
  11998. "Make a compact tree which shows all matches of REGEXP.
  11999. The tree will show the lines where the regexp matches, and any other context
  12000. defined in `org-show-context-detail', which see.
  12001. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12002. done by a previous call to `org-occur' will be kept, to allow stacking of
  12003. calls to this command.
  12004. Optional argument CALLBACK can be a function of no argument. In this case,
  12005. it is called with point at the end of the match, match data being set
  12006. accordingly. Current match is shown only if the return value is non-nil.
  12007. The function must neither move point nor alter narrowing."
  12008. (interactive "sRegexp: \nP")
  12009. (when (equal regexp "")
  12010. (user-error "Regexp cannot be empty"))
  12011. (unless keep-previous
  12012. (org-remove-occur-highlights nil nil t))
  12013. (push (cons regexp callback) org-occur-parameters)
  12014. (let ((cnt 0))
  12015. (save-excursion
  12016. (goto-char (point-min))
  12017. (when (or (not keep-previous) ; do not want to keep
  12018. (not org-occur-highlights)) ; no previous matches
  12019. ;; hide everything
  12020. (org-overview))
  12021. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12022. (isearch-no-upper-case-p regexp t)
  12023. org-occur-case-fold-search)))
  12024. (while (re-search-forward regexp nil t)
  12025. (when (or (not callback)
  12026. (save-match-data (funcall callback)))
  12027. (setq cnt (1+ cnt))
  12028. (when org-highlight-sparse-tree-matches
  12029. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12030. (org-show-context 'occur-tree)))))
  12031. (when org-remove-highlights-with-change
  12032. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12033. nil 'local))
  12034. (unless org-sparse-tree-open-archived-trees
  12035. (org-hide-archived-subtrees (point-min) (point-max)))
  12036. (run-hooks 'org-occur-hook)
  12037. (when (called-interactively-p 'interactive)
  12038. (message "%d match(es) for regexp %s" cnt regexp))
  12039. cnt))
  12040. (defun org-occur-next-match (&optional n _reset)
  12041. "Function for `next-error-function' to find sparse tree matches.
  12042. N is the number of matches to move, when negative move backwards.
  12043. This function always goes back to the starting point when no
  12044. match is found."
  12045. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12046. (search-func (if (< n 0)
  12047. 'previous-single-char-property-change
  12048. 'next-single-char-property-change))
  12049. (n (abs n))
  12050. (pos (point))
  12051. p1)
  12052. (catch 'exit
  12053. (while (setq p1 (funcall search-func (point) 'org-type))
  12054. (when (equal p1 limit)
  12055. (goto-char pos)
  12056. (user-error "No more matches"))
  12057. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12058. (setq n (1- n))
  12059. (when (= n 0)
  12060. (goto-char p1)
  12061. (throw 'exit (point))))
  12062. (goto-char p1))
  12063. (goto-char p1)
  12064. (user-error "No more matches"))))
  12065. (defun org-highlight-new-match (beg end)
  12066. "Highlight from BEG to END and mark the highlight is an occur headline."
  12067. (let ((ov (make-overlay beg end)))
  12068. (overlay-put ov 'face 'secondary-selection)
  12069. (overlay-put ov 'org-type 'org-occur)
  12070. (push ov org-occur-highlights)))
  12071. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12072. "Remove the occur highlights from the buffer.
  12073. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12074. from the `before-change-functions' in the current buffer."
  12075. (interactive)
  12076. (unless org-inhibit-highlight-removal
  12077. (mapc #'delete-overlay org-occur-highlights)
  12078. (setq org-occur-highlights nil)
  12079. (setq org-occur-parameters nil)
  12080. (unless noremove
  12081. (remove-hook 'before-change-functions
  12082. 'org-remove-occur-highlights 'local))))
  12083. ;;;; Priorities
  12084. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12085. "Regular expression matching the priority indicator.")
  12086. (defvar org-remove-priority-next-time nil)
  12087. (defun org-priority-up ()
  12088. "Increase the priority of the current item."
  12089. (interactive)
  12090. (org-priority 'up))
  12091. (defun org-priority-down ()
  12092. "Decrease the priority of the current item."
  12093. (interactive)
  12094. (org-priority 'down))
  12095. (defun org-priority (&optional action _show)
  12096. "Change the priority of an item.
  12097. ACTION can be `set', `up', `down', or a character."
  12098. (interactive "P")
  12099. (if (equal action '(4))
  12100. (org-show-priority)
  12101. (unless org-enable-priority-commands
  12102. (user-error "Priority commands are disabled"))
  12103. (setq action (or action 'set))
  12104. (let (current new news have remove)
  12105. (save-excursion
  12106. (org-back-to-heading t)
  12107. (when (looking-at org-priority-regexp)
  12108. (setq current (string-to-char (match-string 2))
  12109. have t))
  12110. (cond
  12111. ((eq action 'remove)
  12112. (setq remove t new ?\ ))
  12113. ((or (eq action 'set)
  12114. (integerp action))
  12115. (if (not (eq action 'set))
  12116. (setq new action)
  12117. (message "Priority %c-%c, SPC to remove: "
  12118. org-highest-priority org-lowest-priority)
  12119. (save-match-data
  12120. (setq new (read-char-exclusive))))
  12121. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12122. (= (upcase org-lowest-priority) org-lowest-priority))
  12123. (setq new (upcase new)))
  12124. (cond ((equal new ?\ ) (setq remove t))
  12125. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12126. (user-error "Priority must be between `%c' and `%c'"
  12127. org-highest-priority org-lowest-priority))))
  12128. ((eq action 'up)
  12129. (setq new (if have
  12130. (1- current) ; normal cycling
  12131. ;; last priority was empty
  12132. (if (eq last-command this-command)
  12133. org-lowest-priority ; wrap around empty to lowest
  12134. ;; default
  12135. (if org-priority-start-cycle-with-default
  12136. org-default-priority
  12137. (1- org-default-priority))))))
  12138. ((eq action 'down)
  12139. (setq new (if have
  12140. (1+ current) ; normal cycling
  12141. ;; last priority was empty
  12142. (if (eq last-command this-command)
  12143. org-highest-priority ; wrap around empty to highest
  12144. ;; default
  12145. (if org-priority-start-cycle-with-default
  12146. org-default-priority
  12147. (1+ org-default-priority))))))
  12148. (t (user-error "Invalid action")))
  12149. (when (or (< (upcase new) org-highest-priority)
  12150. (> (upcase new) org-lowest-priority))
  12151. (if (and (memq action '(up down))
  12152. (not have) (not (eq last-command this-command)))
  12153. ;; `new' is from default priority
  12154. (error
  12155. "The default can not be set, see `org-default-priority' why")
  12156. ;; normal cycling: `new' is beyond highest/lowest priority
  12157. ;; and is wrapped around to the empty priority
  12158. (setq remove t)))
  12159. (setq news (format "%c" new))
  12160. (if have
  12161. (if remove
  12162. (replace-match "" t t nil 1)
  12163. (replace-match news t t nil 2))
  12164. (if remove
  12165. (user-error "No priority cookie found in line")
  12166. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12167. (if (match-end 2)
  12168. (progn
  12169. (goto-char (match-end 2))
  12170. (insert " [#" news "]"))
  12171. (goto-char (match-beginning 3))
  12172. (insert "[#" news "] "))))
  12173. (org-set-tags nil 'align))
  12174. (if remove
  12175. (message "Priority removed")
  12176. (message "Priority of current item set to %s" news)))))
  12177. (defun org-show-priority ()
  12178. "Show the priority of the current item.
  12179. This priority is composed of the main priority given with the [#A] cookies,
  12180. and by additional input from the age of a schedules or deadline entry."
  12181. (interactive)
  12182. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12183. (org-get-at-bol 'priority)
  12184. (save-excursion
  12185. (save-match-data
  12186. (beginning-of-line)
  12187. (and (looking-at org-heading-regexp)
  12188. (org-get-priority (match-string 0))))))))
  12189. (message "Priority is %d" (if pri pri -1000))))
  12190. (defun org-get-priority (s)
  12191. "Find priority cookie and return priority."
  12192. (save-match-data
  12193. (if (functionp org-get-priority-function)
  12194. (funcall org-get-priority-function)
  12195. (if (not (string-match org-priority-regexp s))
  12196. (* 1000 (- org-lowest-priority org-default-priority))
  12197. (* 1000 (- org-lowest-priority
  12198. (string-to-char (match-string 2 s))))))))
  12199. ;;;; Tags
  12200. (defvar org-agenda-archives-mode)
  12201. (defvar org-map-continue-from nil
  12202. "Position from where mapping should continue.
  12203. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12204. (defvar org-scanner-tags nil
  12205. "The current tag list while the tags scanner is running.")
  12206. (defvar org-trust-scanner-tags nil
  12207. "Should `org-get-tags-at' use the tags for the scanner.
  12208. This is for internal dynamical scoping only.
  12209. When this is non-nil, the function `org-get-tags-at' will return the value
  12210. of `org-scanner-tags' instead of building the list by itself. This
  12211. can lead to large speed-ups when the tags scanner is used in a file with
  12212. many entries, and when the list of tags is retrieved, for example to
  12213. obtain a list of properties. Building the tags list for each entry in such
  12214. a file becomes an N^2 operation - but with this variable set, it scales
  12215. as N.")
  12216. (defvar org--matcher-tags-todo-only nil)
  12217. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12218. "Scan headline tags with inheritance and produce output ACTION.
  12219. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12220. or `agenda' to produce an entry list for an agenda view. It can also be
  12221. a Lisp form or a function that should be called at each matched headline, in
  12222. this case the return value is a list of all return values from these calls.
  12223. MATCHER is a function accepting three arguments, returning
  12224. a non-nil value whenever a given set of tags qualifies a headline
  12225. for inclusion. See `org-make-tags-matcher' for more information.
  12226. As a special case, it can also be set to t (respectively nil) in
  12227. order to match all (respectively none) headline.
  12228. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12229. included in the output.
  12230. START-LEVEL can be a string with asterisks, reducing the scope to
  12231. headlines matching this string."
  12232. (require 'org-agenda)
  12233. (let* ((re (concat "^"
  12234. (if start-level
  12235. ;; Get the correct level to match
  12236. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12237. org-outline-regexp)
  12238. " *\\(\\<\\("
  12239. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12240. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12241. (props (list 'face 'default
  12242. 'done-face 'org-agenda-done
  12243. 'undone-face 'default
  12244. 'mouse-face 'highlight
  12245. 'org-not-done-regexp org-not-done-regexp
  12246. 'org-todo-regexp org-todo-regexp
  12247. 'org-complex-heading-regexp org-complex-heading-regexp
  12248. 'help-echo
  12249. (format "mouse-2 or RET jump to Org file %S"
  12250. (abbreviate-file-name
  12251. (or (buffer-file-name (buffer-base-buffer))
  12252. (buffer-name (buffer-base-buffer)))))))
  12253. (org-map-continue-from nil)
  12254. lspos tags tags-list
  12255. (tags-alist (list (cons 0 org-file-tags)))
  12256. (llast 0) rtn rtn1 level category i txt
  12257. todo marker entry priority
  12258. ts-date ts-date-type ts-date-pair)
  12259. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12260. (setq action (list 'lambda nil action)))
  12261. (save-excursion
  12262. (goto-char (point-min))
  12263. (when (eq action 'sparse-tree)
  12264. (org-overview)
  12265. (org-remove-occur-highlights))
  12266. (while (let (case-fold-search)
  12267. (re-search-forward re nil t))
  12268. (setq org-map-continue-from nil)
  12269. (catch :skip
  12270. (setq todo
  12271. ;; TODO: is the 1-2 difference a bug?
  12272. (when (match-end 1) (match-string-no-properties 2))
  12273. tags (when (match-end 4) (match-string-no-properties 4)))
  12274. (goto-char (setq lspos (match-beginning 0)))
  12275. (setq level (org-reduced-level (org-outline-level))
  12276. category (org-get-category))
  12277. (when (eq action 'agenda)
  12278. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12279. ts-date (car ts-date-pair)
  12280. ts-date-type (cdr ts-date-pair)))
  12281. (setq i llast llast level)
  12282. ;; remove tag lists from same and sublevels
  12283. (while (>= i level)
  12284. (when (setq entry (assoc i tags-alist))
  12285. (setq tags-alist (delete entry tags-alist)))
  12286. (setq i (1- i)))
  12287. ;; add the next tags
  12288. (when tags
  12289. (setq tags (org-split-string tags ":")
  12290. tags-alist
  12291. (cons (cons level tags) tags-alist)))
  12292. ;; compile tags for current headline
  12293. (setq tags-list
  12294. (if org-use-tag-inheritance
  12295. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12296. tags)
  12297. org-scanner-tags tags-list)
  12298. (when org-use-tag-inheritance
  12299. (setcdr (car tags-alist)
  12300. (mapcar (lambda (x)
  12301. (setq x (copy-sequence x))
  12302. (org-add-prop-inherited x))
  12303. (cdar tags-alist))))
  12304. (when (and tags org-use-tag-inheritance
  12305. (or (not (eq t org-use-tag-inheritance))
  12306. org-tags-exclude-from-inheritance))
  12307. ;; Selective inheritance, remove uninherited ones.
  12308. (setcdr (car tags-alist)
  12309. (org-remove-uninherited-tags (cdar tags-alist))))
  12310. (when (and
  12311. ;; eval matcher only when the todo condition is OK
  12312. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12313. (if (functionp matcher)
  12314. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12315. (funcall matcher todo tags-list level))
  12316. matcher))
  12317. ;; Call the skipper, but return t if it does not
  12318. ;; skip, so that the `and' form continues evaluating.
  12319. (progn
  12320. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12321. t)
  12322. ;; Check if timestamps are deselecting this entry
  12323. (or (not todo-only)
  12324. (and (member todo org-todo-keywords-1)
  12325. (or (not org-agenda-tags-todo-honor-ignore-options)
  12326. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12327. ;; select this headline
  12328. (cond
  12329. ((eq action 'sparse-tree)
  12330. (and org-highlight-sparse-tree-matches
  12331. (org-get-heading) (match-end 0)
  12332. (org-highlight-new-match
  12333. (match-beginning 1) (match-end 1)))
  12334. (org-show-context 'tags-tree))
  12335. ((eq action 'agenda)
  12336. (setq txt (org-agenda-format-item
  12337. ""
  12338. (concat
  12339. (if (eq org-tags-match-list-sublevels 'indented)
  12340. (make-string (1- level) ?.) "")
  12341. (org-get-heading))
  12342. (make-string level ?\s)
  12343. category
  12344. tags-list)
  12345. priority (org-get-priority txt))
  12346. (goto-char lspos)
  12347. (setq marker (org-agenda-new-marker))
  12348. (org-add-props txt props
  12349. 'org-marker marker 'org-hd-marker marker 'org-category category
  12350. 'todo-state todo
  12351. 'ts-date ts-date
  12352. 'priority priority
  12353. 'type (concat "tagsmatch" ts-date-type))
  12354. (push txt rtn))
  12355. ((functionp action)
  12356. (setq org-map-continue-from nil)
  12357. (save-excursion
  12358. (setq rtn1 (funcall action))
  12359. (push rtn1 rtn)))
  12360. (t (user-error "Invalid action")))
  12361. ;; if we are to skip sublevels, jump to end of subtree
  12362. (unless org-tags-match-list-sublevels
  12363. (org-end-of-subtree t)
  12364. (backward-char 1))))
  12365. ;; Get the correct position from where to continue
  12366. (if org-map-continue-from
  12367. (goto-char org-map-continue-from)
  12368. (and (= (point) lspos) (end-of-line 1)))))
  12369. (when (and (eq action 'sparse-tree)
  12370. (not org-sparse-tree-open-archived-trees))
  12371. (org-hide-archived-subtrees (point-min) (point-max)))
  12372. (nreverse rtn)))
  12373. (defun org-remove-uninherited-tags (tags)
  12374. "Remove all tags that are not inherited from the list TAGS."
  12375. (cond
  12376. ((eq org-use-tag-inheritance t)
  12377. (if org-tags-exclude-from-inheritance
  12378. (org-delete-all org-tags-exclude-from-inheritance tags)
  12379. tags))
  12380. ((not org-use-tag-inheritance) nil)
  12381. ((stringp org-use-tag-inheritance)
  12382. (delq nil (mapcar
  12383. (lambda (x)
  12384. (if (and (string-match org-use-tag-inheritance x)
  12385. (not (member x org-tags-exclude-from-inheritance)))
  12386. x nil))
  12387. tags)))
  12388. ((listp org-use-tag-inheritance)
  12389. (delq nil (mapcar
  12390. (lambda (x)
  12391. (if (member x org-use-tag-inheritance) x nil))
  12392. tags)))))
  12393. (defun org-match-sparse-tree (&optional todo-only match)
  12394. "Create a sparse tree according to tags string MATCH.
  12395. MATCH is a string with match syntax. It can contain a selection
  12396. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12397. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12398. those. See the manual for details.
  12399. If optional argument TODO-ONLY is non-nil, only select lines that
  12400. are also TODO tasks."
  12401. (interactive "P")
  12402. (org-agenda-prepare-buffers (list (current-buffer)))
  12403. (let ((org--matcher-tags-todo-only todo-only))
  12404. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12405. org--matcher-tags-todo-only)))
  12406. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12407. (defvar org-cached-props nil)
  12408. (defun org-cached-entry-get (pom property)
  12409. (if (or (eq t org-use-property-inheritance)
  12410. (and (stringp org-use-property-inheritance)
  12411. (let ((case-fold-search t))
  12412. (string-match-p org-use-property-inheritance property)))
  12413. (and (listp org-use-property-inheritance)
  12414. (member-ignore-case property org-use-property-inheritance)))
  12415. ;; Caching is not possible, check it directly.
  12416. (org-entry-get pom property 'inherit)
  12417. ;; Get all properties, so we can do complicated checks easily.
  12418. (cdr (assoc-string property
  12419. (or org-cached-props
  12420. (setq org-cached-props (org-entry-properties pom)))
  12421. t))))
  12422. (defun org-global-tags-completion-table (&optional files)
  12423. "Return the list of all tags in all agenda buffer/files.
  12424. Optional FILES argument is a list of files which can be used
  12425. instead of the agenda files."
  12426. (save-excursion
  12427. (org-uniquify
  12428. (delq nil
  12429. (apply #'append
  12430. (mapcar
  12431. (lambda (file)
  12432. (set-buffer (find-file-noselect file))
  12433. (mapcar (lambda (x)
  12434. (and (stringp (car-safe x))
  12435. (list (car-safe x))))
  12436. (or org-current-tag-alist (org-get-buffer-tags))))
  12437. (if (car-safe files) files
  12438. (org-agenda-files))))))))
  12439. (defun org-make-tags-matcher (match)
  12440. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12441. Returns a cons of the selection string MATCH and a function
  12442. implementing the matcher.
  12443. The matcher is to be called at an Org entry, with point on the
  12444. headline, and returns non-nil if the entry matches the selection
  12445. string MATCH. It must be called with three arguments: the TODO
  12446. keyword at the entry (or nil if none), the list of all tags at
  12447. the entry including inherited ones and the reduced level of the
  12448. headline. Additionally, the category of the entry, if any, must
  12449. be specified as the text property `org-category' on the headline.
  12450. This function sets the variable `org--matcher-tags-todo-only' to
  12451. a non-nil value if the matcher restricts matching to TODO
  12452. entries, otherwise it is not touched.
  12453. See also `org-scan-tags'."
  12454. (unless match
  12455. ;; Get a new match request, with completion against the global
  12456. ;; tags table and the local tags in current buffer.
  12457. (let ((org-last-tags-completion-table
  12458. (org-uniquify
  12459. (delq nil (append (org-get-buffer-tags)
  12460. (org-global-tags-completion-table))))))
  12461. (setq match
  12462. (completing-read
  12463. "Match: "
  12464. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12465. (let ((match0 match)
  12466. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12467. (start 0)
  12468. tagsmatch todomatch tagsmatcher todomatcher)
  12469. ;; Expand group tags.
  12470. (setq match (org-tags-expand match))
  12471. ;; Check if there is a TODO part of this match, which would be the
  12472. ;; part after a "/". To make sure that this slash is not part of
  12473. ;; a property value to be matched against, we also check that
  12474. ;; there is no / after that slash. First, find the last slash.
  12475. (let ((s 0))
  12476. (while (string-match "/+" match s)
  12477. (setq start (match-beginning 0))
  12478. (setq s (match-end 0))))
  12479. (if (and (string-match "/+" match start)
  12480. (not (string-match-p "\"" match start)))
  12481. ;; Match contains also a TODO-matching request.
  12482. (progn
  12483. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12484. (setq todomatch (substring match (match-end 0)))
  12485. (when (string-prefix-p "!" todomatch)
  12486. (setq org--matcher-tags-todo-only t)
  12487. (setq todomatch (substring todomatch 1)))
  12488. (when (string-match "\\`\\s-*\\'" todomatch)
  12489. (setq todomatch nil)))
  12490. ;; Only matching tags.
  12491. (setq tagsmatch match)
  12492. (setq todomatch nil))
  12493. ;; Make the tags matcher.
  12494. (when (org-string-nw-p tagsmatch)
  12495. (let ((orlist nil)
  12496. (orterms (org-split-string tagsmatch "|"))
  12497. term)
  12498. (while (setq term (pop orterms))
  12499. (while (and (equal (substring term -1) "\\") orterms)
  12500. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12501. (while (string-match re term)
  12502. (let* ((rest (substring term (match-end 0)))
  12503. (minus (and (match-end 1)
  12504. (equal (match-string 1 term) "-")))
  12505. (tag (save-match-data
  12506. (replace-regexp-in-string
  12507. "\\\\-" "-" (match-string 2 term))))
  12508. (regexp (eq (string-to-char tag) ?{))
  12509. (levelp (match-end 4))
  12510. (propp (match-end 5))
  12511. (mm
  12512. (cond
  12513. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12514. (levelp
  12515. `(,(org-op-to-function (match-string 3 term))
  12516. level
  12517. ,(string-to-number (match-string 4 term))))
  12518. (propp
  12519. (let* ((gv (pcase (upcase (match-string 5 term))
  12520. ("CATEGORY"
  12521. '(get-text-property (point) 'org-category))
  12522. ("TODO" 'todo)
  12523. (p `(org-cached-entry-get nil ,p))))
  12524. (pv (match-string 7 term))
  12525. (regexp (eq (string-to-char pv) ?{))
  12526. (strp (eq (string-to-char pv) ?\"))
  12527. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12528. (po (org-op-to-function (match-string 6 term)
  12529. (if timep 'time strp))))
  12530. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12531. (when timep (setq pv (org-matcher-time pv)))
  12532. (cond ((and regexp (eq po 'org<>))
  12533. `(not (string-match ,pv (or ,gv ""))))
  12534. (regexp `(string-match ,pv (or ,gv "")))
  12535. (strp `(,po (or ,gv "") ,pv))
  12536. (t
  12537. `(,po
  12538. (string-to-number (or ,gv ""))
  12539. ,(string-to-number pv))))))
  12540. (t `(member ,tag tags-list)))))
  12541. (push (if minus `(not ,mm) mm) tagsmatcher)
  12542. (setq term rest)))
  12543. (push `(and ,@tagsmatcher) orlist)
  12544. (setq tagsmatcher nil))
  12545. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12546. ;; Make the TODO matcher.
  12547. (when (org-string-nw-p todomatch)
  12548. (let ((orlist nil))
  12549. (dolist (term (org-split-string todomatch "|"))
  12550. (while (string-match re term)
  12551. (let* ((minus (and (match-end 1)
  12552. (equal (match-string 1 term) "-")))
  12553. (kwd (match-string 2 term))
  12554. (regexp (eq (string-to-char kwd) ?{))
  12555. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12556. `(equal todo ,kwd))))
  12557. (push (if minus `(not ,mm) mm) todomatcher))
  12558. (setq term (substring term (match-end 0))))
  12559. (push (if (> (length todomatcher) 1)
  12560. (cons 'and todomatcher)
  12561. (car todomatcher))
  12562. orlist)
  12563. (setq todomatcher nil))
  12564. (setq todomatcher (cons 'or orlist))))
  12565. ;; Return the string and function of the matcher. If no
  12566. ;; tags-specific or todo-specific matcher exists, match
  12567. ;; everything.
  12568. (let ((matcher (if (and tagsmatcher todomatcher)
  12569. `(and ,tagsmatcher ,todomatcher)
  12570. (or tagsmatcher todomatcher t))))
  12571. (when org--matcher-tags-todo-only
  12572. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12573. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12574. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12575. "Expand group tags in MATCH.
  12576. This replaces every group tag in MATCH with a regexp tag search.
  12577. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12578. will be replaced like this:
  12579. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12580. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12581. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12582. Replacing by a regexp preserves the structure of the match.
  12583. E.g., this expansion
  12584. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12585. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12586. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12587. A group tag in MATCH can contain regular expressions of its own.
  12588. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12589. will be replaced like this:
  12590. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12591. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12592. assumed to be a single group tag, and the function will return
  12593. the list of tags in this group.
  12594. When DOWNCASE is non-nil, expand downcased TAGS."
  12595. (if org-group-tags
  12596. (let* ((case-fold-search t)
  12597. (stable org-mode-syntax-table)
  12598. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12599. (taggroups (if downcased
  12600. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12601. taggroups)
  12602. taggroups))
  12603. (taggroups-keys (mapcar #'car taggroups))
  12604. (return-match (if downcased (downcase match) match))
  12605. (count 0)
  12606. (work-already-expanded tags-already-expanded)
  12607. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12608. ;; @ and _ are allowed as word-components in tags.
  12609. (modify-syntax-entry ?@ "w" stable)
  12610. (modify-syntax-entry ?_ "w" stable)
  12611. ;; Temporarily replace regexp-expressions in the match-expression.
  12612. (while (string-match "{.+?}" return-match)
  12613. (cl-incf count)
  12614. (push (match-string 0 return-match) regexps-in-match)
  12615. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12616. (while (and taggroups-keys
  12617. (with-syntax-table stable
  12618. (string-match
  12619. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12620. (regexp-opt taggroups-keys) "\\>\\)")
  12621. return-match)))
  12622. (let* ((dir (match-string 1 return-match))
  12623. (tag (match-string 2 return-match))
  12624. (tag (if downcased (downcase tag) tag)))
  12625. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12626. (member tag work-already-expanded))
  12627. (setq tags-in-group (assoc tag taggroups))
  12628. (push tag work-already-expanded)
  12629. ;; Recursively expand each tag in the group, if the tag hasn't
  12630. ;; already been expanded. Restore the match-data after all recursive calls.
  12631. (save-match-data
  12632. (let (tags-expanded)
  12633. (dolist (x (cdr tags-in-group))
  12634. (if (and (member x taggroups-keys)
  12635. (not (member x work-already-expanded)))
  12636. (setq tags-expanded
  12637. (delete-dups
  12638. (append
  12639. (org-tags-expand x t downcased
  12640. work-already-expanded)
  12641. tags-expanded)))
  12642. (setq tags-expanded
  12643. (append (list x) tags-expanded)))
  12644. (setq work-already-expanded
  12645. (delete-dups
  12646. (append tags-expanded
  12647. work-already-expanded))))
  12648. (setq tags-in-group
  12649. (delete-dups (cons (car tags-in-group)
  12650. tags-expanded)))))
  12651. ;; Filter tag-regexps from tags.
  12652. (setq regexp-in-group-escaped
  12653. (delq nil (mapcar (lambda (x)
  12654. (if (stringp x)
  12655. (and (equal "{" (substring x 0 1))
  12656. (equal "}" (substring x -1))
  12657. x)
  12658. x))
  12659. tags-in-group))
  12660. regexp-in-group
  12661. (mapcar (lambda (x)
  12662. (substring x 1 -1))
  12663. regexp-in-group-escaped)
  12664. tags-in-group
  12665. (delq nil (mapcar (lambda (x)
  12666. (if (stringp x)
  12667. (and (not (equal "{" (substring x 0 1)))
  12668. (not (equal "}" (substring x -1)))
  12669. x)
  12670. x))
  12671. tags-in-group)))
  12672. ;; If single-as-list, do no more in the while-loop.
  12673. (if (not single-as-list)
  12674. (progn
  12675. (when regexp-in-group
  12676. (setq regexp-in-group
  12677. (concat "\\|"
  12678. (mapconcat 'identity regexp-in-group
  12679. "\\|"))))
  12680. (setq tags-in-group
  12681. (concat dir
  12682. "{\\<"
  12683. (regexp-opt tags-in-group)
  12684. "\\>"
  12685. regexp-in-group
  12686. "}"))
  12687. (when (stringp tags-in-group)
  12688. (org-add-props tags-in-group '(grouptag t)))
  12689. (setq return-match
  12690. (replace-match tags-in-group t t return-match)))
  12691. (setq tags-in-group
  12692. (append regexp-in-group-escaped tags-in-group))))
  12693. (setq taggroups-keys (delete tag taggroups-keys))))
  12694. ;; Add the regular expressions back into the match-expression again.
  12695. (while regexps-in-match
  12696. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12697. (pop regexps-in-match)
  12698. return-match t t))
  12699. (cl-decf count))
  12700. (if single-as-list
  12701. (if tags-in-group tags-in-group (list return-match))
  12702. return-match))
  12703. (if single-as-list
  12704. (list (if downcased (downcase match) match))
  12705. match)))
  12706. (defun org-op-to-function (op &optional stringp)
  12707. "Turn an operator into the appropriate function."
  12708. (setq op
  12709. (cond
  12710. ((equal op "<" ) '(< string< org-time<))
  12711. ((equal op ">" ) '(> org-string> org-time>))
  12712. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12713. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12714. ((member op '("=" "==")) '(= string= org-time=))
  12715. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  12716. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12717. (defun org<> (a b) (not (= a b)))
  12718. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  12719. (defun org-string>= (a b) (not (string< a b)))
  12720. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  12721. (defun org-string<> (a b) (not (string= a b)))
  12722. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  12723. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  12724. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  12725. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  12726. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  12727. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  12728. (defun org-2ft (s)
  12729. "Convert S to a floating point time.
  12730. If S is already a number, just return it. If it is a string, parse
  12731. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  12732. (cond
  12733. ((numberp s) s)
  12734. ((stringp s)
  12735. (condition-case nil
  12736. (float-time (apply #'encode-time (org-parse-time-string s)))
  12737. (error 0.)))
  12738. (t 0.)))
  12739. (defun org-time-today ()
  12740. "Time in seconds today at 0:00.
  12741. Returns the float number of seconds since the beginning of the
  12742. epoch to the beginning of today (00:00)."
  12743. (float-time (apply 'encode-time
  12744. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  12745. (defun org-matcher-time (s)
  12746. "Interpret a time comparison value."
  12747. (save-match-data
  12748. (cond
  12749. ((string= s "<now>") (float-time))
  12750. ((string= s "<today>") (org-time-today))
  12751. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  12752. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  12753. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  12754. (+ (org-time-today)
  12755. (* (string-to-number (match-string 1 s))
  12756. (cdr (assoc (match-string 2 s)
  12757. '(("d" . 86400.0) ("w" . 604800.0)
  12758. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  12759. (t (org-2ft s)))))
  12760. (defun org-match-any-p (re list)
  12761. "Does re match any element of list?"
  12762. (setq list (mapcar (lambda (x) (string-match re x)) list))
  12763. (delq nil list))
  12764. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12765. (defvar org-tags-overlay (make-overlay 1 1))
  12766. (delete-overlay org-tags-overlay)
  12767. (defun org-get-local-tags-at (&optional pos)
  12768. "Get a list of tags defined in the current headline."
  12769. (org-get-tags-at pos 'local))
  12770. (defun org-get-local-tags ()
  12771. "Get a list of tags defined in the current headline."
  12772. (org-get-tags-at nil 'local))
  12773. (defun org-get-tags-at (&optional pos local)
  12774. "Get a list of all headline tags applicable at POS.
  12775. POS defaults to point. If tags are inherited, the list contains
  12776. the targets in the same sequence as the headlines appear, i.e.
  12777. the tags of the current headline come last.
  12778. When LOCAL is non-nil, only return tags from the current headline,
  12779. ignore inherited ones."
  12780. (interactive)
  12781. (if (and org-trust-scanner-tags
  12782. (or (not pos) (equal pos (point)))
  12783. (not local))
  12784. org-scanner-tags
  12785. (let (tags ltags lastpos parent)
  12786. (save-excursion
  12787. (save-restriction
  12788. (widen)
  12789. (goto-char (or pos (point)))
  12790. (save-match-data
  12791. (catch 'done
  12792. (condition-case nil
  12793. (progn
  12794. (org-back-to-heading t)
  12795. (while (not (equal lastpos (point)))
  12796. (setq lastpos (point))
  12797. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  12798. (setq ltags (org-split-string
  12799. (match-string-no-properties 1) ":"))
  12800. (when parent
  12801. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  12802. (setq tags (append
  12803. (if parent
  12804. (org-remove-uninherited-tags ltags)
  12805. ltags)
  12806. tags)))
  12807. (or org-use-tag-inheritance (throw 'done t))
  12808. (when local (throw 'done t))
  12809. (or (org-up-heading-safe) (error nil))
  12810. (setq parent t)))
  12811. (error nil)))))
  12812. (if local
  12813. tags
  12814. (reverse (delete-dups
  12815. (reverse (append
  12816. (org-remove-uninherited-tags
  12817. org-file-tags)
  12818. tags)))))))))
  12819. (defun org-add-prop-inherited (s)
  12820. (add-text-properties 0 (length s) '(inherited t) s)
  12821. s)
  12822. (defun org-toggle-tag (tag &optional onoff)
  12823. "Toggle the tag TAG for the current line.
  12824. If ONOFF is `on' or `off', don't toggle but set to this state."
  12825. (save-excursion
  12826. (org-back-to-heading t)
  12827. (let ((current
  12828. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  12829. (line-end-position) t)
  12830. (let ((tags (match-string 1)))
  12831. ;; Clear current tags.
  12832. (replace-match "")
  12833. ;; Reverse the tags list so any new tag is appended to
  12834. ;; the current list of tags.
  12835. (nreverse (org-split-string tags ":")))))
  12836. res)
  12837. (pcase onoff
  12838. (`off (setq current (delete tag current)))
  12839. ((or `on (guard (not (member tag current))))
  12840. (setq res t)
  12841. (cl-pushnew tag current :test #'equal))
  12842. (_ (setq current (delete tag current))))
  12843. (end-of-line)
  12844. (if current
  12845. (progn
  12846. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  12847. (org-set-tags nil t))
  12848. (delete-horizontal-space))
  12849. (run-hooks 'org-after-tags-change-hook)
  12850. res)))
  12851. (defun org--align-tags-here (to-col)
  12852. "Align tags on the current headline to TO-COL.
  12853. Assume point is on a headline."
  12854. (let ((pos (point)))
  12855. (beginning-of-line)
  12856. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  12857. (>= pos (match-beginning 2)))
  12858. ;; No tags or point within tags: do not align.
  12859. (goto-char pos)
  12860. (goto-char (match-beginning 1))
  12861. (let ((shift (max (- (if (>= to-col 0) to-col
  12862. (- (abs to-col) (string-width (match-string 2))))
  12863. (current-column))
  12864. 1)))
  12865. (replace-match (make-string shift ?\s) nil nil nil 1)
  12866. ;; Preserve initial position, if possible. In any case, stop
  12867. ;; before tags.
  12868. (when (< pos (point)) (goto-char pos))))))
  12869. (defun org-set-tags-command (&optional arg just-align)
  12870. "Call the set-tags command for the current entry."
  12871. (interactive "P")
  12872. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  12873. (org-set-tags arg just-align)
  12874. (save-excursion
  12875. (unless (and (org-region-active-p)
  12876. org-loop-over-headlines-in-active-region)
  12877. (org-back-to-heading t))
  12878. (org-set-tags arg just-align))))
  12879. (defun org-set-tags-to (data)
  12880. "Set the tags of the current entry to DATA, replacing the current tags.
  12881. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  12882. If DATA is nil or the empty string, any tags will be removed."
  12883. (interactive "sTags: ")
  12884. (setq data
  12885. (cond
  12886. ((eq data nil) "")
  12887. ((equal data "") "")
  12888. ((stringp data)
  12889. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  12890. ":"))
  12891. ((listp data)
  12892. (concat ":" (mapconcat 'identity data ":") ":"))))
  12893. (when data
  12894. (save-excursion
  12895. (org-back-to-heading t)
  12896. (when (let ((case-fold-search nil))
  12897. (looking-at org-complex-heading-regexp))
  12898. (if (match-end 5)
  12899. (progn
  12900. (goto-char (match-beginning 5))
  12901. (insert data)
  12902. (delete-region (point) (point-at-eol))
  12903. (org-set-tags nil 'align))
  12904. (goto-char (point-at-eol))
  12905. (insert " " data)
  12906. (org-set-tags nil 'align)))
  12907. (beginning-of-line 1)
  12908. (when (looking-at ".*?\\([ \t]+\\)$")
  12909. (delete-region (match-beginning 1) (match-end 1))))))
  12910. (defun org-align-all-tags ()
  12911. "Align the tags in all headings."
  12912. (interactive)
  12913. (save-excursion
  12914. (or (ignore-errors (org-back-to-heading t))
  12915. (outline-next-heading))
  12916. (if (org-at-heading-p)
  12917. (org-set-tags t)
  12918. (message "No headings"))))
  12919. (defvar org-indent-indentation-per-level)
  12920. (defun org-set-tags (&optional arg just-align)
  12921. "Set the tags for the current headline.
  12922. With prefix ARG, realign all tags in headings in the current buffer.
  12923. When JUST-ALIGN is non-nil, only align tags."
  12924. (interactive "P")
  12925. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12926. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12927. 'region-start-level
  12928. 'region))
  12929. org-loop-over-headlines-in-active-region)
  12930. (org-map-entries
  12931. ;; We don't use ARG and JUST-ALIGN here because these args
  12932. ;; are not useful when looping over headlines.
  12933. #'org-set-tags
  12934. org-loop-over-headlines-in-active-region
  12935. cl
  12936. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  12937. (let ((org-setting-tags t))
  12938. (if arg
  12939. (save-excursion
  12940. (goto-char (point-min))
  12941. (while (re-search-forward org-outline-regexp-bol nil t)
  12942. (org-set-tags nil t)
  12943. (end-of-line))
  12944. (message "All tags realigned to column %d" org-tags-column))
  12945. (let* ((current (org-get-tags-string))
  12946. (tags
  12947. (if just-align current
  12948. ;; Get a new set of tags from the user.
  12949. (save-excursion
  12950. (let* ((seen)
  12951. (table
  12952. (setq
  12953. org-last-tags-completion-table
  12954. ;; Uniquify tags in alists, yet preserve
  12955. ;; structure (i.e., keywords).
  12956. (delq nil
  12957. (mapcar
  12958. (lambda (pair)
  12959. (let ((head (car pair)))
  12960. (cond ((symbolp head) pair)
  12961. ((member head seen) nil)
  12962. (t (push head seen)
  12963. pair))))
  12964. (append
  12965. (or org-current-tag-alist
  12966. (org-get-buffer-tags))
  12967. (and
  12968. org-complete-tags-always-offer-all-agenda-tags
  12969. (org-global-tags-completion-table
  12970. (org-agenda-files))))))))
  12971. (current-tags (org-split-string current ":"))
  12972. (inherited-tags
  12973. (nreverse (nthcdr (length current-tags)
  12974. (nreverse (org-get-tags-at))))))
  12975. (replace-regexp-in-string
  12976. "\\([-+&]+\\|,\\)"
  12977. ":"
  12978. (if (or (eq t org-use-fast-tag-selection)
  12979. (and org-use-fast-tag-selection
  12980. (delq nil (mapcar #'cdr table))))
  12981. (org-fast-tag-selection
  12982. current-tags inherited-tags table
  12983. (and org-fast-tag-selection-include-todo
  12984. org-todo-key-alist))
  12985. (let ((org-add-colon-after-tag-completion
  12986. (< 1 (length table))))
  12987. (org-trim
  12988. (completing-read
  12989. "Tags: "
  12990. #'org-tags-completion-function
  12991. nil nil current 'org-tags-history))))))))))
  12992. (when org-tags-sort-function
  12993. (setq tags
  12994. (mapconcat
  12995. #'identity
  12996. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  12997. org-tags-sort-function)
  12998. ":")))
  12999. (if (or (string= ":" tags)
  13000. (string= "::" tags))
  13001. (setq tags ""))
  13002. (if (not (org-string-nw-p tags)) (setq tags "")
  13003. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13004. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13005. ;; Insert new tags at the correct column.
  13006. (unless (equal current tags)
  13007. (save-excursion
  13008. (beginning-of-line)
  13009. (let ((case-fold-search nil))
  13010. (looking-at org-complex-heading-regexp))
  13011. ;; Remove current tags, if any.
  13012. (when (match-end 5) (replace-match "" nil nil nil 5))
  13013. ;; Insert new tags, if any. Otherwise, remove trailing
  13014. ;; white spaces.
  13015. (end-of-line)
  13016. (if (not (equal tags ""))
  13017. ;; When text is being inserted on an invisible
  13018. ;; region boundary, it can be inadvertently sucked
  13019. ;; into invisibility.
  13020. (org-flag-region (point) (progn (insert " " tags) (point))
  13021. nil
  13022. 'outline)
  13023. (skip-chars-backward " \t")
  13024. (delete-region (point) (line-end-position)))))
  13025. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13026. ;; is on.
  13027. (unless (equal tags "")
  13028. (let* ((level (save-excursion
  13029. (beginning-of-line)
  13030. (skip-chars-forward "\\*")))
  13031. (offset (if (bound-and-true-p org-indent-mode)
  13032. (* (1- org-indent-indentation-per-level)
  13033. (1- level))
  13034. 0))
  13035. (tags-column
  13036. (+ org-tags-column
  13037. (if (> org-tags-column 0) (- offset) offset))))
  13038. (org--align-tags-here tags-column))))
  13039. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13040. (defun org-change-tag-in-region (beg end tag off)
  13041. "Add or remove TAG for each entry in the region.
  13042. This works in the agenda, and also in an Org buffer."
  13043. (interactive
  13044. (list (region-beginning) (region-end)
  13045. (let ((org-last-tags-completion-table
  13046. (if (derived-mode-p 'org-mode)
  13047. (org-uniquify
  13048. (delq nil (append (org-get-buffer-tags)
  13049. (org-global-tags-completion-table))))
  13050. (org-global-tags-completion-table))))
  13051. (completing-read
  13052. "Tag: " 'org-tags-completion-function nil nil nil
  13053. 'org-tags-history))
  13054. (progn
  13055. (message "[s]et or [r]emove? ")
  13056. (equal (read-char-exclusive) ?r))))
  13057. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13058. (let ((agendap (equal major-mode 'org-agenda-mode))
  13059. l1 l2 m buf pos newhead (cnt 0))
  13060. (goto-char end)
  13061. (setq l2 (1- (org-current-line)))
  13062. (goto-char beg)
  13063. (setq l1 (org-current-line))
  13064. (cl-loop for l from l1 to l2 do
  13065. (org-goto-line l)
  13066. (setq m (get-text-property (point) 'org-hd-marker))
  13067. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13068. (and agendap m))
  13069. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13070. pos (if agendap m (point)))
  13071. (with-current-buffer buf
  13072. (save-excursion
  13073. (save-restriction
  13074. (goto-char pos)
  13075. (setq cnt (1+ cnt))
  13076. (org-toggle-tag tag (if off 'off 'on))
  13077. (setq newhead (org-get-heading)))))
  13078. (and agendap (org-agenda-change-all-lines newhead m))))
  13079. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13080. (defun org-tags-completion-function (string _predicate &optional flag)
  13081. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13082. (confirm (lambda (x) (stringp (car x)))))
  13083. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13084. (setq s1 (match-string 1 string)
  13085. s2 (match-string 2 string))
  13086. (setq s1 "" s2 string))
  13087. (cond
  13088. ((eq flag nil)
  13089. ;; try completion
  13090. (setq rtn (try-completion s2 ctable confirm))
  13091. (when (stringp rtn)
  13092. (setq rtn
  13093. (concat s1 s2 (substring rtn (length s2))
  13094. (if (and org-add-colon-after-tag-completion
  13095. (assoc rtn ctable))
  13096. ":" ""))))
  13097. rtn)
  13098. ((eq flag t)
  13099. ;; all-completions
  13100. (all-completions s2 ctable confirm))
  13101. ((eq flag 'lambda)
  13102. ;; exact match?
  13103. (assoc s2 ctable)))))
  13104. (defun org-fast-tag-insert (kwd tags face &optional end)
  13105. "Insert KDW, and the TAGS, the latter with face FACE.
  13106. Also insert END."
  13107. (insert (format "%-12s" (concat kwd ":"))
  13108. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13109. (or end "")))
  13110. (defun org-fast-tag-show-exit (flag)
  13111. (save-excursion
  13112. (org-goto-line 3)
  13113. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13114. (replace-match ""))
  13115. (when flag
  13116. (end-of-line 1)
  13117. (org-move-to-column (- (window-width) 19) t)
  13118. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13119. (defun org-set-current-tags-overlay (current prefix)
  13120. "Add an overlay to CURRENT tag with PREFIX."
  13121. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13122. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13123. (org-overlay-display org-tags-overlay (concat prefix s))))
  13124. (defvar org-last-tag-selection-key nil)
  13125. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13126. "Fast tag selection with single keys.
  13127. CURRENT is the current list of tags in the headline, INHERITED is the
  13128. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13129. possibly with grouping information. TODO-TABLE is a similar table with
  13130. TODO keywords, should these have keys assigned to them.
  13131. If the keys are nil, a-z are automatically assigned.
  13132. Returns the new tags string, or nil to not change the current settings."
  13133. (let* ((fulltable (append table todo-table))
  13134. (maxlen (apply 'max (mapcar
  13135. (lambda (x)
  13136. (if (stringp (car x)) (string-width (car x)) 0))
  13137. fulltable)))
  13138. (buf (current-buffer))
  13139. (expert (eq org-fast-tag-selection-single-key 'expert))
  13140. (buffer-tags nil)
  13141. (fwidth (+ maxlen 3 1 3))
  13142. (ncol (/ (- (window-width) 4) fwidth))
  13143. (i-face 'org-done)
  13144. (c-face 'org-todo)
  13145. tg cnt e c char c1 c2 ntable tbl rtn
  13146. ov-start ov-end ov-prefix
  13147. (exit-after-next org-fast-tag-selection-single-key)
  13148. (done-keywords org-done-keywords)
  13149. groups ingroup intaggroup)
  13150. (save-excursion
  13151. (beginning-of-line 1)
  13152. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13153. (setq ov-start (match-beginning 1)
  13154. ov-end (match-end 1)
  13155. ov-prefix "")
  13156. (setq ov-start (1- (point-at-eol))
  13157. ov-end (1+ ov-start))
  13158. (skip-chars-forward "^\n\r")
  13159. (setq ov-prefix
  13160. (concat
  13161. (buffer-substring (1- (point)) (point))
  13162. (if (> (current-column) org-tags-column)
  13163. " "
  13164. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13165. (move-overlay org-tags-overlay ov-start ov-end)
  13166. (save-window-excursion
  13167. (if expert
  13168. (set-buffer (get-buffer-create " *Org tags*"))
  13169. (delete-other-windows)
  13170. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13171. (org-switch-to-buffer-other-window " *Org tags*"))
  13172. (erase-buffer)
  13173. (setq-local org-done-keywords done-keywords)
  13174. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13175. (org-fast-tag-insert "Current" current c-face "\n\n")
  13176. (org-fast-tag-show-exit exit-after-next)
  13177. (org-set-current-tags-overlay current ov-prefix)
  13178. (setq tbl fulltable char ?a cnt 0)
  13179. (while (setq e (pop tbl))
  13180. (cond
  13181. ((eq (car e) :startgroup)
  13182. (push '() groups) (setq ingroup t)
  13183. (unless (zerop cnt)
  13184. (setq cnt 0)
  13185. (insert "\n"))
  13186. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13187. ((eq (car e) :endgroup)
  13188. (setq ingroup nil cnt 0)
  13189. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13190. ((eq (car e) :startgrouptag)
  13191. (setq intaggroup t)
  13192. (unless (zerop cnt)
  13193. (setq cnt 0)
  13194. (insert "\n"))
  13195. (insert "[ "))
  13196. ((eq (car e) :endgrouptag)
  13197. (setq intaggroup nil cnt 0)
  13198. (insert "]\n"))
  13199. ((equal e '(:newline))
  13200. (unless (zerop cnt)
  13201. (setq cnt 0)
  13202. (insert "\n")
  13203. (setq e (car tbl))
  13204. (while (equal (car tbl) '(:newline))
  13205. (insert "\n")
  13206. (setq tbl (cdr tbl)))))
  13207. ((equal e '(:grouptags)) (insert " : "))
  13208. (t
  13209. (setq tg (copy-sequence (car e)) c2 nil)
  13210. (if (cdr e)
  13211. (setq c (cdr e))
  13212. ;; automatically assign a character.
  13213. (setq c1 (string-to-char
  13214. (downcase (substring
  13215. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13216. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13217. (while (or (rassoc char ntable) (rassoc char table))
  13218. (setq char (1+ char)))
  13219. (setq c2 c1))
  13220. (setq c (or c2 char)))
  13221. (when ingroup (push tg (car groups)))
  13222. (setq tg (org-add-props tg nil 'face
  13223. (cond
  13224. ((not (assoc tg table))
  13225. (org-get-todo-face tg))
  13226. ((member tg current) c-face)
  13227. ((member tg inherited) i-face))))
  13228. (when (equal (caar tbl) :grouptags)
  13229. (org-add-props tg nil 'face 'org-tag-group))
  13230. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13231. (insert "[" c "] " tg (make-string
  13232. (- fwidth 4 (length tg)) ?\ ))
  13233. (push (cons tg c) ntable)
  13234. (when (= (cl-incf cnt) ncol)
  13235. (insert "\n")
  13236. (when (or ingroup intaggroup) (insert " "))
  13237. (setq cnt 0)))))
  13238. (setq ntable (nreverse ntable))
  13239. (insert "\n")
  13240. (goto-char (point-min))
  13241. (unless expert (org-fit-window-to-buffer))
  13242. (setq rtn
  13243. (catch 'exit
  13244. (while t
  13245. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13246. (if (not groups) "no " "")
  13247. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13248. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13249. (setq org-last-tag-selection-key c)
  13250. (cond
  13251. ((= c ?\r) (throw 'exit t))
  13252. ((= c ?!)
  13253. (setq groups (not groups))
  13254. (goto-char (point-min))
  13255. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13256. ((= c ?\C-c)
  13257. (if (not expert)
  13258. (org-fast-tag-show-exit
  13259. (setq exit-after-next (not exit-after-next)))
  13260. (setq expert nil)
  13261. (delete-other-windows)
  13262. (set-window-buffer (split-window-vertically) " *Org tags*")
  13263. (org-switch-to-buffer-other-window " *Org tags*")
  13264. (org-fit-window-to-buffer)))
  13265. ((or (= c ?\C-g)
  13266. (and (= c ?q) (not (rassoc c ntable))))
  13267. (delete-overlay org-tags-overlay)
  13268. (setq quit-flag t))
  13269. ((= c ?\ )
  13270. (setq current nil)
  13271. (when exit-after-next (setq exit-after-next 'now)))
  13272. ((= c ?\t)
  13273. (condition-case nil
  13274. (setq tg (completing-read
  13275. "Tag: "
  13276. (or buffer-tags
  13277. (with-current-buffer buf
  13278. (setq buffer-tags
  13279. (org-get-buffer-tags))))))
  13280. (quit (setq tg "")))
  13281. (when (string-match "\\S-" tg)
  13282. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13283. (if (member tg current)
  13284. (setq current (delete tg current))
  13285. (push tg current)))
  13286. (when exit-after-next (setq exit-after-next 'now)))
  13287. ((setq e (rassoc c todo-table) tg (car e))
  13288. (with-current-buffer buf
  13289. (save-excursion (org-todo tg)))
  13290. (when exit-after-next (setq exit-after-next 'now)))
  13291. ((setq e (rassoc c ntable) tg (car e))
  13292. (if (member tg current)
  13293. (setq current (delete tg current))
  13294. (cl-loop for g in groups do
  13295. (when (member tg g)
  13296. (dolist (x g) (setq current (delete x current)))))
  13297. (push tg current))
  13298. (when exit-after-next (setq exit-after-next 'now))))
  13299. ;; Create a sorted list
  13300. (setq current
  13301. (sort current
  13302. (lambda (a b)
  13303. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13304. (when (eq exit-after-next 'now) (throw 'exit t))
  13305. (goto-char (point-min))
  13306. (beginning-of-line 2)
  13307. (delete-region (point) (point-at-eol))
  13308. (org-fast-tag-insert "Current" current c-face)
  13309. (org-set-current-tags-overlay current ov-prefix)
  13310. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13311. (setq tg (match-string 1))
  13312. (add-text-properties
  13313. (match-beginning 1) (match-end 1)
  13314. (list 'face
  13315. (cond
  13316. ((member tg current) c-face)
  13317. ((member tg inherited) i-face)
  13318. (t (get-text-property (match-beginning 1) 'face))))))
  13319. (goto-char (point-min)))))
  13320. (delete-overlay org-tags-overlay)
  13321. (if rtn
  13322. (mapconcat 'identity current ":")
  13323. nil))))
  13324. (defun org-get-tags-string ()
  13325. "Get the TAGS string in the current headline."
  13326. (unless (org-at-heading-p t)
  13327. (user-error "Not on a heading"))
  13328. (save-excursion
  13329. (beginning-of-line 1)
  13330. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13331. (match-string-no-properties 1)
  13332. "")))
  13333. (defun org-get-tags ()
  13334. "Get the list of tags specified in the current headline."
  13335. (org-split-string (org-get-tags-string) ":"))
  13336. (defun org-get-buffer-tags ()
  13337. "Get a table of all tags used in the buffer, for completion."
  13338. (org-with-wide-buffer
  13339. (goto-char (point-min))
  13340. (let ((tag-re (concat org-outline-regexp-bol
  13341. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13342. tags)
  13343. (while (re-search-forward tag-re nil t)
  13344. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13345. (push tag tags)))
  13346. (mapcar #'list (append org-file-tags (org-uniquify 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-at'. 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 ((value (org-string-nw-p (org-get-tags-string))))
  13657. (when value (push (cons "TAGS" value) props)))
  13658. (when specific (throw 'exit props)))
  13659. (when (or (not specific) (string= specific "ALLTAGS"))
  13660. (let ((value (org-get-tags-at)))
  13661. (when value
  13662. (push (cons "ALLTAGS"
  13663. (format ":%s:" (mapconcat #'identity value ":")))
  13664. props)))
  13665. (when specific (throw 'exit props)))
  13666. (when (or (not specific) (string= specific "BLOCKED"))
  13667. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13668. (when specific (throw 'exit props)))
  13669. (when (or (not specific)
  13670. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13671. (forward-line)
  13672. (when (looking-at-p org-planning-line-re)
  13673. (end-of-line)
  13674. (let ((bol (line-beginning-position))
  13675. ;; Backward compatibility: time keywords used to
  13676. ;; be configurable (before 8.3). Make sure we
  13677. ;; get the correct keyword.
  13678. (key-assoc `(("CLOSED" . ,org-closed-string)
  13679. ("DEADLINE" . ,org-deadline-string)
  13680. ("SCHEDULED" . ,org-scheduled-string))))
  13681. (dolist (pair (if specific (list (assoc specific key-assoc))
  13682. key-assoc))
  13683. (save-excursion
  13684. (when (search-backward (cdr pair) bol t)
  13685. (goto-char (match-end 0))
  13686. (skip-chars-forward " \t")
  13687. (and (looking-at org-ts-regexp-both)
  13688. (push (cons (car pair)
  13689. (match-string-no-properties 0))
  13690. props)))))))
  13691. (when specific (throw 'exit props)))
  13692. (when (or (not specific)
  13693. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13694. (let ((find-ts
  13695. (lambda (end ts)
  13696. ;; Fix next time-stamp before END. TS is the
  13697. ;; list of time-stamps found so far.
  13698. (let ((ts ts)
  13699. (regexp (cond
  13700. ((string= specific "TIMESTAMP")
  13701. org-ts-regexp)
  13702. ((string= specific "TIMESTAMP_IA")
  13703. org-ts-regexp-inactive)
  13704. ((assoc "TIMESTAMP_IA" ts)
  13705. org-ts-regexp)
  13706. ((assoc "TIMESTAMP" ts)
  13707. org-ts-regexp-inactive)
  13708. (t org-ts-regexp-both))))
  13709. (catch 'next
  13710. (while (re-search-forward regexp end t)
  13711. (backward-char)
  13712. (let ((object (org-element-context)))
  13713. ;; Accept to match timestamps in node
  13714. ;; properties, too.
  13715. (when (memq (org-element-type object)
  13716. '(node-property timestamp))
  13717. (let ((type
  13718. (org-element-property :type object)))
  13719. (cond
  13720. ((and (memq type '(active active-range))
  13721. (not (equal specific "TIMESTAMP_IA")))
  13722. (unless (assoc "TIMESTAMP" ts)
  13723. (push (cons "TIMESTAMP"
  13724. (org-element-property
  13725. :raw-value object))
  13726. ts)
  13727. (when specific (throw 'exit ts))))
  13728. ((and (memq type '(inactive inactive-range))
  13729. (not (string= specific "TIMESTAMP")))
  13730. (unless (assoc "TIMESTAMP_IA" ts)
  13731. (push (cons "TIMESTAMP_IA"
  13732. (org-element-property
  13733. :raw-value object))
  13734. ts)
  13735. (when specific (throw 'exit ts))))))
  13736. ;; Both timestamp types are found,
  13737. ;; move to next part.
  13738. (when (= (length ts) 2) (throw 'next ts)))))
  13739. ts)))))
  13740. (goto-char beg)
  13741. ;; First look for timestamps within headline.
  13742. (let ((ts (funcall find-ts (line-end-position) nil)))
  13743. (if (= (length ts) 2) (setq props (nconc ts props))
  13744. ;; Then find timestamps in the section, skipping
  13745. ;; planning line.
  13746. (let ((end (save-excursion (outline-next-heading))))
  13747. (forward-line)
  13748. (when (looking-at-p org-planning-line-re) (forward-line))
  13749. (setq props (nconc (funcall find-ts end ts) props))))))))
  13750. ;; Get the standard properties, like :PROP:.
  13751. (when (memq which '(nil all standard))
  13752. ;; If we are looking after a specific property, delegate
  13753. ;; to `org-entry-get', which is faster. However, make an
  13754. ;; exception for "CATEGORY", since it can be also set
  13755. ;; through keywords (i.e. #+CATEGORY).
  13756. (if (and specific (not (equal specific "CATEGORY")))
  13757. (let ((value (org-entry-get beg specific nil t)))
  13758. (throw 'exit (and value (list (cons specific value)))))
  13759. (let ((range (org-get-property-block beg)))
  13760. (when range
  13761. (let ((end (cdr range)) seen-base)
  13762. (goto-char (car range))
  13763. ;; Unlike to `org--update-property-plist', we
  13764. ;; handle the case where base values is found
  13765. ;; after its extension. We also forbid standard
  13766. ;; properties to be named as special properties.
  13767. (while (re-search-forward org-property-re end t)
  13768. (let* ((key (upcase (match-string-no-properties 2)))
  13769. (extendp (string-match-p "\\+\\'" key))
  13770. (key-base (if extendp (substring key 0 -1) key))
  13771. (value (match-string-no-properties 3)))
  13772. (cond
  13773. ((member-ignore-case key-base org-special-properties))
  13774. (extendp
  13775. (setq props
  13776. (org--update-property-plist key value props)))
  13777. ((member key seen-base))
  13778. (t (push key seen-base)
  13779. (let ((p (assoc-string key props t)))
  13780. (if p (setcdr p (concat value " " (cdr p)))
  13781. (push (cons key value) props))))))))))))
  13782. (unless (assoc "CATEGORY" props)
  13783. (push (cons "CATEGORY" (org-get-category beg)) props)
  13784. (when (string= specific "CATEGORY") (throw 'exit props)))
  13785. ;; Return value.
  13786. props)))))
  13787. (defun org--property-local-values (property literal-nil)
  13788. "Return value for PROPERTY in current entry.
  13789. Value is a list whose car is the base value for PROPERTY and cdr
  13790. a list of accumulated values. Return nil if neither is found in
  13791. the entry. Also return nil when PROPERTY is set to \"nil\",
  13792. unless LITERAL-NIL is non-nil."
  13793. (let ((range (org-get-property-block)))
  13794. (when range
  13795. (goto-char (car range))
  13796. (let* ((case-fold-search t)
  13797. (end (cdr range))
  13798. (value
  13799. ;; Base value.
  13800. (save-excursion
  13801. (let ((v (and (re-search-forward
  13802. (org-re-property property nil t) end t)
  13803. (match-string-no-properties 3))))
  13804. (list (if literal-nil v (org-not-nil v)))))))
  13805. ;; Find additional values.
  13806. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13807. (while (re-search-forward property+ end t)
  13808. (push (match-string-no-properties 3) value)))
  13809. ;; Return final values.
  13810. (and (not (equal value '(nil))) (nreverse value))))))
  13811. (defun org--property-global-value (property literal-nil)
  13812. "Return value for PROPERTY in current buffer.
  13813. Return value is a string. Return nil if property is not set
  13814. globally. Also return nil when PROPERTY is set to \"nil\",
  13815. unless LITERAL-NIL is non-nil."
  13816. (let ((global
  13817. (cdr (or (assoc-string property org-file-properties t)
  13818. (assoc-string property org-global-properties t)
  13819. (assoc-string property org-global-properties-fixed t)))))
  13820. (if literal-nil global (org-not-nil global))))
  13821. (defun org-entry-get (pom property &optional inherit literal-nil)
  13822. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13823. If INHERIT is non-nil and the entry does not have the property,
  13824. then also check higher levels of the hierarchy. If INHERIT is
  13825. the symbol `selective', use inheritance only if the setting in
  13826. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13827. If the property is present but empty, the return value is the
  13828. empty string. If the property is not present at all, nil is
  13829. returned. In any other case, return the value as a string.
  13830. Search is case-insensitive.
  13831. If LITERAL-NIL is set, return the string value \"nil\" as
  13832. a string, do not interpret it as the list atom nil. This is used
  13833. for inheritance when a \"nil\" value can supersede a non-nil
  13834. value higher up the hierarchy."
  13835. (org-with-point-at pom
  13836. (cond
  13837. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13838. ;; We need a special property. Use `org-entry-properties' to
  13839. ;; retrieve it, but specify the wanted property.
  13840. (cdr (assoc-string property (org-entry-properties nil property))))
  13841. ((and inherit
  13842. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13843. (org-entry-get-with-inheritance property literal-nil))
  13844. (t
  13845. (let* ((local (org--property-local-values property literal-nil))
  13846. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13847. (if literal-nil value (org-not-nil value)))))))
  13848. (defun org-property-or-variable-value (var &optional inherit)
  13849. "Check if there is a property fixing the value of VAR.
  13850. If yes, return this value. If not, return the current value of the variable."
  13851. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13852. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13853. (read prop)
  13854. (symbol-value var))))
  13855. (defun org-entry-delete (pom property)
  13856. "Delete PROPERTY from entry at point-or-marker POM.
  13857. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13858. non-nil when a property was removed."
  13859. (org-with-point-at pom
  13860. (pcase (org-get-property-block)
  13861. (`(,begin . ,origin)
  13862. (let* ((end (copy-marker origin))
  13863. (re (org-re-property
  13864. (concat (regexp-quote property) "\\+?") t t)))
  13865. (goto-char begin)
  13866. (while (re-search-forward re end t)
  13867. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13868. ;; If drawer is empty, remove it altogether.
  13869. (when (= begin end)
  13870. (delete-region (line-beginning-position 0)
  13871. (line-beginning-position 2)))
  13872. ;; Return non-nil if some property was removed.
  13873. (prog1 (/= end origin) (set-marker end nil))))
  13874. (_ nil))))
  13875. ;; Multi-values properties are properties that contain multiple values
  13876. ;; These values are assumed to be single words, separated by whitespace.
  13877. (defun org-entry-add-to-multivalued-property (pom property value)
  13878. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13879. (let* ((old (org-entry-get pom property))
  13880. (values (and old (split-string old))))
  13881. (setq value (org-entry-protect-space value))
  13882. (unless (member value values)
  13883. (setq values (append values (list value)))
  13884. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13885. (defun org-entry-remove-from-multivalued-property (pom property value)
  13886. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13887. (let* ((old (org-entry-get pom property))
  13888. (values (and old (split-string old))))
  13889. (setq value (org-entry-protect-space value))
  13890. (when (member value values)
  13891. (setq values (delete value values))
  13892. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13893. (defun org-entry-member-in-multivalued-property (pom property value)
  13894. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13895. (let* ((old (org-entry-get pom property))
  13896. (values (and old (split-string old))))
  13897. (setq value (org-entry-protect-space value))
  13898. (member value values)))
  13899. (defun org-entry-get-multivalued-property (pom property)
  13900. "Return a list of values in a multivalued property."
  13901. (let* ((value (org-entry-get pom property))
  13902. (values (and value (split-string value))))
  13903. (mapcar #'org-entry-restore-space values)))
  13904. (defun org-entry-put-multivalued-property (pom property &rest values)
  13905. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13906. VALUES should be a list of strings. Spaces will be protected."
  13907. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13908. (let* ((value (org-entry-get pom property))
  13909. (values (and value (split-string value))))
  13910. (mapcar #'org-entry-restore-space values)))
  13911. (defun org-entry-protect-space (s)
  13912. "Protect spaces and newline in string S."
  13913. (while (string-match " " s)
  13914. (setq s (replace-match "%20" t t s)))
  13915. (while (string-match "\n" s)
  13916. (setq s (replace-match "%0A" t t s)))
  13917. s)
  13918. (defun org-entry-restore-space (s)
  13919. "Restore spaces and newline in string S."
  13920. (while (string-match "%20" s)
  13921. (setq s (replace-match " " t t s)))
  13922. (while (string-match "%0A" s)
  13923. (setq s (replace-match "\n" t t s)))
  13924. s)
  13925. (defvar org-entry-property-inherited-from (make-marker)
  13926. "Marker pointing to the entry from where a property was inherited.
  13927. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13928. location of the entry where the inheritance search matched. If there was
  13929. no match, the marker will point nowhere.
  13930. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13931. is set.")
  13932. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13933. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13934. The search will stop at the first ancestor which has the property defined.
  13935. If the value found is \"nil\", return nil to show that the property
  13936. should be considered as undefined (this is the meaning of nil here).
  13937. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13938. (move-marker org-entry-property-inherited-from nil)
  13939. (org-with-wide-buffer
  13940. (let (value)
  13941. (catch 'exit
  13942. (while t
  13943. (let ((v (org--property-local-values property literal-nil)))
  13944. (when v
  13945. (setq value
  13946. (concat (mapconcat #'identity (delq nil v) " ")
  13947. (and value " ")
  13948. value)))
  13949. (cond
  13950. ((car v)
  13951. (org-back-to-heading t)
  13952. (move-marker org-entry-property-inherited-from (point))
  13953. (throw 'exit nil))
  13954. ((org-up-heading-safe))
  13955. (t
  13956. (let ((global (org--property-global-value property literal-nil)))
  13957. (cond ((not global))
  13958. (value (setq value (concat global " " value)))
  13959. (t (setq value global))))
  13960. (throw 'exit nil))))))
  13961. (if literal-nil value (org-not-nil value)))))
  13962. (defvar org-property-changed-functions nil
  13963. "Hook called when the value of a property has changed.
  13964. Each hook function should accept two arguments, the name of the property
  13965. and the new value.")
  13966. (defun org-entry-put (pom property value)
  13967. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13968. If the value is nil, it is converted to the empty string. If it
  13969. is not a string, an error is raised. Also raise an error on
  13970. invalid property names.
  13971. PROPERTY can be any regular property (see
  13972. `org-special-properties'). It can also be \"TODO\",
  13973. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13974. For the last two properties, VALUE may have any of the special
  13975. values \"earlier\" and \"later\". The function then increases or
  13976. decreases scheduled or deadline date by one day."
  13977. (cond ((null value) (setq value ""))
  13978. ((not (stringp value)) (error "Properties values should be strings"))
  13979. ((not (org--valid-property-p property))
  13980. (user-error "Invalid property name: \"%s\"" property)))
  13981. (org-with-point-at pom
  13982. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13983. (org-back-to-heading t)
  13984. (org-with-limited-levels (org-back-to-heading t)))
  13985. (let ((beg (point)))
  13986. (cond
  13987. ((equal property "TODO")
  13988. (cond ((not (org-string-nw-p value)) (setq value 'none))
  13989. ((not (member value org-todo-keywords-1))
  13990. (user-error "\"%s\" is not a valid TODO state" value)))
  13991. (org-todo value)
  13992. (org-set-tags nil 'align))
  13993. ((equal property "PRIORITY")
  13994. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  13995. (org-set-tags nil 'align))
  13996. ((equal property "SCHEDULED")
  13997. (forward-line)
  13998. (if (and (looking-at-p org-planning-line-re)
  13999. (re-search-forward
  14000. org-scheduled-time-regexp (line-end-position) t))
  14001. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14002. ((string= value "later") (org-timestamp-change 1 'day))
  14003. ((string= value "") (org-schedule '(4)))
  14004. (t (org-schedule nil value)))
  14005. (if (member value '("earlier" "later" ""))
  14006. (call-interactively #'org-schedule)
  14007. (org-schedule nil value))))
  14008. ((equal property "DEADLINE")
  14009. (forward-line)
  14010. (if (and (looking-at-p org-planning-line-re)
  14011. (re-search-forward
  14012. org-deadline-time-regexp (line-end-position) t))
  14013. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14014. ((string= value "later") (org-timestamp-change 1 'day))
  14015. ((string= value "") (org-deadline '(4)))
  14016. (t (org-deadline nil value)))
  14017. (if (member value '("earlier" "later" ""))
  14018. (call-interactively #'org-deadline)
  14019. (org-deadline nil value))))
  14020. ((member property org-special-properties)
  14021. (error "The %s property cannot be set with `org-entry-put'" property))
  14022. (t
  14023. (let* ((range (org-get-property-block beg 'force))
  14024. (end (cdr range))
  14025. (case-fold-search t))
  14026. (goto-char (car range))
  14027. (if (re-search-forward (org-re-property property nil t) end t)
  14028. (progn (delete-region (match-beginning 0) (match-end 0))
  14029. (goto-char (match-beginning 0)))
  14030. (goto-char end)
  14031. (insert "\n")
  14032. (backward-char))
  14033. (insert ":" property ":")
  14034. (when value (insert " " value))
  14035. (org-indent-line)))))
  14036. (run-hook-with-args 'org-property-changed-functions property value)))
  14037. (defun org-buffer-property-keys (&optional specials defaults columns)
  14038. "Get all property keys in the current buffer.
  14039. When SPECIALS is non-nil, also list the special properties that
  14040. reflect things like tags and TODO state.
  14041. When DEFAULTS is non-nil, also include properties that has
  14042. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14043. DESCRIPTION, LOCATION, and LOGGING and others.
  14044. When COLUMNS in non-nil, also include property names given in
  14045. COLUMN formats in the current buffer."
  14046. (let ((case-fold-search t)
  14047. (props (append
  14048. (and specials org-special-properties)
  14049. (and defaults (cons org-effort-property org-default-properties))
  14050. nil)))
  14051. (org-with-wide-buffer
  14052. (goto-char (point-min))
  14053. (while (re-search-forward org-property-start-re nil t)
  14054. (catch :skip
  14055. (let ((range (org-get-property-block)))
  14056. (unless range (throw :skip nil))
  14057. (goto-char (car range))
  14058. (let ((begin (car range))
  14059. (end (cdr range)))
  14060. ;; Make sure that found property block is not located
  14061. ;; before current point, as it would generate an infloop.
  14062. ;; It can happen, for example, in the following
  14063. ;; situation:
  14064. ;;
  14065. ;; * Headline
  14066. ;; :PROPERTIES:
  14067. ;; ...
  14068. ;; :END:
  14069. ;; *************** Inlinetask
  14070. ;; #+BEGIN_EXAMPLE
  14071. ;; :PROPERTIES:
  14072. ;; #+END_EXAMPLE
  14073. ;;
  14074. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14075. (while (< (point) end)
  14076. (let ((p (progn (looking-at org-property-re)
  14077. (match-string-no-properties 2))))
  14078. ;; Only add true property name, not extension symbol.
  14079. (push (if (not (string-match-p "\\+\\'" p)) p
  14080. (substring p 0 -1))
  14081. props))
  14082. (forward-line))))
  14083. (outline-next-heading)))
  14084. (when columns
  14085. (goto-char (point-min))
  14086. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14087. (let ((element (org-element-at-point)))
  14088. (when (memq (org-element-type element) '(keyword node-property))
  14089. (let ((value (org-element-property :value element))
  14090. (start 0))
  14091. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14092. \\(?:{[^}]+}\\)?"
  14093. value start)
  14094. (setq start (match-end 0))
  14095. (let ((p (match-string-no-properties 1 value)))
  14096. (unless (member-ignore-case p org-special-properties)
  14097. (push p props))))))))))
  14098. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14099. (defun org-property-values (key)
  14100. "List all non-nil values of property KEY in current buffer."
  14101. (org-with-wide-buffer
  14102. (goto-char (point-min))
  14103. (let ((case-fold-search t)
  14104. (re (org-re-property key))
  14105. values)
  14106. (while (re-search-forward re nil t)
  14107. (push (org-entry-get (point) key) values))
  14108. (delete-dups values))))
  14109. (defun org-insert-property-drawer ()
  14110. "Insert a property drawer into the current entry."
  14111. (org-with-wide-buffer
  14112. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14113. (org-back-to-heading t)
  14114. (org-with-limited-levels (org-back-to-heading t)))
  14115. (forward-line)
  14116. (when (looking-at-p org-planning-line-re) (forward-line))
  14117. (unless (looking-at-p org-property-drawer-re)
  14118. ;; Make sure we start editing a line from current entry, not from
  14119. ;; next one. It prevents extending text properties or overlays
  14120. ;; belonging to the latter.
  14121. (when (bolp) (backward-char))
  14122. (let ((begin (1+ (point)))
  14123. (inhibit-read-only t))
  14124. (insert "\n:PROPERTIES:\n:END:")
  14125. (when (eobp) (insert "\n"))
  14126. (org-indent-region begin (point))))))
  14127. (defun org-insert-drawer (&optional arg drawer)
  14128. "Insert a drawer at point.
  14129. When optional argument ARG is non-nil, insert a property drawer.
  14130. Optional argument DRAWER, when non-nil, is a string representing
  14131. drawer's name. Otherwise, the user is prompted for a name.
  14132. If a region is active, insert the drawer around that region
  14133. instead.
  14134. Point is left between drawer's boundaries."
  14135. (interactive "P")
  14136. (let* ((drawer (if arg "PROPERTIES"
  14137. (or drawer (read-from-minibuffer "Drawer: ")))))
  14138. (cond
  14139. ;; With C-u, fall back on `org-insert-property-drawer'
  14140. (arg (org-insert-property-drawer))
  14141. ;; Check validity of suggested drawer's name.
  14142. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14143. (user-error "Invalid drawer name"))
  14144. ;; With an active region, insert a drawer at point.
  14145. ((not (org-region-active-p))
  14146. (progn
  14147. (unless (bolp) (insert "\n"))
  14148. (insert (format ":%s:\n\n:END:\n" drawer))
  14149. (forward-line -2)))
  14150. ;; Otherwise, insert the drawer at point
  14151. (t
  14152. (let ((rbeg (region-beginning))
  14153. (rend (copy-marker (region-end))))
  14154. (unwind-protect
  14155. (progn
  14156. (goto-char rbeg)
  14157. (beginning-of-line)
  14158. (when (save-excursion
  14159. (re-search-forward org-outline-regexp-bol rend t))
  14160. (user-error "Drawers cannot contain headlines"))
  14161. ;; Position point at the beginning of the first
  14162. ;; non-blank line in region. Insert drawer's opening
  14163. ;; there, then indent it.
  14164. (org-skip-whitespace)
  14165. (beginning-of-line)
  14166. (insert ":" drawer ":\n")
  14167. (forward-line -1)
  14168. (indent-for-tab-command)
  14169. ;; Move point to the beginning of the first blank line
  14170. ;; after the last non-blank line in region. Insert
  14171. ;; drawer's closing, then indent it.
  14172. (goto-char rend)
  14173. (skip-chars-backward " \r\t\n")
  14174. (insert "\n:END:")
  14175. (deactivate-mark t)
  14176. (indent-for-tab-command)
  14177. (unless (eolp) (insert "\n")))
  14178. ;; Clear marker, whatever the outcome of insertion is.
  14179. (set-marker rend nil)))))))
  14180. (defvar org-property-set-functions-alist nil
  14181. "Property set function alist.
  14182. Each entry should have the following format:
  14183. (PROPERTY . READ-FUNCTION)
  14184. The read function will be called with the same argument as
  14185. `org-completing-read'.")
  14186. (defun org-set-property-function (property)
  14187. "Get the function that should be used to set PROPERTY.
  14188. This is computed according to `org-property-set-functions-alist'."
  14189. (or (cdr (assoc property org-property-set-functions-alist))
  14190. 'org-completing-read))
  14191. (defun org-read-property-value (property)
  14192. "Read PROPERTY value from user."
  14193. (let* ((completion-ignore-case t)
  14194. (allowed (org-property-get-allowed-values nil property 'table))
  14195. (cur (org-entry-get nil property))
  14196. (prompt (concat property " value"
  14197. (if (and cur (string-match "\\S-" cur))
  14198. (concat " [" cur "]") "") ": "))
  14199. (set-function (org-set-property-function property))
  14200. (val (if allowed
  14201. (funcall set-function prompt allowed nil
  14202. (not (get-text-property 0 'org-unrestricted
  14203. (caar allowed))))
  14204. (funcall set-function prompt
  14205. (mapcar 'list (org-property-values property))
  14206. nil nil "" nil cur))))
  14207. (org-trim val)))
  14208. (defvar org-last-set-property nil)
  14209. (defvar org-last-set-property-value nil)
  14210. (defun org-read-property-name ()
  14211. "Read a property name."
  14212. (let ((completion-ignore-case t)
  14213. (default-prop (or (and (org-at-property-p)
  14214. (match-string-no-properties 2))
  14215. org-last-set-property)))
  14216. (org-completing-read
  14217. (concat "Property"
  14218. (if default-prop (concat " [" default-prop "]") "")
  14219. ": ")
  14220. (mapcar #'list (org-buffer-property-keys nil t t))
  14221. nil nil nil nil default-prop)))
  14222. (defun org-set-property-and-value (use-last)
  14223. "Allow to set [PROPERTY]: [value] direction from prompt.
  14224. When use-default, don't even ask, just use the last
  14225. \"[PROPERTY]: [value]\" string from the history."
  14226. (interactive "P")
  14227. (let* ((completion-ignore-case t)
  14228. (pv (or (and use-last org-last-set-property-value)
  14229. (org-completing-read
  14230. "Enter a \"[Property]: [value]\" pair: "
  14231. nil nil nil nil nil
  14232. org-last-set-property-value)))
  14233. prop val)
  14234. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14235. (setq prop (match-string 1 pv)
  14236. val (match-string 2 pv))
  14237. (org-set-property prop val))))
  14238. (defun org-set-property (property value)
  14239. "In the current entry, set PROPERTY to VALUE.
  14240. When called interactively, this will prompt for a property name, offering
  14241. completion on existing and default properties. And then it will prompt
  14242. for a value, offering completion either on allowed values (via an inherited
  14243. xxx_ALL property) or on existing values in other instances of this property
  14244. in the current file.
  14245. Throw an error when trying to set a property with an invalid name."
  14246. (interactive (list nil nil))
  14247. (let ((property (or property (org-read-property-name))))
  14248. ;; `org-entry-put' also makes the following check, but this one
  14249. ;; avoids polluting `org-last-set-property' and
  14250. ;; `org-last-set-property-value' needlessly.
  14251. (unless (org--valid-property-p property)
  14252. (user-error "Invalid property name: \"%s\"" property))
  14253. (let ((value (or value (org-read-property-value property)))
  14254. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14255. (setq org-last-set-property property)
  14256. (setq org-last-set-property-value (concat property ": " value))
  14257. ;; Possibly postprocess the inserted value:
  14258. (when fn (setq value (funcall fn value)))
  14259. (unless (equal (org-entry-get nil property) value)
  14260. (org-entry-put nil property value)))))
  14261. (defun org-find-property (property &optional value)
  14262. "Find first entry in buffer that sets PROPERTY.
  14263. When optional argument VALUE is non-nil, only consider an entry
  14264. if it contains PROPERTY set to this value. If PROPERTY should be
  14265. explicitly set to nil, use string \"nil\" for VALUE.
  14266. Return position where the entry begins, or nil if there is no
  14267. such entry. If narrowing is in effect, only search the visible
  14268. part of the buffer."
  14269. (save-excursion
  14270. (goto-char (point-min))
  14271. (let ((case-fold-search t)
  14272. (re (org-re-property property nil (not value) value)))
  14273. (catch 'exit
  14274. (while (re-search-forward re nil t)
  14275. (when (if value (org-at-property-p)
  14276. (org-entry-get (point) property nil t))
  14277. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14278. (defun org-delete-property (property)
  14279. "In the current entry, delete PROPERTY."
  14280. (interactive
  14281. (let* ((completion-ignore-case t)
  14282. (cat (org-entry-get (point) "CATEGORY"))
  14283. (props0 (org-entry-properties nil 'standard))
  14284. (props (if cat props0
  14285. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14286. (prop (if (< 1 (length props))
  14287. (completing-read "Property: " props nil t)
  14288. (caar props))))
  14289. (list prop)))
  14290. (if (not property)
  14291. (message "No property to delete in this entry")
  14292. (org-entry-delete nil property)
  14293. (message "Property \"%s\" deleted" property)))
  14294. (defun org-delete-property-globally (property)
  14295. "Remove PROPERTY globally, from all entries.
  14296. This function ignores narrowing, if any."
  14297. (interactive
  14298. (let* ((completion-ignore-case t)
  14299. (prop (completing-read
  14300. "Globally remove property: "
  14301. (mapcar #'list (org-buffer-property-keys)))))
  14302. (list prop)))
  14303. (org-with-wide-buffer
  14304. (goto-char (point-min))
  14305. (let ((count 0)
  14306. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14307. (while (re-search-forward re nil t)
  14308. (when (org-entry-delete (point) property) (cl-incf count)))
  14309. (message "Property \"%s\" removed from %d entries" property count))))
  14310. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14311. (defun org-compute-property-at-point ()
  14312. "Compute the property at point.
  14313. This looks for an enclosing column format, extracts the operator and
  14314. then applies it to the property in the column format's scope."
  14315. (interactive)
  14316. (unless (org-at-property-p)
  14317. (user-error "Not at a property"))
  14318. (let ((prop (match-string-no-properties 2)))
  14319. (org-columns-get-format-and-top-level)
  14320. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14321. (user-error "No operator defined for property %s" prop))
  14322. (org-columns-compute prop)))
  14323. (defvar org-property-allowed-value-functions nil
  14324. "Hook for functions supplying allowed values for a specific property.
  14325. The functions must take a single argument, the name of the property, and
  14326. return a flat list of allowed values. If \":ETC\" is one of
  14327. the values, this means that these values are intended as defaults for
  14328. completion, but that other values should be allowed too.
  14329. The functions must return nil if they are not responsible for this
  14330. property.")
  14331. (defun org-property-get-allowed-values (pom property &optional table)
  14332. "Get allowed values for the property PROPERTY.
  14333. When TABLE is non-nil, return an alist that can directly be used for
  14334. completion."
  14335. (let (vals)
  14336. (cond
  14337. ((equal property "TODO")
  14338. (setq vals (org-with-point-at pom
  14339. (append org-todo-keywords-1 '("")))))
  14340. ((equal property "PRIORITY")
  14341. (let ((n org-lowest-priority))
  14342. (while (>= n org-highest-priority)
  14343. (push (char-to-string n) vals)
  14344. (setq n (1- n)))))
  14345. ((equal property "CATEGORY"))
  14346. ((member property org-special-properties))
  14347. ((setq vals (run-hook-with-args-until-success
  14348. 'org-property-allowed-value-functions property)))
  14349. (t
  14350. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14351. (when (and vals (string-match "\\S-" vals))
  14352. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14353. (setq vals (mapcar (lambda (x)
  14354. (cond ((stringp x) x)
  14355. ((numberp x) (number-to-string x))
  14356. ((symbolp x) (symbol-name x))
  14357. (t "???")))
  14358. vals)))))
  14359. (when (member ":ETC" vals)
  14360. (setq vals (remove ":ETC" vals))
  14361. (org-add-props (car vals) '(org-unrestricted t)))
  14362. (if table (mapcar 'list vals) vals)))
  14363. (defun org-property-previous-allowed-value (&optional _previous)
  14364. "Switch to the next allowed value for this property."
  14365. (interactive)
  14366. (org-property-next-allowed-value t))
  14367. (defun org-property-next-allowed-value (&optional previous)
  14368. "Switch to the next allowed value for this property."
  14369. (interactive)
  14370. (unless (org-at-property-p)
  14371. (user-error "Not at a property"))
  14372. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14373. (key (match-string 2))
  14374. (value (match-string 3))
  14375. (allowed (or (org-property-get-allowed-values (point) key)
  14376. (and (member value '("[ ]" "[-]" "[X]"))
  14377. '("[ ]" "[X]"))))
  14378. (heading (save-match-data (nth 4 (org-heading-components))))
  14379. nval)
  14380. (unless allowed
  14381. (user-error "Allowed values for this property have not been defined"))
  14382. (when previous (setq allowed (reverse allowed)))
  14383. (when (member value allowed)
  14384. (setq nval (car (cdr (member value allowed)))))
  14385. (setq nval (or nval (car allowed)))
  14386. (when (equal nval value)
  14387. (user-error "Only one allowed value for this property"))
  14388. (org-at-property-p)
  14389. (replace-match (concat " :" key ": " nval) t t)
  14390. (org-indent-line)
  14391. (beginning-of-line 1)
  14392. (skip-chars-forward " \t")
  14393. (when (equal prop org-effort-property)
  14394. (org-refresh-property
  14395. '((effort . identity)
  14396. (effort-minutes . org-duration-to-minutes))
  14397. nval)
  14398. (when (string= org-clock-current-task heading)
  14399. (setq org-clock-effort nval)
  14400. (org-clock-update-mode-line)))
  14401. (run-hook-with-args 'org-property-changed-functions key nval)))
  14402. (defun org-find-olp (path &optional this-buffer)
  14403. "Return a marker pointing to the entry at outline path OLP.
  14404. If anything goes wrong, throw an error.
  14405. You can wrap this call to catch the error like this:
  14406. (condition-case msg
  14407. (org-mobile-locate-entry (match-string 4))
  14408. (error (nth 1 msg)))
  14409. The return value will then be either a string with the error message,
  14410. or a marker if everything is OK.
  14411. If THIS-BUFFER is set, the outline path does not contain a file,
  14412. only headings."
  14413. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14414. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14415. (level 1)
  14416. (lmin 1)
  14417. (lmax 1)
  14418. end found flevel)
  14419. (unless buffer (error "File not found :%s" file))
  14420. (with-current-buffer buffer
  14421. (unless (derived-mode-p 'org-mode)
  14422. (error "Buffer %s needs to be in Org mode" buffer))
  14423. (org-with-wide-buffer
  14424. (goto-char (point-min))
  14425. (dolist (heading path)
  14426. (let ((re (format org-complex-heading-regexp-format
  14427. (regexp-quote heading)))
  14428. (cnt 0))
  14429. (while (re-search-forward re end t)
  14430. (setq level (- (match-end 1) (match-beginning 1)))
  14431. (when (and (>= level lmin) (<= level lmax))
  14432. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14433. (when (= cnt 0)
  14434. (error "Heading not found on level %d: %s" lmax heading))
  14435. (when (> cnt 1)
  14436. (error "Heading not unique on level %d: %s" lmax heading))
  14437. (goto-char found)
  14438. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14439. (setq end (save-excursion (org-end-of-subtree t t)))))
  14440. (when (org-at-heading-p)
  14441. (point-marker))))))
  14442. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14443. "Find node HEADING in BUFFER.
  14444. Return a marker to the heading if it was found, or nil if not.
  14445. If POS-ONLY is set, return just the position instead of a marker.
  14446. The heading text must match exact, but it may have a TODO keyword,
  14447. a priority cookie and tags in the standard locations."
  14448. (with-current-buffer (or buffer (current-buffer))
  14449. (org-with-wide-buffer
  14450. (goto-char (point-min))
  14451. (let (case-fold-search)
  14452. (when (re-search-forward
  14453. (format org-complex-heading-regexp-format
  14454. (regexp-quote heading)) nil t)
  14455. (if pos-only
  14456. (match-beginning 0)
  14457. (move-marker (make-marker) (match-beginning 0))))))))
  14458. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14459. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14460. When the target headline is found, return a marker to this location."
  14461. (let ((files (directory-files (or dir default-directory)
  14462. t "\\`[^.#].*\\.org\\'"))
  14463. visiting m buffer)
  14464. (catch 'found
  14465. (dolist (file files)
  14466. (message "trying %s" file)
  14467. (setq visiting (org-find-base-buffer-visiting file))
  14468. (setq buffer (or visiting (find-file-noselect file)))
  14469. (setq m (org-find-exact-headline-in-buffer
  14470. heading buffer))
  14471. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14472. (and m (throw 'found m))))))
  14473. (defun org-find-entry-with-id (ident)
  14474. "Locate the entry that contains the ID property with exact value IDENT.
  14475. IDENT can be a string, a symbol or a number, this function will search for
  14476. the string representation of it.
  14477. Return the position where this entry starts, or nil if there is no such entry."
  14478. (interactive "sID: ")
  14479. (let ((id (cond
  14480. ((stringp ident) ident)
  14481. ((symbolp ident) (symbol-name ident))
  14482. ((numberp ident) (number-to-string ident))
  14483. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14484. (org-with-wide-buffer (org-find-property "ID" id))))
  14485. ;;;; Timestamps
  14486. (defvar org-last-changed-timestamp nil)
  14487. (defvar org-last-inserted-timestamp nil
  14488. "The last time stamp inserted with `org-insert-time-stamp'.")
  14489. (defun org-time-stamp (arg &optional inactive)
  14490. "Prompt for a date/time and insert a time stamp.
  14491. If the user specifies a time like HH:MM or if this command is
  14492. called with at least one prefix argument, the time stamp contains
  14493. the date and the time. Otherwise, only the date is included.
  14494. All parts of a date not specified by the user are filled in from
  14495. the timestamp at point, if any, or the current date/time
  14496. otherwise.
  14497. If there is already a timestamp at the cursor, it is replaced.
  14498. With two universal prefix arguments, insert an active timestamp
  14499. with the current time without prompting the user.
  14500. When called from lisp, the timestamp is inactive if INACTIVE is
  14501. non-nil."
  14502. (interactive "P")
  14503. (let* ((ts (cond
  14504. ((org-at-date-range-p t)
  14505. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14506. ((org-at-timestamp-p 'lax) (match-string 0))))
  14507. ;; Default time is either the timestamp at point or today.
  14508. ;; When entering a range, only the range start is considered.
  14509. (default-time (if (not ts) (current-time)
  14510. (apply #'encode-time (org-parse-time-string ts))))
  14511. (default-input (and ts (org-get-compact-tod ts)))
  14512. (repeater (and ts
  14513. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14514. (match-string 0 ts)))
  14515. org-time-was-given
  14516. org-end-time-was-given
  14517. (time
  14518. (and (if (equal arg '(16)) (current-time)
  14519. ;; Preserve `this-command' and `last-command'.
  14520. (let ((this-command this-command)
  14521. (last-command last-command))
  14522. (org-read-date
  14523. arg 'totime nil nil default-time default-input
  14524. inactive))))))
  14525. (cond
  14526. ((and ts
  14527. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14528. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14529. (insert "--")
  14530. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14531. (ts
  14532. ;; Make sure we're on a timestamp. When in the middle of a date
  14533. ;; range, move arbitrarily to range end.
  14534. (unless (org-at-timestamp-p 'lax)
  14535. (skip-chars-forward "-")
  14536. (org-at-timestamp-p 'lax))
  14537. (replace-match "")
  14538. (setq org-last-changed-timestamp
  14539. (org-insert-time-stamp
  14540. time (or org-time-was-given arg)
  14541. inactive nil nil (list org-end-time-was-given)))
  14542. (when repeater
  14543. (backward-char)
  14544. (insert " " repeater)
  14545. (setq org-last-changed-timestamp
  14546. (concat (substring org-last-inserted-timestamp 0 -1)
  14547. " " repeater ">")))
  14548. (message "Timestamp updated"))
  14549. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14550. (t (org-insert-time-stamp
  14551. time (or org-time-was-given arg) inactive nil nil
  14552. (list org-end-time-was-given))))))
  14553. ;; FIXME: can we use this for something else, like computing time differences?
  14554. (defun org-get-compact-tod (s)
  14555. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14556. (let* ((t1 (match-string 1 s))
  14557. (h1 (string-to-number (match-string 2 s)))
  14558. (m1 (string-to-number (match-string 3 s)))
  14559. (t2 (and (match-end 4) (match-string 5 s)))
  14560. (h2 (and t2 (string-to-number (match-string 6 s))))
  14561. (m2 (and t2 (string-to-number (match-string 7 s))))
  14562. dh dm)
  14563. (if (not t2)
  14564. t1
  14565. (setq dh (- h2 h1) dm (- m2 m1))
  14566. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14567. (concat t1 "+" (number-to-string dh)
  14568. (and (/= 0 dm) (format ":%02d" dm)))))))
  14569. (defun org-time-stamp-inactive (&optional arg)
  14570. "Insert an inactive time stamp.
  14571. An inactive time stamp is enclosed in square brackets instead of angle
  14572. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14573. does not link to the calendar and cannot be changed with the S-cursor keys.
  14574. So these are more for recording a certain time/date."
  14575. (interactive "P")
  14576. (org-time-stamp arg 'inactive))
  14577. (defvar org-date-ovl (make-overlay 1 1))
  14578. (overlay-put org-date-ovl 'face 'org-date-selected)
  14579. (delete-overlay org-date-ovl)
  14580. (defvar org-ans1) ; dynamically scoped parameter
  14581. (defvar org-ans2) ; dynamically scoped parameter
  14582. (defvar org-plain-time-of-day-regexp) ; defined below
  14583. (defvar org-overriding-default-time nil) ; dynamically scoped
  14584. (defvar org-read-date-overlay nil)
  14585. (defvar org-dcst nil) ; dynamically scoped
  14586. (defvar org-read-date-history nil)
  14587. (defvar org-read-date-final-answer nil)
  14588. (defvar org-read-date-analyze-futurep nil)
  14589. (defvar org-read-date-analyze-forced-year nil)
  14590. (defvar org-read-date-inactive)
  14591. (defvar org-read-date-minibuffer-local-map
  14592. (let* ((map (make-sparse-keymap)))
  14593. (set-keymap-parent map minibuffer-local-map)
  14594. (org-defkey map (kbd ".")
  14595. (lambda () (interactive)
  14596. ;; Are we at the beginning of the prompt?
  14597. (if (looking-back "^[^:]+: "
  14598. (let ((inhibit-field-text-motion t))
  14599. (line-beginning-position)))
  14600. (org-eval-in-calendar '(calendar-goto-today))
  14601. (insert "."))))
  14602. (org-defkey map (kbd "C-.")
  14603. (lambda () (interactive)
  14604. (org-eval-in-calendar '(calendar-goto-today))))
  14605. (org-defkey map (kbd "M-S-<left>")
  14606. (lambda () (interactive)
  14607. (org-eval-in-calendar '(calendar-backward-month 1))))
  14608. (org-defkey map (kbd "ESC S-<left>")
  14609. (lambda () (interactive)
  14610. (org-eval-in-calendar '(calendar-backward-month 1))))
  14611. (org-defkey map (kbd "M-S-<right>")
  14612. (lambda () (interactive)
  14613. (org-eval-in-calendar '(calendar-forward-month 1))))
  14614. (org-defkey map (kbd "ESC S-<right>")
  14615. (lambda () (interactive)
  14616. (org-eval-in-calendar '(calendar-forward-month 1))))
  14617. (org-defkey map (kbd "M-S-<up>")
  14618. (lambda () (interactive)
  14619. (org-eval-in-calendar '(calendar-backward-year 1))))
  14620. (org-defkey map (kbd "ESC S-<up>")
  14621. (lambda () (interactive)
  14622. (org-eval-in-calendar '(calendar-backward-year 1))))
  14623. (org-defkey map (kbd "M-S-<down>")
  14624. (lambda () (interactive)
  14625. (org-eval-in-calendar '(calendar-forward-year 1))))
  14626. (org-defkey map (kbd "ESC S-<down>")
  14627. (lambda () (interactive)
  14628. (org-eval-in-calendar '(calendar-forward-year 1))))
  14629. (org-defkey map (kbd "S-<up>")
  14630. (lambda () (interactive)
  14631. (org-eval-in-calendar '(calendar-backward-week 1))))
  14632. (org-defkey map (kbd "S-<down>")
  14633. (lambda () (interactive)
  14634. (org-eval-in-calendar '(calendar-forward-week 1))))
  14635. (org-defkey map (kbd "S-<left>")
  14636. (lambda () (interactive)
  14637. (org-eval-in-calendar '(calendar-backward-day 1))))
  14638. (org-defkey map (kbd "S-<right>")
  14639. (lambda () (interactive)
  14640. (org-eval-in-calendar '(calendar-forward-day 1))))
  14641. (org-defkey map "!"
  14642. (lambda () (interactive)
  14643. (org-eval-in-calendar '(diary-view-entries))
  14644. (message "")))
  14645. (org-defkey map ">"
  14646. (lambda () (interactive)
  14647. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14648. (org-defkey map "<"
  14649. (lambda () (interactive)
  14650. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14651. (org-defkey map "\C-v"
  14652. (lambda () (interactive)
  14653. (org-eval-in-calendar
  14654. '(calendar-scroll-left-three-months 1))))
  14655. (org-defkey map "\M-v"
  14656. (lambda () (interactive)
  14657. (org-eval-in-calendar
  14658. '(calendar-scroll-right-three-months 1))))
  14659. map)
  14660. "Keymap for minibuffer commands when using `org-read-date'.")
  14661. (defvar org-def)
  14662. (defvar org-defdecode)
  14663. (defvar org-with-time)
  14664. (defvar calendar-setup) ; Dynamically scoped.
  14665. (defun org-read-date (&optional with-time to-time from-string prompt
  14666. default-time default-input inactive)
  14667. "Read a date, possibly a time, and make things smooth for the user.
  14668. The prompt will suggest to enter an ISO date, but you can also enter anything
  14669. which will at least partially be understood by `parse-time-string'.
  14670. Unrecognized parts of the date will default to the current day, month, year,
  14671. hour and minute. If this command is called to replace a timestamp at point,
  14672. or to enter the second timestamp of a range, the default time is taken
  14673. from the existing stamp. Furthermore, the command prefers the future,
  14674. so if you are giving a date where the year is not given, and the day-month
  14675. combination is already past in the current year, it will assume you
  14676. mean next year. For details, see the manual. A few examples:
  14677. 3-2-5 --> 2003-02-05
  14678. feb 15 --> currentyear-02-15
  14679. 2/15 --> currentyear-02-15
  14680. sep 12 9 --> 2009-09-12
  14681. 12:45 --> today 12:45
  14682. 22 sept 0:34 --> currentyear-09-22 0:34
  14683. 12 --> currentyear-currentmonth-12
  14684. Fri --> nearest Friday after today
  14685. -Tue --> last Tuesday
  14686. etc.
  14687. Furthermore you can specify a relative date by giving, as the *first* thing
  14688. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14689. change in days weeks, months, years.
  14690. With a single plus or minus, the date is relative to today. With a double
  14691. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14692. +4d --> four days from today
  14693. +4 --> same as above
  14694. +2w --> two weeks from today
  14695. ++5 --> five days from default date
  14696. The function understands only English month and weekday abbreviations.
  14697. While prompting, a calendar is popped up - you can also select the
  14698. date with the mouse (button 1). The calendar shows a period of three
  14699. months. To scroll it to other months, use the keys `>' and `<'.
  14700. If you don't like the calendar, turn it off with
  14701. (setq org-read-date-popup-calendar nil)
  14702. With optional argument TO-TIME, the date will immediately be converted
  14703. to an internal time.
  14704. With an optional argument WITH-TIME, the prompt will suggest to
  14705. also insert a time. Note that when WITH-TIME is not set, you can
  14706. still enter a time, and this function will inform the calling routine
  14707. about this change. The calling routine may then choose to change the
  14708. format used to insert the time stamp into the buffer to include the time.
  14709. With optional argument FROM-STRING, read from this string instead from
  14710. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14711. the time/date that is used for everything that is not specified by the
  14712. user."
  14713. (require 'parse-time)
  14714. (let* ((org-with-time with-time)
  14715. (org-time-stamp-rounding-minutes
  14716. (if (equal org-with-time '(16))
  14717. '(0 0)
  14718. org-time-stamp-rounding-minutes))
  14719. (org-dcst org-display-custom-times)
  14720. (ct (org-current-time))
  14721. (org-def (or org-overriding-default-time default-time ct))
  14722. (org-defdecode (decode-time org-def))
  14723. (cur-frame (selected-frame))
  14724. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14725. (calendar-setup
  14726. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14727. (calendar-move-hook nil)
  14728. (calendar-view-diary-initially-flag nil)
  14729. (calendar-view-holidays-initially-flag nil)
  14730. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14731. ;; Rationalize `org-def' and `org-defdecode', if required.
  14732. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14733. (setf (nth 2 org-defdecode) -1)
  14734. (setf (nth 1 org-defdecode) 59)
  14735. (setq org-def (apply #'encode-time org-defdecode))
  14736. (setq org-defdecode (decode-time org-def)))
  14737. (let* ((timestr (format-time-string
  14738. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14739. org-def))
  14740. (prompt (concat (if prompt (concat prompt " ") "")
  14741. (format "Date+time [%s]: " timestr))))
  14742. (cond
  14743. (from-string (setq ans from-string))
  14744. (org-read-date-popup-calendar
  14745. (save-excursion
  14746. (save-window-excursion
  14747. (calendar)
  14748. (when (eq calendar-setup 'calendar-only)
  14749. (setq cal-frame
  14750. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14751. (select-frame cal-frame))
  14752. (org-eval-in-calendar '(setq cursor-type nil) t)
  14753. (unwind-protect
  14754. (progn
  14755. (calendar-forward-day (- (time-to-days org-def)
  14756. (calendar-absolute-from-gregorian
  14757. (calendar-current-date))))
  14758. (org-eval-in-calendar nil t)
  14759. (let* ((old-map (current-local-map))
  14760. (map (copy-keymap calendar-mode-map))
  14761. (minibuffer-local-map
  14762. (copy-keymap org-read-date-minibuffer-local-map)))
  14763. (org-defkey map (kbd "RET") 'org-calendar-select)
  14764. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14765. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14766. (unwind-protect
  14767. (progn
  14768. (use-local-map map)
  14769. (setq org-read-date-inactive inactive)
  14770. (add-hook 'post-command-hook 'org-read-date-display)
  14771. (setq org-ans0
  14772. (read-string prompt
  14773. default-input
  14774. 'org-read-date-history
  14775. nil))
  14776. ;; org-ans0: from prompt
  14777. ;; org-ans1: from mouse click
  14778. ;; org-ans2: from calendar motion
  14779. (setq ans
  14780. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14781. (remove-hook 'post-command-hook 'org-read-date-display)
  14782. (use-local-map old-map)
  14783. (when org-read-date-overlay
  14784. (delete-overlay org-read-date-overlay)
  14785. (setq org-read-date-overlay nil)))))
  14786. (bury-buffer "*Calendar*")
  14787. (when cal-frame
  14788. (delete-frame cal-frame)
  14789. (select-frame-set-input-focus cur-frame))))))
  14790. (t ; Naked prompt only
  14791. (unwind-protect
  14792. (setq ans (read-string prompt default-input
  14793. 'org-read-date-history timestr))
  14794. (when org-read-date-overlay
  14795. (delete-overlay org-read-date-overlay)
  14796. (setq org-read-date-overlay nil))))))
  14797. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14798. (when org-read-date-analyze-forced-year
  14799. (message "Year was forced into %s"
  14800. (if org-read-date-force-compatible-dates
  14801. "compatible range (1970-2037)"
  14802. "range representable on this machine"))
  14803. (ding))
  14804. ;; One round trip to get rid of 34th of August and stuff like that....
  14805. (setq final (decode-time (apply 'encode-time final)))
  14806. (setq org-read-date-final-answer ans)
  14807. (if to-time
  14808. (apply 'encode-time final)
  14809. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14810. (format "%04d-%02d-%02d %02d:%02d"
  14811. (nth 5 final) (nth 4 final) (nth 3 final)
  14812. (nth 2 final) (nth 1 final))
  14813. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14814. (defun org-read-date-display ()
  14815. "Display the current date prompt interpretation in the minibuffer."
  14816. (when org-read-date-display-live
  14817. (when org-read-date-overlay
  14818. (delete-overlay org-read-date-overlay))
  14819. (when (minibufferp (current-buffer))
  14820. (save-excursion
  14821. (end-of-line 1)
  14822. (while (not (equal (buffer-substring
  14823. (max (point-min) (- (point) 4)) (point))
  14824. " "))
  14825. (insert " ")))
  14826. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14827. " " (or org-ans1 org-ans2)))
  14828. (org-end-time-was-given nil)
  14829. (f (org-read-date-analyze ans org-def org-defdecode))
  14830. (fmts (if org-dcst
  14831. org-time-stamp-custom-formats
  14832. org-time-stamp-formats))
  14833. (fmt (if (or org-with-time
  14834. (and (boundp 'org-time-was-given) org-time-was-given))
  14835. (cdr fmts)
  14836. (car fmts)))
  14837. (txt (format-time-string fmt (apply 'encode-time f)))
  14838. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14839. (txt (concat "=> " txt)))
  14840. (when (and org-end-time-was-given
  14841. (string-match org-plain-time-of-day-regexp txt))
  14842. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14843. org-end-time-was-given
  14844. (substring txt (match-end 0)))))
  14845. (when org-read-date-analyze-futurep
  14846. (setq txt (concat txt " (=>F)")))
  14847. (setq org-read-date-overlay
  14848. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14849. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14850. (defun org-read-date-analyze (ans def defdecode)
  14851. "Analyze the combined answer of the date prompt."
  14852. ;; FIXME: cleanup and comment
  14853. ;; Pass `current-time' result to `decode-time' (instead of calling
  14854. ;; without arguments) so that only `current-time' has to be
  14855. ;; overridden in tests.
  14856. (let ((org-def def)
  14857. (org-defdecode defdecode)
  14858. (nowdecode (decode-time (current-time)))
  14859. delta deltan deltaw deltadef year month day
  14860. hour minute second wday pm h2 m2 tl wday1
  14861. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14862. (setq org-read-date-analyze-futurep nil
  14863. org-read-date-analyze-forced-year nil)
  14864. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14865. (setq ans "+0"))
  14866. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14867. (setq ans (replace-match "" t t ans)
  14868. deltan (car delta)
  14869. deltaw (nth 1 delta)
  14870. deltadef (nth 2 delta)))
  14871. ;; Check if there is an iso week date in there. If yes, store the
  14872. ;; info and postpone interpreting it until the rest of the parsing
  14873. ;; is done.
  14874. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14875. (setq iso-year (when (match-end 1)
  14876. (org-small-year-to-year
  14877. (string-to-number (match-string 1 ans))))
  14878. iso-weekday (when (match-end 3)
  14879. (string-to-number (match-string 3 ans)))
  14880. iso-week (string-to-number (match-string 2 ans)))
  14881. (setq ans (replace-match "" t t ans)))
  14882. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14883. (when (string-match
  14884. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14885. (setq year (if (match-end 2)
  14886. (string-to-number (match-string 2 ans))
  14887. (progn (setq kill-year t)
  14888. (string-to-number (format-time-string "%Y"))))
  14889. month (string-to-number (match-string 3 ans))
  14890. day (string-to-number (match-string 4 ans)))
  14891. (setq year (org-small-year-to-year year))
  14892. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14893. t nil ans)))
  14894. ;; Help matching dotted european dates
  14895. (when (string-match
  14896. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14897. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14898. (setq kill-year t)
  14899. (string-to-number (format-time-string "%Y")))
  14900. day (string-to-number (match-string 1 ans))
  14901. month (string-to-number (match-string 2 ans))
  14902. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14903. t nil ans)))
  14904. ;; Help matching american dates, like 5/30 or 5/30/7
  14905. (when (string-match
  14906. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14907. (setq year (if (match-end 4)
  14908. (string-to-number (match-string 4 ans))
  14909. (progn (setq kill-year t)
  14910. (string-to-number (format-time-string "%Y"))))
  14911. month (string-to-number (match-string 1 ans))
  14912. day (string-to-number (match-string 2 ans)))
  14913. (setq year (org-small-year-to-year year))
  14914. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14915. t nil ans)))
  14916. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14917. ;; If there is a time with am/pm, and *no* time without it, we convert
  14918. ;; so that matching will be successful.
  14919. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14920. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14921. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14922. (setq hour (string-to-number (match-string 1 ans))
  14923. minute (if (match-end 3)
  14924. (string-to-number (match-string 3 ans))
  14925. 0)
  14926. pm (equal ?p
  14927. (string-to-char (downcase (match-string 4 ans)))))
  14928. (if (and (= hour 12) (not pm))
  14929. (setq hour 0)
  14930. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14931. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14932. t t ans))))
  14933. ;; Check if a time range is given as a duration
  14934. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14935. (setq hour (string-to-number (match-string 1 ans))
  14936. h2 (+ hour (string-to-number (match-string 3 ans)))
  14937. minute (string-to-number (match-string 2 ans))
  14938. m2 (+ minute (if (match-end 5) (string-to-number
  14939. (match-string 5 ans))0)))
  14940. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14941. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14942. t t ans)))
  14943. ;; Check if there is a time range
  14944. (when (boundp 'org-end-time-was-given)
  14945. (setq org-time-was-given nil)
  14946. (when (and (string-match org-plain-time-of-day-regexp ans)
  14947. (match-end 8))
  14948. (setq org-end-time-was-given (match-string 8 ans))
  14949. (setq ans (concat (substring ans 0 (match-beginning 7))
  14950. (substring ans (match-end 7))))))
  14951. (setq tl (parse-time-string ans)
  14952. day (or (nth 3 tl) (nth 3 org-defdecode))
  14953. month
  14954. (cond ((nth 4 tl))
  14955. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14956. ;; Day was specified. Make sure DAY+MONTH
  14957. ;; combination happens in the future.
  14958. ((nth 3 tl)
  14959. (setq futurep t)
  14960. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14961. (nth 4 nowdecode)))
  14962. (t (nth 4 org-defdecode)))
  14963. year
  14964. (cond ((and (not kill-year) (nth 5 tl)))
  14965. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14966. ;; Month was guessed in the future and is at least
  14967. ;; equal to NOWDECODE's. Fix year accordingly.
  14968. (futurep
  14969. (if (or (> month (nth 4 nowdecode))
  14970. (>= day (nth 3 nowdecode)))
  14971. (nth 5 nowdecode)
  14972. (1+ (nth 5 nowdecode))))
  14973. ;; Month was specified. Make sure MONTH+YEAR
  14974. ;; combination happens in the future.
  14975. ((nth 4 tl)
  14976. (setq futurep t)
  14977. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  14978. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  14979. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  14980. (t (nth 5 nowdecode))))
  14981. (t (nth 5 org-defdecode)))
  14982. hour (or (nth 2 tl) (nth 2 org-defdecode))
  14983. minute (or (nth 1 tl) (nth 1 org-defdecode))
  14984. second (or (nth 0 tl) 0)
  14985. wday (nth 6 tl))
  14986. (when (and (eq org-read-date-prefer-future 'time)
  14987. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  14988. (equal day (nth 3 nowdecode))
  14989. (equal month (nth 4 nowdecode))
  14990. (equal year (nth 5 nowdecode))
  14991. (nth 2 tl)
  14992. (or (< (nth 2 tl) (nth 2 nowdecode))
  14993. (and (= (nth 2 tl) (nth 2 nowdecode))
  14994. (nth 1 tl)
  14995. (< (nth 1 tl) (nth 1 nowdecode)))))
  14996. (setq day (1+ day)
  14997. futurep t))
  14998. ;; Special date definitions below
  14999. (cond
  15000. (iso-week
  15001. ;; There was an iso week
  15002. (require 'cal-iso)
  15003. (setq futurep nil)
  15004. (setq year (or iso-year year)
  15005. day (or iso-weekday wday 1)
  15006. wday nil ; to make sure that the trigger below does not match
  15007. iso-date (calendar-gregorian-from-absolute
  15008. (calendar-iso-to-absolute
  15009. (list iso-week day year))))
  15010. ; FIXME: Should we also push ISO weeks into the future?
  15011. ; (when (and org-read-date-prefer-future
  15012. ; (not iso-year)
  15013. ; (< (calendar-absolute-from-gregorian iso-date)
  15014. ; (time-to-days (current-time))))
  15015. ; (setq year (1+ year)
  15016. ; iso-date (calendar-gregorian-from-absolute
  15017. ; (calendar-iso-to-absolute
  15018. ; (list iso-week day year)))))
  15019. (setq month (car iso-date)
  15020. year (nth 2 iso-date)
  15021. day (nth 1 iso-date)))
  15022. (deltan
  15023. (setq futurep nil)
  15024. (unless deltadef
  15025. ;; Pass `current-time' result to `decode-time' (instead of
  15026. ;; calling without arguments) so that only `current-time' has
  15027. ;; to be overridden in tests.
  15028. (let ((now (decode-time (current-time))))
  15029. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15030. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15031. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15032. ((equal deltaw "m") (setq month (+ month deltan)))
  15033. ((equal deltaw "y") (setq year (+ year deltan)))))
  15034. ((and wday (not (nth 3 tl)))
  15035. ;; Weekday was given, but no day, so pick that day in the week
  15036. ;; on or after the derived date.
  15037. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15038. (unless (equal wday wday1)
  15039. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15040. (when (and (boundp 'org-time-was-given)
  15041. (nth 2 tl))
  15042. (setq org-time-was-given t))
  15043. (when (< year 100) (setq year (+ 2000 year)))
  15044. ;; Check of the date is representable
  15045. (if org-read-date-force-compatible-dates
  15046. (progn
  15047. (when (< year 1970)
  15048. (setq year 1970 org-read-date-analyze-forced-year t))
  15049. (when (> year 2037)
  15050. (setq year 2037 org-read-date-analyze-forced-year t)))
  15051. (condition-case nil
  15052. (ignore (encode-time second minute hour day month year))
  15053. (error
  15054. (setq year (nth 5 org-defdecode))
  15055. (setq org-read-date-analyze-forced-year t))))
  15056. (setq org-read-date-analyze-futurep futurep)
  15057. (list second minute hour day month year)))
  15058. (defvar parse-time-weekdays)
  15059. (defun org-read-date-get-relative (s today default)
  15060. "Check string S for special relative date string.
  15061. TODAY and DEFAULT are internal times, for today and for a default.
  15062. Return shift list (N what def-flag)
  15063. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15064. N is the number of WHATs to shift.
  15065. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15066. the DEFAULT date rather than TODAY."
  15067. (require 'parse-time)
  15068. (when (and
  15069. (string-match
  15070. (concat
  15071. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15072. "\\([0-9]+\\)?"
  15073. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15074. "\\([ \t]\\|$\\)") s)
  15075. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15076. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15077. (string-to-char (substring (match-string 1 s) -1))
  15078. ?+))
  15079. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15080. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15081. (what (if (match-end 3) (match-string 3 s) "d"))
  15082. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15083. (date (if rel default today))
  15084. (wday (nth 6 (decode-time date)))
  15085. delta)
  15086. (if wday1
  15087. (progn
  15088. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15089. (when (= delta 0) (setq delta 7))
  15090. (when (= dir ?-)
  15091. (setq delta (- delta 7))
  15092. (when (= delta 0) (setq delta -7)))
  15093. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15094. (list delta "d" rel))
  15095. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15096. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15097. "Turn a user-specified date into the internal representation.
  15098. The internal representation needed by the calendar is (month day year).
  15099. This is a wrapper to handle the brain-dead convention in calendar that
  15100. user function argument order change dependent on argument order."
  15101. (pcase calendar-date-style
  15102. (`american (list arg1 arg2 arg3))
  15103. (`european (list arg2 arg1 arg3))
  15104. (`iso (list arg2 arg3 arg1))))
  15105. (defun org-eval-in-calendar (form &optional keepdate)
  15106. "Eval FORM in the calendar window and return to current window.
  15107. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15108. (let ((sf (selected-frame))
  15109. (sw (selected-window)))
  15110. (select-window (get-buffer-window "*Calendar*" t))
  15111. (eval form)
  15112. (when (and (not keepdate) (calendar-cursor-to-date))
  15113. (let* ((date (calendar-cursor-to-date))
  15114. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15115. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15116. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15117. (select-window sw)
  15118. (select-frame-set-input-focus sf)))
  15119. (defun org-calendar-select ()
  15120. "Return to `org-read-date' with the date currently selected.
  15121. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15122. (interactive)
  15123. (when (calendar-cursor-to-date)
  15124. (let* ((date (calendar-cursor-to-date))
  15125. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15126. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15127. (when (active-minibuffer-window) (exit-minibuffer))))
  15128. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15129. "Insert a date stamp for the date given by the internal TIME.
  15130. See `format-time-string' for the format of TIME.
  15131. WITH-HM means use the stamp format that includes the time of the day.
  15132. INACTIVE means use square brackets instead of angular ones, so that the
  15133. stamp will not contribute to the agenda.
  15134. PRE and POST are optional strings to be inserted before and after the
  15135. stamp.
  15136. The command returns the inserted time stamp."
  15137. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15138. stamp)
  15139. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15140. (insert-before-markers (or pre ""))
  15141. (when (listp extra)
  15142. (setq extra (car extra))
  15143. (if (and (stringp extra)
  15144. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15145. (setq extra (format "-%02d:%02d"
  15146. (string-to-number (match-string 1 extra))
  15147. (string-to-number (match-string 2 extra))))
  15148. (setq extra nil)))
  15149. (when extra
  15150. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15151. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15152. (insert-before-markers (or post ""))
  15153. (setq org-last-inserted-timestamp stamp)))
  15154. (defun org-toggle-time-stamp-overlays ()
  15155. "Toggle the use of custom time stamp formats."
  15156. (interactive)
  15157. (setq org-display-custom-times (not org-display-custom-times))
  15158. (unless org-display-custom-times
  15159. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15160. (while (setq p (next-single-property-change p 'display))
  15161. (when (and (get-text-property p 'display)
  15162. (eq (get-text-property p 'face) 'org-date))
  15163. (remove-text-properties
  15164. p (setq p (next-single-property-change p 'display))
  15165. '(display t))))
  15166. (set-buffer-modified-p bmp)))
  15167. (org-restart-font-lock)
  15168. (setq org-table-may-need-update t)
  15169. (if org-display-custom-times
  15170. (message "Time stamps are overlaid with custom format")
  15171. (message "Time stamp overlays removed")))
  15172. (defun org-display-custom-time (beg end)
  15173. "Overlay modified time stamp format over timestamp between BEG and END."
  15174. (let* ((ts (buffer-substring beg end))
  15175. t1 with-hm tf time str (off 0))
  15176. (save-match-data
  15177. (setq t1 (org-parse-time-string ts t))
  15178. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15179. (setq off (- (match-end 0) (match-beginning 0)))))
  15180. (setq end (- end off))
  15181. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15182. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15183. time (org-fix-decoded-time t1)
  15184. str (org-add-props
  15185. (format-time-string
  15186. (substring tf 1 -1) (apply 'encode-time time))
  15187. nil 'mouse-face 'highlight))
  15188. (put-text-property beg end 'display str)))
  15189. (defun org-fix-decoded-time (time)
  15190. "Set 0 instead of nil for the first 6 elements of time.
  15191. Don't touch the rest."
  15192. (let ((n 0))
  15193. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15194. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15195. "Difference between TIMESTAMP-STRING and now in days.
  15196. If SECONDS is non-nil, return the difference in seconds."
  15197. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15198. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15199. (funcall fdiff (current-time)))))
  15200. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15201. "Is the time in TIMESTAMP-STRING close to the current date?"
  15202. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15203. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15204. (not (org-entry-is-done-p))))
  15205. (defun org-get-wdays (ts &optional delay zero-delay)
  15206. "Get the deadline lead time appropriate for timestring TS.
  15207. When DELAY is non-nil, get the delay time for scheduled items
  15208. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15209. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15210. don't try to find the delay cookie in the scheduled timestamp."
  15211. (let ((tv (if delay org-scheduled-delay-days
  15212. org-deadline-warning-days)))
  15213. (cond
  15214. ((or (and delay (< tv 0))
  15215. (and delay zero-delay (<= tv 0))
  15216. (and (not delay) (<= tv 0)))
  15217. ;; Enforce this value no matter what
  15218. (- tv))
  15219. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15220. ;; lead time is specified.
  15221. (floor (* (string-to-number (match-string 1 ts))
  15222. (cdr (assoc (match-string 2 ts)
  15223. '(("d" . 1) ("w" . 7)
  15224. ("m" . 30.4) ("y" . 365.25)
  15225. ("h" . 0.041667)))))))
  15226. ;; go for the default.
  15227. (t tv))))
  15228. (defun org-calendar-select-mouse (ev)
  15229. "Return to `org-read-date' with the date currently selected.
  15230. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15231. (interactive "e")
  15232. (mouse-set-point ev)
  15233. (when (calendar-cursor-to-date)
  15234. (let* ((date (calendar-cursor-to-date))
  15235. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15236. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15237. (when (active-minibuffer-window) (exit-minibuffer))))
  15238. (defun org-check-deadlines (ndays)
  15239. "Check if there are any deadlines due or past due.
  15240. A deadline is considered due if it happens within `org-deadline-warning-days'
  15241. days from today's date. If the deadline appears in an entry marked DONE,
  15242. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15243. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15244. are shown."
  15245. (interactive "P")
  15246. (let* ((org-warn-days
  15247. (cond
  15248. ((equal ndays '(4)) 100000)
  15249. (ndays (prefix-numeric-value ndays))
  15250. (t (abs org-deadline-warning-days))))
  15251. (case-fold-search nil)
  15252. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15253. (callback
  15254. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15255. (message "%d deadlines past-due or due within %d days"
  15256. (org-occur regexp nil callback)
  15257. org-warn-days)))
  15258. (defsubst org-re-timestamp (type)
  15259. "Return a regexp for timestamp TYPE.
  15260. Allowed values for TYPE are:
  15261. all: all timestamps
  15262. active: only active timestamps (<...>)
  15263. inactive: only inactive timestamps ([...])
  15264. scheduled: only scheduled timestamps
  15265. deadline: only deadline timestamps
  15266. closed: only closed time-stamps
  15267. When TYPE is nil, fall back on returning a regexp that matches
  15268. both scheduled and deadline timestamps."
  15269. (cl-case type
  15270. (all org-ts-regexp-both)
  15271. (active org-ts-regexp)
  15272. (inactive org-ts-regexp-inactive)
  15273. (scheduled org-scheduled-time-regexp)
  15274. (deadline org-deadline-time-regexp)
  15275. (closed org-closed-time-regexp)
  15276. (otherwise
  15277. (concat "\\<"
  15278. (regexp-opt (list org-deadline-string org-scheduled-string))
  15279. " *<\\([^>]+\\)>"))))
  15280. (defun org-check-before-date (d)
  15281. "Check if there are deadlines or scheduled entries before date D."
  15282. (interactive (list (org-read-date)))
  15283. (let* ((case-fold-search nil)
  15284. (regexp (org-re-timestamp org-ts-type))
  15285. (ts-type org-ts-type)
  15286. (callback
  15287. (lambda ()
  15288. (let ((match (match-string 1)))
  15289. (and (if (memq ts-type '(active inactive all))
  15290. (eq (org-element-type (save-excursion
  15291. (backward-char)
  15292. (org-element-context)))
  15293. 'timestamp)
  15294. (org-at-planning-p))
  15295. (time-less-p
  15296. (org-time-string-to-time match)
  15297. (org-time-string-to-time d)))))))
  15298. (message "%d entries before %s"
  15299. (org-occur regexp nil callback)
  15300. d)))
  15301. (defun org-check-after-date (d)
  15302. "Check if there are deadlines or scheduled entries after date D."
  15303. (interactive (list (org-read-date)))
  15304. (let* ((case-fold-search nil)
  15305. (regexp (org-re-timestamp org-ts-type))
  15306. (ts-type org-ts-type)
  15307. (callback
  15308. (lambda ()
  15309. (let ((match (match-string 1)))
  15310. (and (if (memq ts-type '(active inactive all))
  15311. (eq (org-element-type (save-excursion
  15312. (backward-char)
  15313. (org-element-context)))
  15314. 'timestamp)
  15315. (org-at-planning-p))
  15316. (not (time-less-p
  15317. (org-time-string-to-time match)
  15318. (org-time-string-to-time d))))))))
  15319. (message "%d entries after %s"
  15320. (org-occur regexp nil callback)
  15321. d)))
  15322. (defun org-check-dates-range (start-date end-date)
  15323. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15324. (interactive (list (org-read-date nil nil nil "Range starts")
  15325. (org-read-date nil nil nil "Range end")))
  15326. (let ((case-fold-search nil)
  15327. (regexp (org-re-timestamp org-ts-type))
  15328. (callback
  15329. (let ((type org-ts-type))
  15330. (lambda ()
  15331. (let ((match (match-string 1)))
  15332. (and
  15333. (if (memq type '(active inactive all))
  15334. (eq (org-element-type (save-excursion
  15335. (backward-char)
  15336. (org-element-context)))
  15337. 'timestamp)
  15338. (org-at-planning-p))
  15339. (not (time-less-p
  15340. (org-time-string-to-time match)
  15341. (org-time-string-to-time start-date)))
  15342. (time-less-p
  15343. (org-time-string-to-time match)
  15344. (org-time-string-to-time end-date))))))))
  15345. (message "%d entries between %s and %s"
  15346. (org-occur regexp nil callback) start-date end-date)))
  15347. (defun org-evaluate-time-range (&optional to-buffer)
  15348. "Evaluate a time range by computing the difference between start and end.
  15349. Normally the result is just printed in the echo area, but with prefix arg
  15350. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15351. If the time range is actually in a table, the result is inserted into the
  15352. next column.
  15353. For time difference computation, a year is assumed to be exactly 365
  15354. days in order to avoid rounding problems."
  15355. (interactive "P")
  15356. (or
  15357. (org-clock-update-time-maybe)
  15358. (save-excursion
  15359. (unless (org-at-date-range-p t)
  15360. (goto-char (point-at-bol))
  15361. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15362. (unless (org-at-date-range-p t)
  15363. (user-error "Not at a time-stamp range, and none found in current line")))
  15364. (let* ((ts1 (match-string 1))
  15365. (ts2 (match-string 2))
  15366. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15367. (match-end (match-end 0))
  15368. (time1 (org-time-string-to-time ts1))
  15369. (time2 (org-time-string-to-time ts2))
  15370. (t1 (float-time time1))
  15371. (t2 (float-time time2))
  15372. (diff (abs (- t2 t1)))
  15373. (negative (< (- t2 t1) 0))
  15374. ;; (ys (floor (* 365 24 60 60)))
  15375. (ds (* 24 60 60))
  15376. (hs (* 60 60))
  15377. (fy "%dy %dd %02d:%02d")
  15378. (fy1 "%dy %dd")
  15379. (fd "%dd %02d:%02d")
  15380. (fd1 "%dd")
  15381. (fh "%02d:%02d")
  15382. y d h m align)
  15383. (if havetime
  15384. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15385. y 0
  15386. d (floor (/ diff ds)) diff (mod diff ds)
  15387. h (floor (/ diff hs)) diff (mod diff hs)
  15388. m (floor (/ diff 60)))
  15389. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15390. y 0
  15391. d (floor (+ (/ diff ds) 0.5))
  15392. h 0 m 0))
  15393. (if (not to-buffer)
  15394. (message "%s" (org-make-tdiff-string y d h m))
  15395. (if (org-at-table-p)
  15396. (progn
  15397. (goto-char match-end)
  15398. (setq align t)
  15399. (and (looking-at " *|") (goto-char (match-end 0))))
  15400. (goto-char match-end))
  15401. (when (looking-at
  15402. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15403. (replace-match ""))
  15404. (when negative (insert " -"))
  15405. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15406. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15407. (insert " " (format fh h m))))
  15408. (when align (org-table-align))
  15409. (message "Time difference inserted")))))
  15410. (defun org-make-tdiff-string (y d h m)
  15411. (let ((fmt "")
  15412. (l nil))
  15413. (when (> y 0)
  15414. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15415. (push y l))
  15416. (when (> d 0)
  15417. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15418. (push d l))
  15419. (when (> h 0)
  15420. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15421. (push h l))
  15422. (when (> m 0)
  15423. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15424. (push m l))
  15425. (apply 'format fmt (nreverse l))))
  15426. (defun org-time-string-to-time (s)
  15427. "Convert timestamp string S into internal time."
  15428. (apply #'encode-time (org-parse-time-string s)))
  15429. (defun org-time-string-to-seconds (s)
  15430. "Convert a timestamp string S into a number of seconds."
  15431. (float-time (org-time-string-to-time s)))
  15432. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15433. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15434. "Convert time stamp S to an absolute day number.
  15435. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15436. stamp, get the closest date to DAYNR. If PREFER is
  15437. `past' (respectively `future') return a date past (respectively
  15438. after) or equal to DAYNR.
  15439. POS is the location of time stamp S, as a buffer position in
  15440. BUFFER.
  15441. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15442. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15443. signaled."
  15444. (cond
  15445. ((string-match "\\`%%\\((.*)\\)" s)
  15446. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15447. ;; only able to match individual dates. If it fails, raise an
  15448. ;; error.
  15449. (if (and daynr
  15450. (org-diary-sexp-entry
  15451. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15452. daynr
  15453. (signal 'org-diary-sexp-no-match (list s))))
  15454. (daynr (org-closest-date s daynr prefer))
  15455. (t (time-to-days
  15456. (condition-case errdata
  15457. (apply #'encode-time (org-parse-time-string s))
  15458. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15459. s
  15460. (if (not (and buffer pos)) ""
  15461. (format-message " at %d in buffer `%s'" pos buffer))
  15462. (cdr errdata))))))))
  15463. (defun org-days-to-iso-week (days)
  15464. "Return the iso week number."
  15465. (require 'cal-iso)
  15466. (car (calendar-iso-from-absolute days)))
  15467. (defun org-small-year-to-year (year)
  15468. "Convert 2-digit years into 4-digit years.
  15469. YEAR is expanded into one of the 30 next years, if possible, or
  15470. into a past one. Any year larger than 99 is returned unchanged."
  15471. (if (>= year 100) year
  15472. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15473. (century (/ current 100))
  15474. (offset (- year (% current 100))))
  15475. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15476. ((> offset -70) (+ (* century 100) year))
  15477. (t (+ (* (1+ century) 100) year))))))
  15478. (defun org-time-from-absolute (d)
  15479. "Return the time corresponding to date D.
  15480. D may be an absolute day number, or a calendar-type list (month day year)."
  15481. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15482. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15483. (defvar org-agenda-current-date)
  15484. (defun org-calendar-holiday ()
  15485. "List of holidays, for Diary display in Org mode."
  15486. (require 'holidays)
  15487. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15488. (and hl (mapconcat #'identity hl "; "))))
  15489. (defun org-diary-sexp-entry (sexp entry d)
  15490. "Process a SEXP diary ENTRY for date D."
  15491. (require 'diary-lib)
  15492. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15493. ;; dynamically.
  15494. (let* ((sexp `(let ((entry ,entry)
  15495. (date ',d))
  15496. ,(car (read-from-string sexp))))
  15497. (result (if calendar-debug-sexp (eval sexp)
  15498. (condition-case nil
  15499. (eval sexp)
  15500. (error
  15501. (beep)
  15502. (message "Bad sexp at line %d in %s: %s"
  15503. (org-current-line)
  15504. (buffer-file-name) sexp)
  15505. (sleep-for 2))))))
  15506. (cond ((stringp result) (split-string result "; "))
  15507. ((and (consp result)
  15508. (not (consp (cdr result)))
  15509. (stringp (cdr result))) (cdr result))
  15510. ((and (consp result)
  15511. (stringp (car result))) result)
  15512. (result entry))))
  15513. (defun org-diary-to-ical-string (frombuf)
  15514. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15515. This uses the icalendar.el library."
  15516. (let* ((tmpdir temporary-file-directory)
  15517. (tmpfile (make-temp-name
  15518. (expand-file-name "orgics" tmpdir)))
  15519. buf rtn b e)
  15520. (with-current-buffer frombuf
  15521. (icalendar-export-region (point-min) (point-max) tmpfile)
  15522. (setq buf (find-buffer-visiting tmpfile))
  15523. (set-buffer buf)
  15524. (goto-char (point-min))
  15525. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15526. (setq b (match-beginning 0)))
  15527. (goto-char (point-max))
  15528. (when (re-search-backward "^END:VEVENT" nil t)
  15529. (setq e (match-end 0)))
  15530. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15531. (kill-buffer buf)
  15532. (delete-file tmpfile)
  15533. rtn))
  15534. (defun org-closest-date (start current prefer)
  15535. "Return closest date to CURRENT starting from START.
  15536. CURRENT and START are both time stamps.
  15537. When PREFER is `past', return a date that is either CURRENT or
  15538. past. When PREFER is `future', return a date that is either
  15539. CURRENT or future.
  15540. Only time stamps with a repeater are modified. Any other time
  15541. stamp stay unchanged. In any case, return value is an absolute
  15542. day number."
  15543. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15544. ;; No repeater. Do not shift time stamp.
  15545. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15546. (let ((value (string-to-number (match-string 1 start)))
  15547. (type (match-string 2 start)))
  15548. (if (= 0 value)
  15549. ;; Repeater with a 0-value is considered as void.
  15550. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15551. (let* ((base (org-date-to-gregorian start))
  15552. (target (org-date-to-gregorian current))
  15553. (sday (calendar-absolute-from-gregorian base))
  15554. (cday (calendar-absolute-from-gregorian target))
  15555. n1 n2)
  15556. ;; If START is already past CURRENT, just return START.
  15557. (if (<= cday sday) sday
  15558. ;; Compute closest date before (N1) and closest date past
  15559. ;; (N2) CURRENT.
  15560. (pcase type
  15561. ("h"
  15562. (let ((missing-hours
  15563. (mod (+ (- (* 24 (- cday sday))
  15564. (nth 2 (org-parse-time-string start)))
  15565. org-extend-today-until)
  15566. value)))
  15567. (setf n1 (if (= missing-hours 0) cday
  15568. (- cday (1+ (/ missing-hours 24)))))
  15569. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15570. ((or "d" "w")
  15571. (let ((value (if (equal type "w") (* 7 value) value)))
  15572. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15573. (setf n2 (+ n1 value))))
  15574. ("m"
  15575. (let* ((add-months
  15576. (lambda (d n)
  15577. ;; Add N months to gregorian date D, i.e.,
  15578. ;; a list (MONTH DAY YEAR). Return a valid
  15579. ;; gregorian date.
  15580. (let ((m (+ (nth 0 d) n)))
  15581. (list (mod m 12)
  15582. (nth 1 d)
  15583. (+ (/ m 12) (nth 2 d))))))
  15584. (months ; Complete months to TARGET.
  15585. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15586. (- (nth 0 target) (nth 0 base))
  15587. ;; If START's day is greater than
  15588. ;; TARGET's, remove incomplete month.
  15589. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15590. value)
  15591. value))
  15592. (before (funcall add-months base months)))
  15593. (setf n1 (calendar-absolute-from-gregorian before))
  15594. (setf n2
  15595. (calendar-absolute-from-gregorian
  15596. (funcall add-months before value)))))
  15597. (_
  15598. (let* ((d (nth 1 base))
  15599. (m (nth 0 base))
  15600. (y (nth 2 base))
  15601. (years ; Complete years to TARGET.
  15602. (* (/ (- (nth 2 target)
  15603. y
  15604. ;; If START's month and day are
  15605. ;; greater than TARGET's, remove
  15606. ;; incomplete year.
  15607. (if (or (> (nth 0 target) m)
  15608. (and (= (nth 0 target) m)
  15609. (> (nth 1 target) d)))
  15610. 0
  15611. 1))
  15612. value)
  15613. value))
  15614. (before (list m d (+ y years))))
  15615. (setf n1 (calendar-absolute-from-gregorian before))
  15616. (setf n2 (calendar-absolute-from-gregorian
  15617. (list m d (+ (nth 2 before) value)))))))
  15618. ;; Handle PREFER parameter, if any.
  15619. (cond
  15620. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15621. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15622. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15623. (defun org-date-to-gregorian (d)
  15624. "Turn any specification of date D into a Gregorian date for the calendar."
  15625. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15626. ((and (listp d) (= (length d) 3)) d)
  15627. ((stringp d)
  15628. (let ((d (org-parse-time-string d)))
  15629. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15630. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15631. (defun org-parse-time-string (s &optional nodefault)
  15632. "Parse the standard Org time string.
  15633. This should be a lot faster than the normal `parse-time-string'.
  15634. If time is not given, defaults to 0:00. However, with optional
  15635. NODEFAULT, hour and minute fields will be nil if not given."
  15636. (cond ((string-match org-ts-regexp0 s)
  15637. (list 0
  15638. (when (or (match-beginning 8) (not nodefault))
  15639. (string-to-number (or (match-string 8 s) "0")))
  15640. (when (or (match-beginning 7) (not nodefault))
  15641. (string-to-number (or (match-string 7 s) "0")))
  15642. (string-to-number (match-string 4 s))
  15643. (string-to-number (match-string 3 s))
  15644. (string-to-number (match-string 2 s))
  15645. nil nil nil))
  15646. ((string-match "^<[^>]+>$" s)
  15647. ;; FIXME: `decode-time' needs to be called with ZONE as its
  15648. ;; second argument. However, this requires at least Emacs
  15649. ;; 25.1. We can do it when we switch to this version as our
  15650. ;; minimal requirement.
  15651. (decode-time (seconds-to-time (org-matcher-time s))))
  15652. (t (error "Not a standard Org time string: %s" s))))
  15653. (defun org-timestamp-up (&optional arg)
  15654. "Increase the date item at the cursor by one.
  15655. If the cursor is on the year, change the year. If it is on the month,
  15656. the day or the time, change that.
  15657. With prefix ARG, change by that many units."
  15658. (interactive "p")
  15659. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15660. (defun org-timestamp-down (&optional arg)
  15661. "Decrease the date item at the cursor by one.
  15662. If the cursor is on the year, change the year. If it is on the month,
  15663. the day or the time, change that.
  15664. With prefix ARG, change by that many units."
  15665. (interactive "p")
  15666. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15667. (defun org-timestamp-up-day (&optional arg)
  15668. "Increase the date in the time stamp by one day.
  15669. With prefix ARG, change that many days."
  15670. (interactive "p")
  15671. (if (and (not (org-at-timestamp-p 'lax))
  15672. (org-at-heading-p))
  15673. (org-todo 'up)
  15674. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15675. (defun org-timestamp-down-day (&optional arg)
  15676. "Decrease the date in the time stamp by one day.
  15677. With prefix ARG, change that many days."
  15678. (interactive "p")
  15679. (if (and (not (org-at-timestamp-p 'lax))
  15680. (org-at-heading-p))
  15681. (org-todo 'down)
  15682. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15683. (defun org-at-timestamp-p (&optional extended)
  15684. "Non-nil if point is inside a timestamp.
  15685. By default, the function only consider syntactically valid active
  15686. timestamps. However, the caller may have a broader definition
  15687. for timestamps. As a consequence, optional argument EXTENDED can
  15688. be set to the following values
  15689. `inactive'
  15690. Include also syntactically valid inactive timestamps.
  15691. `agenda'
  15692. Include timestamps allowed in Agenda, i.e., those in
  15693. properties drawers, planning lines and clock lines.
  15694. `lax'
  15695. Ignore context. The function matches any part of the
  15696. document looking like a timestamp. This includes comments,
  15697. example blocks...
  15698. For backward-compatibility with Org 9.0, every other non-nil
  15699. value is equivalent to `inactive'.
  15700. When at a timestamp, return the position of the point as a symbol
  15701. among `bracket', `after', `year', `month', `hour', `minute',
  15702. `day' or a number of character from the last know part of the
  15703. time stamp.
  15704. When matching, the match groups are the following:
  15705. group 1: year
  15706. group 2: month
  15707. group 3: day number
  15708. group 4: day name
  15709. group 5: hours, if any
  15710. group 6: minutes, if any"
  15711. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15712. (pos (point))
  15713. (match?
  15714. (let ((boundaries (org-in-regexp regexp)))
  15715. (save-match-data
  15716. (cond ((null boundaries) nil)
  15717. ((eq extended 'lax) t)
  15718. (t
  15719. (or (and (eq extended 'agenda)
  15720. (or (org-at-planning-p)
  15721. (org-at-property-p)
  15722. (and (bound-and-true-p
  15723. org-agenda-include-inactive-timestamps)
  15724. (org-at-clock-log-p))))
  15725. (eq 'timestamp
  15726. (save-excursion
  15727. (when (= pos (cdr boundaries)) (forward-char -1))
  15728. (org-element-type (org-element-context)))))))))))
  15729. (cond
  15730. ((not match?) nil)
  15731. ((= pos (match-beginning 0)) 'bracket)
  15732. ;; Distinguish location right before the closing bracket from
  15733. ;; right after it.
  15734. ((= pos (1- (match-end 0))) 'bracket)
  15735. ((= pos (match-end 0)) 'after)
  15736. ((org-pos-in-match-range pos 2) 'year)
  15737. ((org-pos-in-match-range pos 3) 'month)
  15738. ((org-pos-in-match-range pos 7) 'hour)
  15739. ((org-pos-in-match-range pos 8) 'minute)
  15740. ((or (org-pos-in-match-range pos 4)
  15741. (org-pos-in-match-range pos 5)) 'day)
  15742. ((and (> pos (or (match-end 8) (match-end 5)))
  15743. (< pos (match-end 0)))
  15744. (- pos (or (match-end 8) (match-end 5))))
  15745. (t 'day))))
  15746. (defun org-toggle-timestamp-type ()
  15747. "Toggle the type (<active> or [inactive]) of a time stamp."
  15748. (interactive)
  15749. (when (org-at-timestamp-p 'lax)
  15750. (let ((beg (match-beginning 0)) (end (match-end 0))
  15751. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15752. (save-excursion
  15753. (goto-char beg)
  15754. (while (re-search-forward "[][<>]" end t)
  15755. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15756. t t)))
  15757. (message "Timestamp is now %sactive"
  15758. (if (equal (char-after beg) ?<) "" "in")))))
  15759. (defun org-at-clock-log-p ()
  15760. "Non-nil if point is on a clock log line."
  15761. (and (org-match-line org-clock-line-re)
  15762. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15763. (defvar org-clock-history) ; defined in org-clock.el
  15764. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15765. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15766. "Change the date in the time stamp at point.
  15767. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15768. `year', `minute', `second'. If WHAT is not given, the cursor position
  15769. in the timestamp determines what will be changed.
  15770. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15771. (let ((origin (point))
  15772. (timestamp? (org-at-timestamp-p 'lax))
  15773. origin-cat
  15774. with-hm inactive
  15775. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15776. extra rem
  15777. ts time time0 fixnext clrgx)
  15778. (unless timestamp? (user-error "Not at a timestamp"))
  15779. (if (and (not what) (eq timestamp? 'bracket))
  15780. (org-toggle-timestamp-type)
  15781. ;; Point isn't on brackets. Remember the part of the time-stamp
  15782. ;; the point was in. Indeed, size of time-stamps may change,
  15783. ;; but point must be kept in the same category nonetheless.
  15784. (setq origin-cat timestamp?)
  15785. (when (and (not what) (not (eq timestamp? 'day))
  15786. org-display-custom-times
  15787. (get-text-property (point) 'display)
  15788. (not (get-text-property (1- (point)) 'display)))
  15789. (setq timestamp? 'day))
  15790. (setq timestamp? (or what timestamp?)
  15791. inactive (= (char-after (match-beginning 0)) ?\[)
  15792. ts (match-string 0))
  15793. (replace-match "")
  15794. (when (string-match
  15795. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15796. ts)
  15797. (setq extra (match-string 1 ts))
  15798. (when suppress-tmp-delay
  15799. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15800. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15801. (setq with-hm t))
  15802. (setq time0 (org-parse-time-string ts))
  15803. (when (and updown
  15804. (eq timestamp? 'minute)
  15805. (not current-prefix-arg))
  15806. ;; This looks like s-up and s-down. Change by one rounding step.
  15807. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15808. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15809. (setcar (cdr time0) (+ (nth 1 time0)
  15810. (if (> n 0) (- rem) (- dm rem))))))
  15811. (setq time
  15812. (apply #'encode-time
  15813. (or (car time0) 0)
  15814. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15815. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15816. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15817. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15818. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15819. (nthcdr 6 time0)))
  15820. (when (and (memq timestamp? '(hour minute))
  15821. extra
  15822. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15823. (setq extra (org-modify-ts-extra
  15824. extra
  15825. (if (eq timestamp? 'hour) 2 5)
  15826. n dm)))
  15827. (when (integerp timestamp?)
  15828. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15829. (when (eq what 'calendar)
  15830. (let ((cal-date (org-get-date-from-calendar)))
  15831. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15832. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15833. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15834. (setcar time0 (or (car time0) 0))
  15835. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15836. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15837. (setq time (apply 'encode-time time0))))
  15838. ;; Insert the new time-stamp, and ensure point stays in the same
  15839. ;; category as before (i.e. not after the last position in that
  15840. ;; category).
  15841. (let ((pos (point)))
  15842. ;; Stay before inserted string. `save-excursion' is of no use.
  15843. (setq org-last-changed-timestamp
  15844. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15845. (goto-char pos))
  15846. (save-match-data
  15847. (looking-at org-ts-regexp3)
  15848. (goto-char
  15849. (pcase origin-cat
  15850. ;; `day' category ends before `hour' if any, or at the end
  15851. ;; of the day name.
  15852. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15853. (`hour (min (match-end 7) origin))
  15854. (`minute (min (1- (match-end 8)) origin))
  15855. ((pred integerp) (min (1- (match-end 0)) origin))
  15856. ;; Point was right after the time-stamp. However, the
  15857. ;; time-stamp length might have changed, so refer to
  15858. ;; (match-end 0) instead.
  15859. (`after (match-end 0))
  15860. ;; `year' and `month' have both fixed size: point couldn't
  15861. ;; have moved into another part.
  15862. (_ origin))))
  15863. ;; Update clock if on a CLOCK line.
  15864. (org-clock-update-time-maybe)
  15865. ;; Maybe adjust the closest clock in `org-clock-history'
  15866. (when org-clock-adjust-closest
  15867. (if (not (and (org-at-clock-log-p)
  15868. (< 1 (length (delq nil (mapcar 'marker-position
  15869. org-clock-history))))))
  15870. (message "No clock to adjust")
  15871. (cond ((save-excursion ; fix previous clock?
  15872. (re-search-backward org-ts-regexp0 nil t)
  15873. (looking-back (concat org-clock-string " \\[")
  15874. (line-beginning-position)))
  15875. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15876. ((save-excursion ; fix next clock?
  15877. (re-search-backward org-ts-regexp0 nil t)
  15878. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15879. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15880. (save-window-excursion
  15881. ;; Find closest clock to point, adjust the previous/next one in history
  15882. (let* ((p (save-excursion (org-back-to-heading t)))
  15883. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15884. (clfixnth
  15885. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15886. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15887. (if (not clfixpos)
  15888. (message "No clock to adjust")
  15889. (save-excursion
  15890. (org-goto-marker-or-bmk clfixpos)
  15891. (org-show-subtree)
  15892. (when (re-search-forward clrgx nil t)
  15893. (goto-char (match-beginning 1))
  15894. (let (org-clock-adjust-closest)
  15895. (org-timestamp-change n timestamp? updown))
  15896. (message "Clock adjusted in %s for heading: %s"
  15897. (file-name-nondirectory (buffer-file-name))
  15898. (org-get-heading t t)))))))))
  15899. ;; Try to recenter the calendar window, if any.
  15900. (when (and org-calendar-follow-timestamp-change
  15901. (get-buffer-window "*Calendar*" t)
  15902. (memq timestamp? '(day month year)))
  15903. (org-recenter-calendar (time-to-days time))))))
  15904. (defun org-modify-ts-extra (s pos n dm)
  15905. "Change the different parts of the lead-time and repeat fields in timestamp."
  15906. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15907. ng h m new rem)
  15908. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15909. (cond
  15910. ((or (org-pos-in-match-range pos 2)
  15911. (org-pos-in-match-range pos 3))
  15912. (setq m (string-to-number (match-string 3 s))
  15913. h (string-to-number (match-string 2 s)))
  15914. (if (org-pos-in-match-range pos 2)
  15915. (setq h (+ h n))
  15916. (setq n (* dm (with-no-warnings (signum n))))
  15917. (unless (= 0 (setq rem (% m dm)))
  15918. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15919. (setq m (+ m n)))
  15920. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15921. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15922. (setq h (mod h 24))
  15923. (setq ng 1 new (format "-%02d:%02d" h m)))
  15924. ((org-pos-in-match-range pos 6)
  15925. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15926. ((org-pos-in-match-range pos 5)
  15927. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15928. ((org-pos-in-match-range pos 9)
  15929. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15930. ((org-pos-in-match-range pos 8)
  15931. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15932. (when ng
  15933. (setq s (concat
  15934. (substring s 0 (match-beginning ng))
  15935. new
  15936. (substring s (match-end ng))))))
  15937. s))
  15938. (defun org-recenter-calendar (d)
  15939. "If the calendar is visible, recenter it to date D."
  15940. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15941. (when cwin
  15942. (let ((calendar-move-hook nil))
  15943. (with-selected-window cwin
  15944. (calendar-goto-date
  15945. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15946. (defun org-goto-calendar (&optional arg)
  15947. "Go to the Emacs calendar at the current date.
  15948. If there is a time stamp in the current line, go to that date.
  15949. A prefix ARG can be used to force the current date."
  15950. (interactive "P")
  15951. (let ((calendar-move-hook nil)
  15952. (calendar-view-holidays-initially-flag nil)
  15953. (calendar-view-diary-initially-flag nil)
  15954. diff)
  15955. (when (or (org-at-timestamp-p 'lax)
  15956. (org-match-line (concat ".*" org-ts-regexp)))
  15957. (let ((d1 (time-to-days (current-time)))
  15958. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15959. (setq diff (- d2 d1))))
  15960. (calendar)
  15961. (calendar-goto-today)
  15962. (when (and diff (not arg)) (calendar-forward-day diff))))
  15963. (defun org-get-date-from-calendar ()
  15964. "Return a list (month day year) of date at point in calendar."
  15965. (with-current-buffer "*Calendar*"
  15966. (save-match-data
  15967. (calendar-cursor-to-date))))
  15968. (defun org-date-from-calendar ()
  15969. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15970. If there is already a time stamp at the cursor position, update it."
  15971. (interactive)
  15972. (if (org-at-timestamp-p 'lax)
  15973. (org-timestamp-change 0 'calendar)
  15974. (let ((cal-date (org-get-date-from-calendar)))
  15975. (org-insert-time-stamp
  15976. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15977. (defcustom org-effort-durations
  15978. `(("min" . 1)
  15979. ("h" . 60)
  15980. ("d" . ,(* 60 8))
  15981. ("w" . ,(* 60 8 5))
  15982. ("m" . ,(* 60 8 5 4))
  15983. ("y" . ,(* 60 8 5 40)))
  15984. "Conversion factor to minutes for an effort modifier.
  15985. Each entry has the form (MODIFIER . MINUTES).
  15986. In an effort string, a number followed by MODIFIER is multiplied
  15987. by the specified number of MINUTES to obtain an effort in
  15988. minutes.
  15989. For example, if the value of this variable is ((\"hours\" . 60)), then an
  15990. effort string \"2hours\" is equivalent to 120 minutes."
  15991. :group 'org-agenda
  15992. :version "26.1"
  15993. :package-version '(Org . "8.3")
  15994. :type '(alist :key-type (string :tag "Modifier")
  15995. :value-type (number :tag "Minutes")))
  15996. (defcustom org-image-actual-width t
  15997. "Should we use the actual width of images when inlining them?
  15998. When set to t, always use the image width.
  15999. When set to a number, use imagemagick (when available) to set
  16000. the image's width to this value.
  16001. When set to a number in a list, try to get the width from any
  16002. #+ATTR.* keyword if it matches a width specification like
  16003. #+ATTR_HTML: :width 300px
  16004. and fall back on that number if none is found.
  16005. When set to nil, try to get the width from an #+ATTR.* keyword
  16006. and fall back on the original width if none is found.
  16007. This requires Emacs >= 24.1, build with imagemagick support."
  16008. :group 'org-appearance
  16009. :version "24.4"
  16010. :package-version '(Org . "8.0")
  16011. :type '(choice
  16012. (const :tag "Use the image width" t)
  16013. (integer :tag "Use a number of pixels")
  16014. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16015. (const :tag "Use #+ATTR* or don't resize" nil)))
  16016. (defcustom org-agenda-inhibit-startup nil
  16017. "Inhibit startup when preparing agenda buffers.
  16018. When this variable is t, the initialization of the Org agenda
  16019. buffers is inhibited: e.g. the visibility state is not set, the
  16020. tables are not re-aligned, etc."
  16021. :type 'boolean
  16022. :version "24.3"
  16023. :group 'org-agenda)
  16024. (defcustom org-agenda-ignore-properties nil
  16025. "Avoid updating text properties when building the agenda.
  16026. Properties are used to prepare buffers for effort estimates,
  16027. appointments, statistics and subtree-local categories.
  16028. If you don't use these in the agenda, you can add them to this
  16029. list and agenda building will be a bit faster.
  16030. The value is a list, with zero or more of the symbols `effort', `appt',
  16031. `stats' or `category'."
  16032. :type '(set :greedy t
  16033. (const effort)
  16034. (const appt)
  16035. (const stats)
  16036. (const category))
  16037. :version "26.1"
  16038. :package-version '(Org . "8.3")
  16039. :group 'org-agenda)
  16040. ;;;; Files
  16041. (defun org-save-all-org-buffers ()
  16042. "Save all Org buffers without user confirmation."
  16043. (interactive)
  16044. (message "Saving all Org buffers...")
  16045. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16046. (when (featurep 'org-id) (org-id-locations-save))
  16047. (message "Saving all Org buffers... done"))
  16048. (defun org-revert-all-org-buffers ()
  16049. "Revert all Org buffers.
  16050. Prompt for confirmation when there are unsaved changes.
  16051. Be sure you know what you are doing before letting this function
  16052. overwrite your changes.
  16053. This function is useful in a setup where one tracks Org files
  16054. with a version control system, to revert on one machine after pulling
  16055. changes from another. I believe the procedure must be like this:
  16056. 1. M-x org-save-all-org-buffers
  16057. 2. Pull changes from the other machine, resolve conflicts
  16058. 3. M-x org-revert-all-org-buffers"
  16059. (interactive)
  16060. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16061. (user-error "Abort"))
  16062. (save-excursion
  16063. (save-window-excursion
  16064. (dolist (b (buffer-list))
  16065. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16066. (with-current-buffer b buffer-file-name))
  16067. (pop-to-buffer-same-window b)
  16068. (revert-buffer t 'no-confirm)))
  16069. (when (and (featurep 'org-id) org-id-track-globally)
  16070. (org-id-locations-load)))))
  16071. ;;;; Agenda files
  16072. ;;;###autoload
  16073. (defun org-switchb (&optional arg)
  16074. "Switch between Org buffers.
  16075. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16076. With `\\[universal-argument] \\[universal-argument]' \
  16077. prefix, restrict available buffers to agenda files."
  16078. (interactive "P")
  16079. (let ((blist (org-buffer-list
  16080. (cond ((equal arg '(4)) 'files)
  16081. ((equal arg '(16)) 'agenda)))))
  16082. (pop-to-buffer-same-window
  16083. (completing-read "Org buffer: "
  16084. (mapcar #'list (mapcar #'buffer-name blist))
  16085. nil t))))
  16086. (defun org-buffer-list (&optional predicate exclude-tmp)
  16087. "Return a list of Org buffers.
  16088. PREDICATE can be `export', `files' or `agenda'.
  16089. export restrict the list to Export buffers.
  16090. files restrict the list to buffers visiting Org files.
  16091. agenda restrict the list to buffers visiting agenda files.
  16092. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16093. (let* ((bfn nil)
  16094. (agenda-files (and (eq predicate 'agenda)
  16095. (mapcar 'file-truename (org-agenda-files t))))
  16096. (filter
  16097. (cond
  16098. ((eq predicate 'files)
  16099. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16100. ((eq predicate 'export)
  16101. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16102. ((eq predicate 'agenda)
  16103. (lambda (b)
  16104. (with-current-buffer b
  16105. (and (derived-mode-p 'org-mode)
  16106. (setq bfn (buffer-file-name b))
  16107. (member (file-truename bfn) agenda-files)))))
  16108. (t (lambda (b) (with-current-buffer b
  16109. (or (derived-mode-p 'org-mode)
  16110. (string-match "\\*Org .*Export"
  16111. (buffer-name b)))))))))
  16112. (delq nil
  16113. (mapcar
  16114. (lambda(b)
  16115. (if (and (funcall filter b)
  16116. (or (not exclude-tmp)
  16117. (not (string-match "tmp" (buffer-name b)))))
  16118. b
  16119. nil))
  16120. (buffer-list)))))
  16121. (defun org-agenda-files (&optional unrestricted archives)
  16122. "Get the list of agenda files.
  16123. Optional UNRESTRICTED means return the full list even if a restriction
  16124. is currently in place.
  16125. When ARCHIVES is t, include all archive files that are really being
  16126. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16127. `org-agenda-archives-mode' is t."
  16128. (let ((files
  16129. (cond
  16130. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16131. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16132. ((listp org-agenda-files) org-agenda-files)
  16133. (t (error "Invalid value of `org-agenda-files'")))))
  16134. (setq files (apply 'append
  16135. (mapcar (lambda (f)
  16136. (if (file-directory-p f)
  16137. (directory-files
  16138. f t org-agenda-file-regexp)
  16139. (list f)))
  16140. files)))
  16141. (when org-agenda-skip-unavailable-files
  16142. (setq files (delq nil
  16143. (mapcar (function
  16144. (lambda (file)
  16145. (and (file-readable-p file) file)))
  16146. files))))
  16147. (when (or (eq archives t)
  16148. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16149. (setq files (org-add-archive-files files)))
  16150. files))
  16151. (defun org-agenda-file-p (&optional file)
  16152. "Return non-nil, if FILE is an agenda file.
  16153. If FILE is omitted, use the file associated with the current
  16154. buffer."
  16155. (let ((fname (or file (buffer-file-name))))
  16156. (and fname
  16157. (member (file-truename fname)
  16158. (mapcar #'file-truename (org-agenda-files t))))))
  16159. (defun org-edit-agenda-file-list ()
  16160. "Edit the list of agenda files.
  16161. Depending on setup, this either uses customize to edit the variable
  16162. `org-agenda-files', or it visits the file that is holding the list. In the
  16163. latter case, the buffer is set up in a way that saving it automatically kills
  16164. the buffer and restores the previous window configuration."
  16165. (interactive)
  16166. (if (stringp org-agenda-files)
  16167. (let ((cw (current-window-configuration)))
  16168. (find-file org-agenda-files)
  16169. (setq-local org-window-configuration cw)
  16170. (add-hook 'after-save-hook
  16171. (lambda ()
  16172. (set-window-configuration
  16173. (prog1 org-window-configuration
  16174. (kill-buffer (current-buffer))))
  16175. (org-install-agenda-files-menu)
  16176. (message "New agenda file list installed"))
  16177. nil 'local)
  16178. (message "%s" (substitute-command-keys
  16179. "Edit list and finish with \\[save-buffer]")))
  16180. (customize-variable 'org-agenda-files)))
  16181. (defun org-store-new-agenda-file-list (list)
  16182. "Set new value for the agenda file list and save it correctly."
  16183. (if (stringp org-agenda-files)
  16184. (let ((fe (org-read-agenda-file-list t)) b u)
  16185. (while (setq b (find-buffer-visiting org-agenda-files))
  16186. (kill-buffer b))
  16187. (with-temp-file org-agenda-files
  16188. (insert
  16189. (mapconcat
  16190. (lambda (f) ;; Keep un-expanded entries.
  16191. (if (setq u (assoc f fe))
  16192. (cdr u)
  16193. f))
  16194. list "\n")
  16195. "\n")))
  16196. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16197. (org-insert-mode-line-in-empty-file nil))
  16198. (setq org-agenda-files list)
  16199. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16200. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16201. "Read the list of agenda files from a file.
  16202. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16203. filenames, used by `org-store-new-agenda-file-list' to write back
  16204. un-expanded file names."
  16205. (when (file-directory-p org-agenda-files)
  16206. (error "`org-agenda-files' cannot be a single directory"))
  16207. (when (stringp org-agenda-files)
  16208. (with-temp-buffer
  16209. (insert-file-contents org-agenda-files)
  16210. (mapcar
  16211. (lambda (f)
  16212. (let ((e (expand-file-name (substitute-in-file-name f)
  16213. org-directory)))
  16214. (if pair-with-expansion
  16215. (cons e f)
  16216. e)))
  16217. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16218. ;;;###autoload
  16219. (defun org-cycle-agenda-files ()
  16220. "Cycle through the files in `org-agenda-files'.
  16221. If the current buffer visits an agenda file, find the next one in the list.
  16222. If the current buffer does not, find the first agenda file."
  16223. (interactive)
  16224. (let* ((fs (or (org-agenda-files t)
  16225. (user-error "No agenda files")))
  16226. (files (copy-sequence fs))
  16227. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16228. file)
  16229. (when tcf
  16230. (while (and (setq file (pop files))
  16231. (not (equal (file-truename file) tcf)))))
  16232. (find-file (car (or files fs)))
  16233. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16234. (defun org-agenda-file-to-front (&optional to-end)
  16235. "Move/add the current file to the top of the agenda file list.
  16236. If the file is not present in the list, it is added to the front. If it is
  16237. present, it is moved there. With optional argument TO-END, add/move to the
  16238. end of the list."
  16239. (interactive "P")
  16240. (let ((org-agenda-skip-unavailable-files nil)
  16241. (file-alist (mapcar (lambda (x)
  16242. (cons (file-truename x) x))
  16243. (org-agenda-files t)))
  16244. (ctf (file-truename
  16245. (or buffer-file-name
  16246. (user-error "Please save the current buffer to a file"))))
  16247. x had)
  16248. (setq x (assoc ctf file-alist) had x)
  16249. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16250. (if to-end
  16251. (setq file-alist (append (delq x file-alist) (list x)))
  16252. (setq file-alist (cons x (delq x file-alist))))
  16253. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16254. (org-install-agenda-files-menu)
  16255. (message "File %s to %s of agenda file list"
  16256. (if had "moved" "added") (if to-end "end" "front"))))
  16257. (defun org-remove-file (&optional file)
  16258. "Remove current file from the list of files in variable `org-agenda-files'.
  16259. These are the files which are being checked for agenda entries.
  16260. Optional argument FILE means use this file instead of the current."
  16261. (interactive)
  16262. (let* ((org-agenda-skip-unavailable-files nil)
  16263. (file (or file buffer-file-name
  16264. (user-error "Current buffer does not visit a file")))
  16265. (true-file (file-truename file))
  16266. (afile (abbreviate-file-name file))
  16267. (files (delq nil (mapcar
  16268. (lambda (x)
  16269. (unless (equal true-file
  16270. (file-truename x))
  16271. x))
  16272. (org-agenda-files t)))))
  16273. (if (not (= (length files) (length (org-agenda-files t))))
  16274. (progn
  16275. (org-store-new-agenda-file-list files)
  16276. (org-install-agenda-files-menu)
  16277. (message "Removed from Org Agenda list: %s" afile))
  16278. (message "File was not in list: %s (not removed)" afile))))
  16279. (defun org-file-menu-entry (file)
  16280. (vector file (list 'find-file file) t))
  16281. (defun org-check-agenda-file (file)
  16282. "Make sure FILE exists. If not, ask user what to do."
  16283. (unless (file-exists-p file)
  16284. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16285. (abbreviate-file-name file))
  16286. (let ((r (downcase (read-char-exclusive))))
  16287. (cond
  16288. ((equal r ?r)
  16289. (org-remove-file file)
  16290. (throw 'nextfile t))
  16291. (t (user-error "Abort"))))))
  16292. (defun org-get-agenda-file-buffer (file)
  16293. "Get an agenda buffer visiting FILE.
  16294. If the buffer needs to be created, add it to the list of buffers
  16295. which might be released later."
  16296. (let ((buf (org-find-base-buffer-visiting file)))
  16297. (if buf
  16298. buf ; just return it
  16299. ;; Make a new buffer and remember it
  16300. (setq buf (find-file-noselect file))
  16301. (when buf (push buf org-agenda-new-buffers))
  16302. buf)))
  16303. (defun org-release-buffers (blist)
  16304. "Release all buffers in list, asking the user for confirmation when needed.
  16305. When a buffer is unmodified, it is just killed. When modified, it is saved
  16306. \(if the user agrees) and then killed."
  16307. (let (file)
  16308. (dolist (buf blist)
  16309. (setq file (buffer-file-name buf))
  16310. (when (and (buffer-modified-p buf)
  16311. file
  16312. (y-or-n-p (format "Save file %s? " file)))
  16313. (with-current-buffer buf (save-buffer)))
  16314. (kill-buffer buf))))
  16315. (defun org-agenda-prepare-buffers (files)
  16316. "Create buffers for all agenda files, protect archived trees and comments."
  16317. (interactive)
  16318. (let ((pa '(:org-archived t))
  16319. (pc '(:org-comment t))
  16320. (pall '(:org-archived t :org-comment t))
  16321. (inhibit-read-only t)
  16322. (org-inhibit-startup org-agenda-inhibit-startup)
  16323. (rea (concat ":" org-archive-tag ":"))
  16324. re pos)
  16325. (setq org-tag-alist-for-agenda nil
  16326. org-tag-groups-alist-for-agenda nil)
  16327. (save-excursion
  16328. (save-restriction
  16329. (dolist (file files)
  16330. (catch 'nextfile
  16331. (if (bufferp file)
  16332. (set-buffer file)
  16333. (org-check-agenda-file file)
  16334. (set-buffer (org-get-agenda-file-buffer file)))
  16335. (widen)
  16336. (org-set-regexps-and-options 'tags-only)
  16337. (setq pos (point))
  16338. (or (memq 'category org-agenda-ignore-properties)
  16339. (org-refresh-category-properties))
  16340. (or (memq 'stats org-agenda-ignore-properties)
  16341. (org-refresh-stats-properties))
  16342. (or (memq 'effort org-agenda-ignore-properties)
  16343. (org-refresh-effort-properties))
  16344. (or (memq 'appt org-agenda-ignore-properties)
  16345. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16346. (setq org-todo-keywords-for-agenda
  16347. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16348. (setq org-done-keywords-for-agenda
  16349. (append org-done-keywords-for-agenda org-done-keywords))
  16350. (setq org-todo-keyword-alist-for-agenda
  16351. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16352. (setq org-tag-alist-for-agenda
  16353. (org-uniquify
  16354. (append org-tag-alist-for-agenda
  16355. org-current-tag-alist)))
  16356. ;; Merge current file's tag groups into global
  16357. ;; `org-tag-groups-alist-for-agenda'.
  16358. (when org-group-tags
  16359. (dolist (alist org-tag-groups-alist)
  16360. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16361. (if old
  16362. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16363. (push alist org-tag-groups-alist-for-agenda)))))
  16364. (org-with-silent-modifications
  16365. (save-excursion
  16366. (remove-text-properties (point-min) (point-max) pall)
  16367. (when org-agenda-skip-archived-trees
  16368. (goto-char (point-min))
  16369. (while (re-search-forward rea nil t)
  16370. (when (org-at-heading-p t)
  16371. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16372. (goto-char (point-min))
  16373. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16374. (while (re-search-forward re nil t)
  16375. (when (save-match-data (org-in-commented-heading-p t))
  16376. (add-text-properties
  16377. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16378. (goto-char pos)))))
  16379. (setq org-todo-keywords-for-agenda
  16380. (org-uniquify org-todo-keywords-for-agenda))
  16381. (setq org-todo-keyword-alist-for-agenda
  16382. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16383. ;;;; CDLaTeX minor mode
  16384. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16385. "Keymap for the minor `org-cdlatex-mode'.")
  16386. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16387. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16388. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16389. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16390. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16391. (defvar org-cdlatex-texmathp-advice-is-done nil
  16392. "Flag remembering if we have applied the advice to texmathp already.")
  16393. (define-minor-mode org-cdlatex-mode
  16394. "Toggle the minor `org-cdlatex-mode'.
  16395. This mode supports entering LaTeX environment and math in LaTeX fragments
  16396. in Org mode.
  16397. \\{org-cdlatex-mode-map}"
  16398. nil " OCDL" nil
  16399. (when org-cdlatex-mode
  16400. (require 'cdlatex)
  16401. (run-hooks 'cdlatex-mode-hook)
  16402. (cdlatex-compute-tables))
  16403. (unless org-cdlatex-texmathp-advice-is-done
  16404. (setq org-cdlatex-texmathp-advice-is-done t)
  16405. (defadvice texmathp (around org-math-always-on activate)
  16406. "Always return t in Org buffers.
  16407. This is because we want to insert math symbols without dollars even outside
  16408. the LaTeX math segments. If Org mode thinks that point is actually inside
  16409. an embedded LaTeX fragment, let `texmathp' do its job.
  16410. `\\[org-cdlatex-mode-map]'"
  16411. (interactive)
  16412. (let (p)
  16413. (cond
  16414. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16415. ((eq this-command 'cdlatex-math-symbol)
  16416. (setq ad-return-value t
  16417. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16418. (t
  16419. (let ((p (org-inside-LaTeX-fragment-p)))
  16420. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16421. (setq ad-return-value t
  16422. texmathp-why '("Org mode embedded math" . 0))
  16423. (when p ad-do-it)))))))))
  16424. (defun turn-on-org-cdlatex ()
  16425. "Unconditionally turn on `org-cdlatex-mode'."
  16426. (org-cdlatex-mode 1))
  16427. (defun org-try-cdlatex-tab ()
  16428. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16429. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16430. - inside a LaTeX fragment, or
  16431. - after the first word in a line, where an abbreviation expansion could
  16432. insert a LaTeX environment."
  16433. (when org-cdlatex-mode
  16434. (cond
  16435. ;; Before any word on the line: No expansion possible.
  16436. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16437. ;; Just after first word on the line: Expand it. Make sure it
  16438. ;; cannot happen on headlines, though.
  16439. ((save-excursion
  16440. (skip-chars-backward "a-zA-Z0-9*")
  16441. (skip-chars-backward " \t")
  16442. (and (bolp) (not (org-at-heading-p))))
  16443. (cdlatex-tab) t)
  16444. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16445. (defun org-cdlatex-underscore-caret (&optional _arg)
  16446. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16447. Revert to the normal definition outside of these fragments."
  16448. (interactive "P")
  16449. (if (org-inside-LaTeX-fragment-p)
  16450. (call-interactively 'cdlatex-sub-superscript)
  16451. (let (org-cdlatex-mode)
  16452. (call-interactively (key-binding (vector last-input-event))))))
  16453. (defun org-cdlatex-math-modify (&optional _arg)
  16454. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16455. Revert to the normal definition outside of these fragments."
  16456. (interactive "P")
  16457. (if (org-inside-LaTeX-fragment-p)
  16458. (call-interactively 'cdlatex-math-modify)
  16459. (let (org-cdlatex-mode)
  16460. (call-interactively (key-binding (vector last-input-event))))))
  16461. (defun org-cdlatex-environment-indent (&optional environment item)
  16462. "Execute `cdlatex-environment' and indent the inserted environment.
  16463. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16464. The inserted environment is indented to current indentation
  16465. unless point is at the beginning of the line, in which the
  16466. environment remains unintended."
  16467. (interactive)
  16468. ;; cdlatex-environment always return nil. Therefore, capture output
  16469. ;; first and determine if an environment was selected.
  16470. (let* ((beg (point-marker))
  16471. (end (copy-marker (point) t))
  16472. (inserted (progn
  16473. (ignore-errors (cdlatex-environment environment item))
  16474. (< beg end)))
  16475. ;; Figure out how many lines to move forward after the
  16476. ;; environment has been inserted.
  16477. (lines (when inserted
  16478. (save-excursion
  16479. (- (cl-loop while (< beg (point))
  16480. with x = 0
  16481. do (forward-line -1)
  16482. (cl-incf x)
  16483. finally return x)
  16484. (if (progn (goto-char beg)
  16485. (and (progn (skip-chars-forward " \t") (eolp))
  16486. (progn (skip-chars-backward " \t") (bolp))))
  16487. 1 0)))))
  16488. (env (org-trim (delete-and-extract-region beg end))))
  16489. (when inserted
  16490. ;; Get indentation of next line unless at column 0.
  16491. (let ((ind (if (bolp) 0
  16492. (save-excursion
  16493. (org-return-indent)
  16494. (prog1 (org-get-indentation)
  16495. (when (progn (skip-chars-forward " \t") (eolp))
  16496. (delete-region beg (point)))))))
  16497. (bol (progn (skip-chars-backward " \t") (bolp))))
  16498. ;; Insert a newline before environment unless at column zero
  16499. ;; to "escape" the current line. Insert a newline if
  16500. ;; something is one the same line as \end{ENVIRONMENT}.
  16501. (insert
  16502. (concat (unless bol "\n") env
  16503. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16504. (unless (zerop ind)
  16505. (save-excursion
  16506. (goto-char beg)
  16507. (while (< (point) end)
  16508. (unless (eolp) (indent-line-to ind))
  16509. (forward-line))))
  16510. (goto-char beg)
  16511. (forward-line lines)
  16512. (indent-line-to ind)))
  16513. (set-marker beg nil)
  16514. (set-marker end nil)))
  16515. ;;;; LaTeX fragments
  16516. (defun org-inside-LaTeX-fragment-p ()
  16517. "Test if point is inside a LaTeX fragment.
  16518. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16519. sequence appearing also before point.
  16520. Even though the matchers for math are configurable, this function assumes
  16521. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16522. delimiters are skipped when they have been removed by customization.
  16523. The return value is nil, or a cons cell with the delimiter and the
  16524. position of this delimiter.
  16525. This function does a reasonably good job, but can locally be fooled by
  16526. for example currency specifications. For example it will assume being in
  16527. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16528. fragments that are properly closed, but during editing, we have to live
  16529. with the uncertainty caused by missing closing delimiters. This function
  16530. looks only before point, not after."
  16531. (catch 'exit
  16532. (let ((pos (point))
  16533. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16534. (lim (save-excursion (org-backward-paragraph) (point)))
  16535. dd-on str (start 0) m re)
  16536. (goto-char pos)
  16537. (when dodollar
  16538. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16539. re (nth 1 (assoc "$" org-latex-regexps)))
  16540. (while (string-match re str start)
  16541. (cond
  16542. ((= (match-end 0) (length str))
  16543. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16544. ((= (match-end 0) (- (length str) 5))
  16545. (throw 'exit nil))
  16546. (t (setq start (match-end 0))))))
  16547. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16548. (goto-char pos)
  16549. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16550. (and (match-beginning 2) (throw 'exit nil))
  16551. ;; count $$
  16552. (while (re-search-backward "\\$\\$" lim t)
  16553. (setq dd-on (not dd-on)))
  16554. (goto-char pos)
  16555. (when dd-on (cons "$$" m))))))
  16556. (defun org-inside-latex-macro-p ()
  16557. "Is point inside a LaTeX macro or its arguments?"
  16558. (save-match-data
  16559. (org-in-regexp
  16560. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16561. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16562. "Build an overlay between BEG and END using IMAGE file.
  16563. Argument IMAGETYPE is the extension of the displayed image,
  16564. as a string. It defaults to \"png\"."
  16565. (let ((ov (make-overlay beg end))
  16566. (imagetype (or (intern imagetype) 'png)))
  16567. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16568. (overlay-put ov 'evaporate t)
  16569. (overlay-put ov
  16570. 'modification-hooks
  16571. (list (lambda (o _flag _beg _end &optional _l)
  16572. (delete-overlay o))))
  16573. (overlay-put ov
  16574. 'display
  16575. (list 'image :type imagetype :file image :ascent 'center))))
  16576. (defun org--list-latex-overlays (&optional beg end)
  16577. "List all Org LaTeX overlays in current buffer.
  16578. Limit to overlays between BEG and END when those are provided."
  16579. (cl-remove-if-not
  16580. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16581. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16582. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16583. "Remove all overlays with LaTeX fragment images in current buffer.
  16584. When optional arguments BEG and END are non-nil, remove all
  16585. overlays between them instead. Return a non-nil value when some
  16586. overlays were removed, nil otherwise."
  16587. (let ((overlays (org--list-latex-overlays beg end)))
  16588. (mapc #'delete-overlay overlays)
  16589. overlays))
  16590. (defun org-toggle-latex-fragment (&optional arg)
  16591. "Preview the LaTeX fragment at point, or all locally or globally.
  16592. If the cursor is on a LaTeX fragment, create the image and overlay
  16593. it over the source code, if there is none. Remove it otherwise.
  16594. If there is no fragment at point, display all fragments in the
  16595. current section.
  16596. With prefix ARG, preview or clear image for all fragments in the
  16597. current subtree or in the whole buffer when used before the first
  16598. headline. With a prefix ARG `\\[universal-argument] \
  16599. \\[universal-argument]' preview or clear images
  16600. for all fragments in the buffer."
  16601. (interactive "P")
  16602. (when (display-graphic-p)
  16603. (catch 'exit
  16604. (save-excursion
  16605. (let (beg end msg)
  16606. (cond
  16607. ((or (equal arg '(16))
  16608. (and (equal arg '(4))
  16609. (org-with-limited-levels (org-before-first-heading-p))))
  16610. (if (org-remove-latex-fragment-image-overlays)
  16611. (progn (message "LaTeX fragments images removed from buffer")
  16612. (throw 'exit nil))
  16613. (setq msg "Creating images for buffer...")))
  16614. ((equal arg '(4))
  16615. (org-with-limited-levels (org-back-to-heading t))
  16616. (setq beg (point))
  16617. (setq end (progn (org-end-of-subtree t) (point)))
  16618. (if (org-remove-latex-fragment-image-overlays beg end)
  16619. (progn
  16620. (message "LaTeX fragment images removed from subtree")
  16621. (throw 'exit nil))
  16622. (setq msg "Creating images for subtree...")))
  16623. ((let ((datum (org-element-context)))
  16624. (when (memq (org-element-type datum)
  16625. '(latex-environment latex-fragment))
  16626. (setq beg (org-element-property :begin datum))
  16627. (setq end (org-element-property :end datum))
  16628. (if (org-remove-latex-fragment-image-overlays beg end)
  16629. (progn (message "LaTeX fragment image removed")
  16630. (throw 'exit nil))
  16631. (setq msg "Creating image...")))))
  16632. (t
  16633. (org-with-limited-levels
  16634. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16635. (outline-previous-heading)
  16636. (point)))
  16637. (setq end (progn (outline-next-heading) (point)))
  16638. (if (org-remove-latex-fragment-image-overlays beg end)
  16639. (progn
  16640. (message "LaTeX fragment images removed from section")
  16641. (throw 'exit nil))
  16642. (setq msg "Creating images for section...")))))
  16643. (let ((file (buffer-file-name (buffer-base-buffer))))
  16644. (org-format-latex
  16645. (concat org-preview-latex-image-directory "org-ltximg")
  16646. beg end
  16647. ;; Emacs cannot overlay images from remote hosts. Create
  16648. ;; it in `temporary-file-directory' instead.
  16649. (if (or (not file) (file-remote-p file))
  16650. temporary-file-directory
  16651. default-directory)
  16652. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16653. (message (concat msg "done")))))))
  16654. (defun org-format-latex
  16655. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16656. "Replace LaTeX fragments with links to an image.
  16657. The function takes care of creating the replacement image.
  16658. Only consider fragments between BEG and END when those are
  16659. provided.
  16660. When optional argument OVERLAYS is non-nil, display the image on
  16661. top of the fragment instead of replacing it.
  16662. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16663. Some of the options can be changed using the variable
  16664. `org-format-latex-options', which see."
  16665. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16666. (unless (eq processing-type 'verbatim)
  16667. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16668. (cnt 0)
  16669. checkdir-flag)
  16670. (goto-char (or beg (point-min)))
  16671. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16672. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16673. (overlay-recenter (or end (point-max))))
  16674. (while (re-search-forward math-regexp end t)
  16675. (unless (and overlays
  16676. (eq (get-char-property (point) 'org-overlay-type)
  16677. 'org-latex-overlay))
  16678. (let* ((context (org-element-context))
  16679. (type (org-element-type context)))
  16680. (when (memq type '(latex-environment latex-fragment))
  16681. (let ((block-type (eq type 'latex-environment))
  16682. (value (org-element-property :value context))
  16683. (beg (org-element-property :begin context))
  16684. (end (save-excursion
  16685. (goto-char (org-element-property :end context))
  16686. (skip-chars-backward " \r\t\n")
  16687. (point))))
  16688. (cond
  16689. ((eq processing-type 'mathjax)
  16690. ;; Prepare for MathJax processing.
  16691. (if (not (string-match "\\`\\$\\$?" value))
  16692. (goto-char end)
  16693. (delete-region beg end)
  16694. (if (string= (match-string 0 value) "$$")
  16695. (insert "\\[" (substring value 2 -2) "\\]")
  16696. (insert "\\(" (substring value 1 -1) "\\)"))))
  16697. ((assq processing-type org-preview-latex-process-alist)
  16698. ;; Process to an image.
  16699. (cl-incf cnt)
  16700. (goto-char beg)
  16701. (let* ((processing-info
  16702. (cdr (assq processing-type org-preview-latex-process-alist)))
  16703. (face (face-at-point))
  16704. ;; Get the colors from the face at point.
  16705. (fg
  16706. (let ((color (plist-get org-format-latex-options
  16707. :foreground)))
  16708. (if (and forbuffer (eq color 'auto))
  16709. (face-attribute face :foreground nil 'default)
  16710. color)))
  16711. (bg
  16712. (let ((color (plist-get org-format-latex-options
  16713. :background)))
  16714. (if (and forbuffer (eq color 'auto))
  16715. (face-attribute face :background nil 'default)
  16716. color)))
  16717. (hash (sha1 (prin1-to-string
  16718. (list org-format-latex-header
  16719. org-latex-default-packages-alist
  16720. org-latex-packages-alist
  16721. org-format-latex-options
  16722. forbuffer value fg bg))))
  16723. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16724. (absprefix (expand-file-name prefix dir))
  16725. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16726. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16727. (sep (and block-type "\n\n"))
  16728. (link (concat sep "[[file:" linkfile "]]" sep))
  16729. (options
  16730. (org-combine-plists
  16731. org-format-latex-options
  16732. `(:foreground ,fg :background ,bg))))
  16733. (when msg (message msg cnt))
  16734. (unless checkdir-flag ; Ensure the directory exists.
  16735. (setq checkdir-flag t)
  16736. (let ((todir (file-name-directory absprefix)))
  16737. (unless (file-directory-p todir)
  16738. (make-directory todir t))))
  16739. (unless (file-exists-p movefile)
  16740. (org-create-formula-image
  16741. value movefile options forbuffer processing-type))
  16742. (if overlays
  16743. (progn
  16744. (dolist (o (overlays-in beg end))
  16745. (when (eq (overlay-get o 'org-overlay-type)
  16746. 'org-latex-overlay)
  16747. (delete-overlay o)))
  16748. (org--format-latex-make-overlay beg end movefile imagetype)
  16749. (goto-char end))
  16750. (delete-region beg end)
  16751. (insert
  16752. (org-add-props link
  16753. (list 'org-latex-src
  16754. (replace-regexp-in-string "\"" "" value)
  16755. 'org-latex-src-embed-type
  16756. (if block-type 'paragraph 'character)))))))
  16757. ((eq processing-type 'mathml)
  16758. ;; Process to MathML.
  16759. (unless (org-format-latex-mathml-available-p)
  16760. (user-error "LaTeX to MathML converter not configured"))
  16761. (cl-incf cnt)
  16762. (when msg (message msg cnt))
  16763. (goto-char beg)
  16764. (delete-region beg end)
  16765. (insert (org-format-latex-as-mathml
  16766. value block-type prefix dir)))
  16767. (t
  16768. (error "Unknown conversion process %s for LaTeX fragments"
  16769. processing-type)))))))))))
  16770. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16771. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16772. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16773. sucessful, return the portion between \"<math...> </math>\"
  16774. elements otherwise return nil. When MATHML-FILE is specified,
  16775. write the results in to that file. When invoked as an
  16776. interactive command, prompt for LATEX-FRAG, with initial value
  16777. set to the current active region and echo the results for user
  16778. inspection."
  16779. (interactive (list (let ((frag (when (org-region-active-p)
  16780. (buffer-substring-no-properties
  16781. (region-beginning) (region-end)))))
  16782. (read-string "LaTeX Fragment: " frag nil frag))))
  16783. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16784. (let* ((tmp-in-file
  16785. (let ((file (file-relative-name
  16786. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16787. (write-region latex-frag nil file)
  16788. file))
  16789. (tmp-out-file (file-relative-name
  16790. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16791. (cmd (format-spec
  16792. org-latex-to-mathml-convert-command
  16793. `((?j . ,(and org-latex-to-mathml-jar-file
  16794. (shell-quote-argument
  16795. (expand-file-name
  16796. org-latex-to-mathml-jar-file))))
  16797. (?I . ,(shell-quote-argument tmp-in-file))
  16798. (?i . ,latex-frag)
  16799. (?o . ,(shell-quote-argument tmp-out-file)))))
  16800. mathml shell-command-output)
  16801. (when (called-interactively-p 'any)
  16802. (unless (org-format-latex-mathml-available-p)
  16803. (user-error "LaTeX to MathML converter not configured")))
  16804. (message "Running %s" cmd)
  16805. (setq shell-command-output (shell-command-to-string cmd))
  16806. (setq mathml
  16807. (when (file-readable-p tmp-out-file)
  16808. (with-current-buffer (find-file-noselect tmp-out-file t)
  16809. (goto-char (point-min))
  16810. (when (re-search-forward
  16811. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16812. (regexp-quote
  16813. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16814. nil t)
  16815. (prog1 (match-string 0) (kill-buffer))))))
  16816. (cond
  16817. (mathml
  16818. (setq mathml
  16819. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16820. (when mathml-file
  16821. (write-region mathml nil mathml-file))
  16822. (when (called-interactively-p 'any)
  16823. (message mathml)))
  16824. ((message "LaTeX to MathML conversion failed")
  16825. (message shell-command-output)))
  16826. (delete-file tmp-in-file)
  16827. (when (file-exists-p tmp-out-file)
  16828. (delete-file tmp-out-file))
  16829. mathml))
  16830. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16831. prefix &optional dir)
  16832. "Use `org-create-math-formula' but check local cache first."
  16833. (let* ((absprefix (expand-file-name prefix dir))
  16834. (print-length nil) (print-level nil)
  16835. (formula-id (concat
  16836. "formula-"
  16837. (sha1
  16838. (prin1-to-string
  16839. (list latex-frag
  16840. org-latex-to-mathml-convert-command)))))
  16841. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16842. (formula-cache-dir (file-name-directory formula-cache)))
  16843. (unless (file-directory-p formula-cache-dir)
  16844. (make-directory formula-cache-dir t))
  16845. (unless (file-exists-p formula-cache)
  16846. (org-create-math-formula latex-frag formula-cache))
  16847. (if (file-exists-p formula-cache)
  16848. ;; Successful conversion. Return the link to MathML file.
  16849. (org-add-props
  16850. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16851. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16852. 'org-latex-src-embed-type (if latex-frag-type
  16853. 'paragraph 'character)))
  16854. ;; Failed conversion. Return the LaTeX fragment verbatim
  16855. latex-frag)))
  16856. (defun org--get-display-dpi ()
  16857. "Get the DPI of the display.
  16858. The function assumes that the display has the same pixel width in
  16859. the horizontal and vertical directions."
  16860. (if (display-graphic-p)
  16861. (round (/ (display-pixel-height)
  16862. (/ (display-mm-height) 25.4)))
  16863. (error "Attempt to calculate the dpi of a non-graphic display")))
  16864. (defun org-create-formula-image
  16865. (string tofile options buffer &optional processing-type)
  16866. "Create an image from LaTeX source using external processes.
  16867. The LaTeX STRING is saved to a temporary LaTeX file, then
  16868. converted to an image file by process PROCESSING-TYPE defined in
  16869. `org-preview-latex-process-alist'. A nil value defaults to
  16870. `org-preview-latex-default-process'.
  16871. The generated image file is eventually moved to TOFILE.
  16872. The OPTIONS argument controls the size, foreground color and
  16873. background color of the generated image.
  16874. When BUFFER non-nil, this function is used for LaTeX previewing.
  16875. Otherwise, it is used to deal with LaTeX snippets showed in
  16876. a HTML file."
  16877. (let* ((processing-type (or processing-type
  16878. org-preview-latex-default-process))
  16879. (processing-info
  16880. (cdr (assq processing-type org-preview-latex-process-alist)))
  16881. (programs (plist-get processing-info :programs))
  16882. (error-message (or (plist-get processing-info :message) ""))
  16883. (use-xcolor (plist-get processing-info :use-xcolor))
  16884. (image-input-type (plist-get processing-info :image-input-type))
  16885. (image-output-type (plist-get processing-info :image-output-type))
  16886. (post-clean (or (plist-get processing-info :post-clean)
  16887. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16888. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16889. (latex-header
  16890. (or (plist-get processing-info :latex-header)
  16891. (org-latex-make-preamble
  16892. (org-export-get-environment (org-export-get-backend 'latex))
  16893. org-format-latex-header
  16894. 'snippet)))
  16895. (latex-compiler (plist-get processing-info :latex-compiler))
  16896. (image-converter (plist-get processing-info :image-converter))
  16897. (tmpdir temporary-file-directory)
  16898. (texfilebase (make-temp-name
  16899. (expand-file-name "orgtex" tmpdir)))
  16900. (texfile (concat texfilebase ".tex"))
  16901. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16902. '(1.0 . 1.0)))
  16903. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16904. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16905. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16906. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16907. "Black"))
  16908. (bg (or (plist-get options (if buffer :background :html-background))
  16909. "Transparent"))
  16910. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16911. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16912. (dolist (program programs)
  16913. (org-check-external-command program error-message))
  16914. (if use-xcolor
  16915. (progn (if (eq fg 'default)
  16916. (setq fg (org-latex-color :foreground))
  16917. (setq fg (org-latex-color-format fg)))
  16918. (if (eq bg 'default)
  16919. (setq bg (org-latex-color :background))
  16920. (setq bg (org-latex-color-format
  16921. (if (string= bg "Transparent") "white" bg))))
  16922. (with-temp-file texfile
  16923. (insert latex-header)
  16924. (insert "\n\\begin{document}\n"
  16925. "\\definecolor{fg}{rgb}{" fg "}\n"
  16926. "\\definecolor{bg}{rgb}{" bg "}\n"
  16927. "\n\\pagecolor{bg}\n"
  16928. "\n{\\color{fg}\n"
  16929. string
  16930. "\n}\n"
  16931. "\n\\end{document}\n")))
  16932. (if (eq fg 'default)
  16933. (setq fg (org-dvipng-color :foreground))
  16934. (unless (string= fg "Transparent")
  16935. (setq fg (org-dvipng-color-format fg))))
  16936. (if (eq bg 'default)
  16937. (setq bg (org-dvipng-color :background))
  16938. (unless (string= bg "Transparent")
  16939. (setq bg (org-dvipng-color-format bg))))
  16940. (with-temp-file texfile
  16941. (insert latex-header)
  16942. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16943. (let* ((err-msg (format "Please adjust `%s' part of \
  16944. `org-preview-latex-process-alist'."
  16945. processing-type))
  16946. (image-input-file
  16947. (org-compile-file
  16948. texfile latex-compiler image-input-type err-msg log-buf))
  16949. (image-output-file
  16950. (org-compile-file
  16951. image-input-file image-converter image-output-type err-msg log-buf
  16952. `((?F . ,(shell-quote-argument fg))
  16953. (?B . ,(shell-quote-argument bg))
  16954. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16955. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16956. (copy-file image-output-file tofile 'replace)
  16957. (dolist (e post-clean)
  16958. (when (file-exists-p (concat texfilebase e))
  16959. (delete-file (concat texfilebase e))))
  16960. image-output-file)))
  16961. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16962. "Fill a LaTeX header template TPL.
  16963. In the template, the following place holders will be recognized:
  16964. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16965. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16966. [PACKAGES] \\usepackage statements for PKG
  16967. [NO-PACKAGES] do not include PKG
  16968. [EXTRA] the string EXTRA
  16969. [NO-EXTRA] do not include EXTRA
  16970. For backward compatibility, if both the positive and the negative place
  16971. holder is missing, the positive one (without the \"NO-\") will be
  16972. assumed to be present at the end of the template.
  16973. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16974. EXTRA is a string.
  16975. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16976. (let (rpl (end ""))
  16977. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16978. (setq rpl (if (or (match-end 1) (not def-pkg))
  16979. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16980. tpl (replace-match rpl t t tpl))
  16981. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16982. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16983. (setq rpl (if (or (match-end 1) (not pkg))
  16984. "" (org-latex-packages-to-string pkg snippets-p t))
  16985. tpl (replace-match rpl t t tpl))
  16986. (when pkg (setq end
  16987. (concat end "\n"
  16988. (org-latex-packages-to-string pkg snippets-p)))))
  16989. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16990. (setq rpl (if (or (match-end 1) (not extra))
  16991. "" (concat extra "\n"))
  16992. tpl (replace-match rpl t t tpl))
  16993. (when (and extra (string-match "\\S-" extra))
  16994. (setq end (concat end "\n" extra))))
  16995. (if (string-match "\\S-" end)
  16996. (concat tpl "\n" end)
  16997. tpl)))
  16998. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  16999. "Turn an alist of packages into a string with the \\usepackage macros."
  17000. (setq pkg (mapconcat (lambda(p)
  17001. (cond
  17002. ((stringp p) p)
  17003. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17004. (format "%% Package %s omitted" (cadr p)))
  17005. ((equal "" (car p))
  17006. (format "\\usepackage{%s}" (cadr p)))
  17007. (t
  17008. (format "\\usepackage[%s]{%s}"
  17009. (car p) (cadr p)))))
  17010. pkg
  17011. "\n"))
  17012. (if newline (concat pkg "\n") pkg))
  17013. (defun org-dvipng-color (attr)
  17014. "Return a RGB color specification for dvipng."
  17015. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17016. (defun org-dvipng-color-format (color-name)
  17017. "Convert COLOR-NAME to a RGB color value for dvipng."
  17018. (apply #'format "rgb %s %s %s"
  17019. (mapcar 'org-normalize-color
  17020. (color-values color-name))))
  17021. (defun org-latex-color (attr)
  17022. "Return a RGB color for the LaTeX color package."
  17023. (org-latex-color-format (face-attribute 'default attr nil)))
  17024. (defun org-latex-color-format (color-name)
  17025. "Convert COLOR-NAME to a RGB color value."
  17026. (apply #'format "%s,%s,%s"
  17027. (mapcar 'org-normalize-color
  17028. (color-values color-name))))
  17029. (defun org-normalize-color (value)
  17030. "Return string to be used as color value for an RGB component."
  17031. (format "%g" (/ value 65535.0)))
  17032. ;; Image display
  17033. (defvar-local org-inline-image-overlays nil)
  17034. (defun org-toggle-inline-images (&optional include-linked)
  17035. "Toggle the display of inline images.
  17036. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17037. (interactive "P")
  17038. (if org-inline-image-overlays
  17039. (progn
  17040. (org-remove-inline-images)
  17041. (when (called-interactively-p 'interactive)
  17042. (message "Inline image display turned off")))
  17043. (org-display-inline-images include-linked)
  17044. (when (called-interactively-p 'interactive)
  17045. (message (if org-inline-image-overlays
  17046. (format "%d images displayed inline"
  17047. (length org-inline-image-overlays))
  17048. "No images to display inline")))))
  17049. (defun org-redisplay-inline-images ()
  17050. "Refresh the display of inline images."
  17051. (interactive)
  17052. (if (not org-inline-image-overlays)
  17053. (org-toggle-inline-images)
  17054. (org-toggle-inline-images)
  17055. (org-toggle-inline-images)))
  17056. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17057. "Display inline images.
  17058. An inline image is a link which follows either of these
  17059. conventions:
  17060. 1. Its path is a file with an extension matching return value
  17061. from `image-file-name-regexp' and it has no contents.
  17062. 2. Its description consists in a single link of the previous
  17063. type.
  17064. When optional argument INCLUDE-LINKED is non-nil, also links with
  17065. a text description part will be inlined. This can be nice for
  17066. a quick look at those images, but it does not reflect what
  17067. exported files will look like.
  17068. When optional argument REFRESH is non-nil, refresh existing
  17069. images between BEG and END. This will create new image displays
  17070. only if necessary. BEG and END default to the buffer
  17071. boundaries."
  17072. (interactive "P")
  17073. (when (display-graphic-p)
  17074. (unless refresh
  17075. (org-remove-inline-images)
  17076. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17077. (org-with-wide-buffer
  17078. (goto-char (or beg (point-min)))
  17079. (let* ((case-fold-search t)
  17080. (file-extension-re (image-file-name-regexp))
  17081. (link-abbrevs (mapcar #'car
  17082. (append org-link-abbrev-alist-local
  17083. org-link-abbrev-alist)))
  17084. ;; Check absolute, relative file names and explicit
  17085. ;; "file:" links. Also check link abbreviations since
  17086. ;; some might expand to "file" links.
  17087. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17088. (if (not link-abbrevs) ""
  17089. (format "\\|\\(?:%s:\\)"
  17090. (regexp-opt link-abbrevs))))))
  17091. (while (re-search-forward file-types-re end t)
  17092. (let ((link (save-match-data (org-element-context))))
  17093. ;; Check if we're at an inline image, i.e., an image file
  17094. ;; link without a description (unless INCLUDE-LINKED is
  17095. ;; non-nil).
  17096. (when (and (equal "file" (org-element-property :type link))
  17097. (or include-linked
  17098. (null (org-element-contents link)))
  17099. (string-match-p file-extension-re
  17100. (org-element-property :path link)))
  17101. (let ((file (expand-file-name
  17102. (org-link-unescape
  17103. (org-element-property :path link)))))
  17104. (when (file-exists-p file)
  17105. (let ((width
  17106. ;; Apply `org-image-actual-width' specifications.
  17107. (cond
  17108. ((not (image-type-available-p 'imagemagick)) nil)
  17109. ((eq org-image-actual-width t) nil)
  17110. ((listp org-image-actual-width)
  17111. (or
  17112. ;; First try to find a width among
  17113. ;; attributes associated to the paragraph
  17114. ;; containing link.
  17115. (let ((paragraph
  17116. (let ((e link))
  17117. (while (and (setq e (org-element-property
  17118. :parent e))
  17119. (not (eq (org-element-type e)
  17120. 'paragraph))))
  17121. e)))
  17122. (when paragraph
  17123. (save-excursion
  17124. (goto-char (org-element-property :begin paragraph))
  17125. (when
  17126. (re-search-forward
  17127. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17128. (org-element-property
  17129. :post-affiliated paragraph)
  17130. t)
  17131. (string-to-number (match-string 1))))))
  17132. ;; Otherwise, fall-back to provided number.
  17133. (car org-image-actual-width)))
  17134. ((numberp org-image-actual-width)
  17135. org-image-actual-width)))
  17136. (old (get-char-property-and-overlay
  17137. (org-element-property :begin link)
  17138. 'org-image-overlay)))
  17139. (if (and (car-safe old) refresh)
  17140. (image-refresh (overlay-get (cdr old) 'display))
  17141. (let ((image (create-image file
  17142. (and width 'imagemagick)
  17143. nil
  17144. :width width)))
  17145. (when image
  17146. (let ((ov (make-overlay
  17147. (org-element-property :begin link)
  17148. (progn
  17149. (goto-char
  17150. (org-element-property :end link))
  17151. (skip-chars-backward " \t")
  17152. (point)))))
  17153. (overlay-put ov 'display image)
  17154. (overlay-put ov 'face 'default)
  17155. (overlay-put ov 'org-image-overlay t)
  17156. (overlay-put
  17157. ov 'modification-hooks
  17158. (list 'org-display-inline-remove-overlay))
  17159. (push ov org-inline-image-overlays)))))))))))))))
  17160. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17161. "Remove inline-display overlay if a corresponding region is modified."
  17162. (let ((inhibit-modification-hooks t))
  17163. (when (and ov after)
  17164. (delete ov org-inline-image-overlays)
  17165. (delete-overlay ov))))
  17166. (defun org-remove-inline-images ()
  17167. "Remove inline display of images."
  17168. (interactive)
  17169. (mapc #'delete-overlay org-inline-image-overlays)
  17170. (setq org-inline-image-overlays nil))
  17171. ;;; Key bindings
  17172. (defun org-remap (map &rest commands)
  17173. "In MAP, remap the functions given in COMMANDS.
  17174. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17175. (let (new old)
  17176. (while commands
  17177. (setq old (pop commands) new (pop commands))
  17178. (org-defkey map (vector 'remap old) new))))
  17179. ;;;; Outline functions that can be remapped in Org
  17180. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17181. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17182. (define-key org-mode-map [remap outline-forward-same-level]
  17183. #'org-forward-heading-same-level)
  17184. (define-key org-mode-map [remap outline-backward-same-level]
  17185. #'org-backward-heading-same-level)
  17186. (define-key org-mode-map [remap outline-show-branches]
  17187. #'org-kill-note-or-show-branches)
  17188. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17189. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17190. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17191. (define-key org-mode-map [remap outline-next-visible-heading]
  17192. #'org-next-visible-heading)
  17193. (define-key org-mode-map [remap outline-previous-visible-heading]
  17194. #'org-previous-visible-heading)
  17195. (define-key org-mode-map [remap show-children] #'org-show-children)
  17196. ;;;; Make `C-c C-x' a prefix key
  17197. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17198. ;;;; TAB key with modifiers
  17199. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17200. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17201. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17202. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17203. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17204. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17205. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17206. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17207. ;;;; RET key with modifiers
  17208. (org-defkey org-mode-map (kbd "S-RET") #'org-table-copy-down)
  17209. (org-defkey org-mode-map (kbd "M-S-RET") #'org-insert-todo-heading)
  17210. (org-defkey org-mode-map (kbd "ESC S-RET") #'org-insert-todo-heading)
  17211. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17212. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17213. ;;;; Cursor keys with modifiers
  17214. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17215. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17216. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17217. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17218. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17219. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17220. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17221. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17222. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17223. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17224. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17225. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17226. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17227. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17228. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17229. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17230. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17231. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17232. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17233. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17234. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17235. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17236. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17237. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17238. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17239. ;;;; Babel keys
  17240. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17241. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17242. (define-key org-babel-map key def))
  17243. ;;;; Extra keys for TTY access.
  17244. ;; We only set them when really needed because otherwise the
  17245. ;; menus don't show the simple keys
  17246. (when (or org-use-extra-keys (not window-system))
  17247. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17248. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17249. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17250. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17251. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17252. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17253. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17254. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17255. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17256. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17257. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17258. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17259. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17260. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17261. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17262. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17263. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17264. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17265. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17266. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17267. ;;;; Narrow map
  17268. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17269. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17270. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17271. ;;;; Remap usual Emacs bindings
  17272. (org-remap org-mode-map
  17273. 'self-insert-command 'org-self-insert-command
  17274. 'delete-char 'org-delete-char
  17275. 'delete-backward-char 'org-delete-backward-char
  17276. 'open-line 'org-open-line
  17277. 'comment-dwim 'org-comment-dwim
  17278. 'forward-paragraph 'org-forward-paragraph
  17279. 'backward-paragraph 'org-backward-paragraph
  17280. 'delete-indentation 'org-delete-indentation)
  17281. ;;;; All the other keys
  17282. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17283. (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
  17284. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17285. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17286. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17287. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17288. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17289. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17290. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17291. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17292. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17293. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17294. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17295. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17296. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17297. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17298. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17299. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17300. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17301. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17302. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17303. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17304. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17305. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17306. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17307. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17308. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17309. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17310. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17311. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17312. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17313. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17314. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17315. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17316. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17317. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17318. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17319. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17320. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17321. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17322. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17323. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17324. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17325. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17326. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17327. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17328. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17329. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17330. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17331. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17332. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17333. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17334. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17335. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17336. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17337. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17338. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17339. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17340. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17341. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17342. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17343. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17344. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17345. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17346. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17347. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17348. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17349. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17350. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17351. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17352. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17353. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17354. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17355. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17356. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17357. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17358. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17359. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17360. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17361. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17362. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17363. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17364. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17365. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17366. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17367. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17368. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17369. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17370. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17371. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17372. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17373. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17374. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17375. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17376. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17377. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17378. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17379. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17380. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17381. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17382. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17383. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17384. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17385. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17386. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17387. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17388. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17389. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17390. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17391. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17392. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17393. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17394. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17395. (org-defkey org-mode-map (kbd "C-c C-x w") #'org-insert-structure-template)
  17396. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17397. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17398. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17399. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17400. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17401. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17402. (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17403. (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
  17404. (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17405. (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17406. (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17407. ;;; Speed commands
  17408. (defconst org-speed-commands-default
  17409. '(
  17410. ("Outline Navigation")
  17411. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17412. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17413. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17414. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17415. ("F" . org-next-block)
  17416. ("B" . org-previous-block)
  17417. ("u" . (org-speed-move-safe 'outline-up-heading))
  17418. ("j" . org-goto)
  17419. ("g" . (org-refile t))
  17420. ("Outline Visibility")
  17421. ("c" . org-cycle)
  17422. ("C" . org-shifttab)
  17423. (" " . org-display-outline-path)
  17424. ("s" . org-narrow-to-subtree)
  17425. ("=" . org-columns)
  17426. ("Outline Structure Editing")
  17427. ("U" . org-metaup)
  17428. ("D" . org-metadown)
  17429. ("r" . org-metaright)
  17430. ("l" . org-metaleft)
  17431. ("R" . org-shiftmetaright)
  17432. ("L" . org-shiftmetaleft)
  17433. ("i" . (progn (forward-char 1) (call-interactively
  17434. 'org-insert-heading-respect-content)))
  17435. ("^" . org-sort)
  17436. ("w" . org-refile)
  17437. ("a" . org-archive-subtree-default-with-confirmation)
  17438. ("@" . org-mark-subtree)
  17439. ("#" . org-toggle-comment)
  17440. ("Clock Commands")
  17441. ("I" . org-clock-in)
  17442. ("O" . org-clock-out)
  17443. ("Meta Data Editing")
  17444. ("t" . org-todo)
  17445. ("," . (org-priority))
  17446. ("0" . (org-priority ?\ ))
  17447. ("1" . (org-priority ?A))
  17448. ("2" . (org-priority ?B))
  17449. ("3" . (org-priority ?C))
  17450. (":" . org-set-tags-command)
  17451. ("e" . org-set-effort)
  17452. ("E" . org-inc-effort)
  17453. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17454. (org-entry-put (point) "APPT_WARNTIME" m)))
  17455. ("Agenda Views etc")
  17456. ("v" . org-agenda)
  17457. ("/" . org-sparse-tree)
  17458. ("Misc")
  17459. ("o" . org-open-at-point)
  17460. ("?" . org-speed-command-help)
  17461. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17462. (">" . (org-agenda-remove-restriction-lock))
  17463. )
  17464. "The default speed commands.")
  17465. (defun org-print-speed-command (e)
  17466. (if (> (length (car e)) 1)
  17467. (progn
  17468. (princ "\n")
  17469. (princ (car e))
  17470. (princ "\n")
  17471. (princ (make-string (length (car e)) ?-))
  17472. (princ "\n"))
  17473. (princ (car e))
  17474. (princ " ")
  17475. (if (symbolp (cdr e))
  17476. (princ (symbol-name (cdr e)))
  17477. (prin1 (cdr e)))
  17478. (princ "\n")))
  17479. (defun org-speed-command-help ()
  17480. "Show the available speed commands."
  17481. (interactive)
  17482. (if (not org-use-speed-commands)
  17483. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17484. (with-output-to-temp-buffer "*Help*"
  17485. (princ "User-defined Speed commands\n===========================\n")
  17486. (mapc #'org-print-speed-command org-speed-commands-user)
  17487. (princ "\n")
  17488. (princ "Built-in Speed commands\n=======================\n")
  17489. (mapc #'org-print-speed-command org-speed-commands-default))
  17490. (with-current-buffer "*Help*"
  17491. (setq truncate-lines t))))
  17492. (defun org-speed-move-safe (cmd)
  17493. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17494. If not, return to the original position and throw an error."
  17495. (interactive)
  17496. (let ((pos (point)))
  17497. (call-interactively cmd)
  17498. (unless (and (bolp) (org-at-heading-p))
  17499. (goto-char pos)
  17500. (error "Boundary reached while executing %s" cmd))))
  17501. (defvar org-self-insert-command-undo-counter 0)
  17502. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17503. (defvar org-speed-command nil)
  17504. (defun org-speed-command-activate (keys)
  17505. "Hook for activating single-letter speed commands.
  17506. `org-speed-commands-default' specifies a minimal command set.
  17507. Use `org-speed-commands-user' for further customization."
  17508. (when (or (and (bolp) (looking-at org-outline-regexp))
  17509. (and (functionp org-use-speed-commands)
  17510. (funcall org-use-speed-commands)))
  17511. (cdr (assoc keys (append org-speed-commands-user
  17512. org-speed-commands-default)))))
  17513. (defun org-babel-speed-command-activate (keys)
  17514. "Hook for activating single-letter code block commands."
  17515. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17516. (cdr (assoc keys org-babel-key-bindings))))
  17517. (defcustom org-speed-command-hook
  17518. '(org-speed-command-activate org-babel-speed-command-activate)
  17519. "Hook for activating speed commands at strategic locations.
  17520. Hook functions are called in sequence until a valid handler is
  17521. found.
  17522. Each hook takes a single argument, a user-pressed command key
  17523. which is also a `self-insert-command' from the global map.
  17524. Within the hook, examine the cursor position and the command key
  17525. and return nil or a valid handler as appropriate. Handler could
  17526. be one of an interactive command, a function, or a form.
  17527. Set `org-use-speed-commands' to non-nil value to enable this
  17528. hook. The default setting is `org-speed-command-activate'."
  17529. :group 'org-structure
  17530. :version "24.1"
  17531. :type 'hook)
  17532. (defun org-self-insert-command (N)
  17533. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17534. If the cursor is in a table looking at whitespace, the whitespace is
  17535. overwritten, and the table is not marked as requiring realignment."
  17536. (interactive "p")
  17537. (org-check-before-invisible-edit 'insert)
  17538. (cond
  17539. ((and org-use-speed-commands
  17540. (let ((kv (this-command-keys-vector)))
  17541. (setq org-speed-command
  17542. (run-hook-with-args-until-success
  17543. 'org-speed-command-hook
  17544. (make-string 1 (aref kv (1- (length kv))))))))
  17545. (cond
  17546. ((commandp org-speed-command)
  17547. (setq this-command org-speed-command)
  17548. (call-interactively org-speed-command))
  17549. ((functionp org-speed-command)
  17550. (funcall org-speed-command))
  17551. ((and org-speed-command (listp org-speed-command))
  17552. (eval org-speed-command))
  17553. (t (let (org-use-speed-commands)
  17554. (call-interactively 'org-self-insert-command)))))
  17555. ((and
  17556. (org-at-table-p)
  17557. (eq N 1)
  17558. (not (org-region-active-p))
  17559. (progn
  17560. ;; Check if we blank the field, and if that triggers align.
  17561. (and (featurep 'org-table) org-table-auto-blank-field
  17562. (memq last-command
  17563. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17564. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17565. ;; Got extra space, this field does not determine
  17566. ;; column width.
  17567. (let (org-table-may-need-update) (org-table-blank-field))
  17568. ;; No extra space, this field may determine column
  17569. ;; width.
  17570. (org-table-blank-field)))
  17571. t)
  17572. (looking-at "[^|\n]* \\( \\)|"))
  17573. ;; There is room for insertion without re-aligning the table.
  17574. (delete-region (match-beginning 1) (match-end 1))
  17575. (self-insert-command N))
  17576. (t
  17577. (setq org-table-may-need-update t)
  17578. (self-insert-command N)
  17579. (org-fix-tags-on-the-fly)
  17580. (when org-self-insert-cluster-for-undo
  17581. (if (not (eq last-command 'org-self-insert-command))
  17582. (setq org-self-insert-command-undo-counter 1)
  17583. (if (>= org-self-insert-command-undo-counter 20)
  17584. (setq org-self-insert-command-undo-counter 1)
  17585. (and (> org-self-insert-command-undo-counter 0)
  17586. buffer-undo-list (listp buffer-undo-list)
  17587. (not (cadr buffer-undo-list)) ; remove nil entry
  17588. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17589. (setq org-self-insert-command-undo-counter
  17590. (1+ org-self-insert-command-undo-counter))))))))
  17591. (defun org-check-before-invisible-edit (kind)
  17592. "Check is editing if kind KIND would be dangerous with invisible text around.
  17593. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17594. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17595. (when (and org-catch-invisible-edits
  17596. (or (not (boundp 'visible-mode)) (not visible-mode))
  17597. (or (get-char-property (point) 'invisible)
  17598. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17599. ;; OK, we need to take a closer look. Do not consider
  17600. ;; invisibility obtained through text properties (e.g., link
  17601. ;; fontification), as it cannot be toggled.
  17602. (let* ((invisible-at-point
  17603. (pcase (get-char-property-and-overlay (point) 'invisible)
  17604. (`(,_ . ,(and (pred overlayp) o)) o)))
  17605. ;; Assume that point cannot land in the middle of an
  17606. ;; overlay, or between two overlays.
  17607. (invisible-before-point
  17608. (and (not invisible-at-point)
  17609. (not (bobp))
  17610. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17611. (`(,_ . ,(and (pred overlayp) o)) o))))
  17612. (border-and-ok-direction
  17613. (or
  17614. ;; Check if we are acting predictably before invisible
  17615. ;; text.
  17616. (and invisible-at-point
  17617. (memq kind '(insert delete-backward)))
  17618. ;; Check if we are acting predictably after invisible text
  17619. ;; This works not well, and I have turned it off. It seems
  17620. ;; better to always show and stop after invisible text.
  17621. ;; (and (not invisible-at-point) invisible-before-point
  17622. ;; (memq kind '(insert delete)))
  17623. )))
  17624. (when (or invisible-at-point invisible-before-point)
  17625. (when (eq org-catch-invisible-edits 'error)
  17626. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17627. (if (and org-custom-properties-overlays
  17628. (y-or-n-p "Display invisible properties in this buffer? "))
  17629. (org-toggle-custom-properties-visibility)
  17630. ;; Make the area visible
  17631. (save-excursion
  17632. (when invisible-before-point
  17633. (goto-char
  17634. (previous-single-char-property-change (point) 'invisible)))
  17635. ;; Remove whatever overlay is currently making yet-to-be
  17636. ;; edited text invisible. Also remove nested invisibility
  17637. ;; related overlays.
  17638. (delete-overlay (or invisible-at-point invisible-before-point))
  17639. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17640. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17641. (`(,_ . ,(and (pred overlayp) o))
  17642. (delete-overlay o)
  17643. t)))))
  17644. (cond
  17645. ((eq org-catch-invisible-edits 'show)
  17646. ;; That's it, we do the edit after showing
  17647. (message
  17648. "Unfolding invisible region around point before editing")
  17649. (sit-for 1))
  17650. ((and (eq org-catch-invisible-edits 'smart)
  17651. border-and-ok-direction)
  17652. (message "Unfolding invisible region around point before editing"))
  17653. (t
  17654. ;; Don't do the edit, make the user repeat it in full visibility
  17655. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17656. (defun org-fix-tags-on-the-fly ()
  17657. "Align tags in headline at point.
  17658. Unlike to `org-set-tags', it ignores region and sorting."
  17659. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  17660. (org-at-heading-p))
  17661. (let ((org-ignore-region t)
  17662. (org-tags-sort-function nil))
  17663. (org-set-tags nil t))))
  17664. (defun org-delete-backward-char (N)
  17665. "Like `delete-backward-char', insert whitespace at field end in tables.
  17666. When deleting backwards, in tables this function will insert whitespace in
  17667. front of the next \"|\" separator, to keep the table aligned. The table will
  17668. still be marked for re-alignment if the field did fill the entire column,
  17669. because, in this case the deletion might narrow the column."
  17670. (interactive "p")
  17671. (save-match-data
  17672. (org-check-before-invisible-edit 'delete-backward)
  17673. (if (and (org-at-table-p)
  17674. (eq N 1)
  17675. (not (org-region-active-p))
  17676. (string-match "|" (buffer-substring (point-at-bol) (point)))
  17677. (looking-at ".*?|"))
  17678. (let ((pos (point))
  17679. (noalign (looking-at "[^|\n\r]* |"))
  17680. (c org-table-may-need-update))
  17681. (backward-delete-char N)
  17682. (unless overwrite-mode
  17683. (skip-chars-forward "^|")
  17684. (insert " ")
  17685. (goto-char (1- pos)))
  17686. ;; noalign: if there were two spaces at the end, this field
  17687. ;; does not determine the width of the column.
  17688. (when noalign (setq org-table-may-need-update c)))
  17689. (backward-delete-char N)
  17690. (org-fix-tags-on-the-fly))))
  17691. (defun org-delete-char (N)
  17692. "Like `delete-char', but insert whitespace at field end in tables.
  17693. When deleting characters, in tables this function will insert whitespace in
  17694. front of the next \"|\" separator, to keep the table aligned. The table will
  17695. still be marked for re-alignment if the field did fill the entire column,
  17696. because, in this case the deletion might narrow the column."
  17697. (interactive "p")
  17698. (save-match-data
  17699. (org-check-before-invisible-edit 'delete)
  17700. (if (and (org-at-table-p)
  17701. (not (bolp))
  17702. (not (= (char-after) ?|))
  17703. (eq N 1))
  17704. (if (looking-at ".*?|")
  17705. (let ((pos (point))
  17706. (noalign (looking-at "[^|\n\r]* |"))
  17707. (c org-table-may-need-update))
  17708. (replace-match
  17709. (concat (substring (match-string 0) 1 -1) " |") nil t)
  17710. (goto-char pos)
  17711. ;; noalign: if there were two spaces at the end, this field
  17712. ;; does not determine the width of the column.
  17713. (when noalign (setq org-table-may-need-update c)))
  17714. (delete-char N))
  17715. (delete-char N)
  17716. (org-fix-tags-on-the-fly))))
  17717. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17718. (put 'org-self-insert-command 'delete-selection
  17719. (lambda ()
  17720. (not (run-hook-with-args-until-success
  17721. 'self-insert-uses-region-functions))))
  17722. (put 'orgtbl-self-insert-command 'delete-selection
  17723. (lambda ()
  17724. (not (run-hook-with-args-until-success
  17725. 'self-insert-uses-region-functions))))
  17726. (put 'org-delete-char 'delete-selection 'supersede)
  17727. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17728. (put 'org-yank 'delete-selection 'yank)
  17729. ;; Make `flyspell-mode' delay after some commands
  17730. (put 'org-self-insert-command 'flyspell-delayed t)
  17731. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17732. (put 'org-delete-char 'flyspell-delayed t)
  17733. (put 'org-delete-backward-char 'flyspell-delayed t)
  17734. ;; Make pabbrev-mode expand after Org mode commands
  17735. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17736. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17737. (defun org-transpose-words ()
  17738. "Transpose words for Org.
  17739. This uses the `org-mode-transpose-word-syntax-table' syntax
  17740. table, which interprets characters in `org-emphasis-alist' as
  17741. word constituents."
  17742. (interactive)
  17743. (with-syntax-table org-mode-transpose-word-syntax-table
  17744. (call-interactively 'transpose-words)))
  17745. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  17746. (defvar org-ctrl-c-ctrl-c-hook nil
  17747. "Hook for functions attaching themselves to `C-c C-c'.
  17748. This can be used to add additional functionality to the C-c C-c
  17749. key which executes context-dependent commands. This hook is run
  17750. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17751. run after the last test.
  17752. Each function will be called with no arguments. The function
  17753. must check if the context is appropriate for it to act. If yes,
  17754. it should do its thing and then return a non-nil value. If the
  17755. context is wrong, just do nothing and return nil.")
  17756. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17757. "Hook for functions attaching themselves to `C-c C-c'.
  17758. This can be used to add additional functionality to the C-c C-c
  17759. key which executes context-dependent commands. This hook is run
  17760. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17761. before the first test.
  17762. Each function will be called with no arguments. The function
  17763. must check if the context is appropriate for it to act. If yes,
  17764. it should do its thing and then return a non-nil value. If the
  17765. context is wrong, just do nothing and return nil.")
  17766. (defvar org-tab-first-hook nil
  17767. "Hook for functions to attach themselves to TAB.
  17768. See `org-ctrl-c-ctrl-c-hook' for more information.
  17769. This hook runs as the first action when TAB is pressed, even before
  17770. `org-cycle' messes around with the `outline-regexp' to cater for
  17771. inline tasks and plain list item folding.
  17772. If any function in this hook returns t, any other actions that
  17773. would have been caused by TAB (such as table field motion or visibility
  17774. cycling) will not occur.")
  17775. (defvar org-tab-after-check-for-table-hook nil
  17776. "Hook for functions to attach themselves to TAB.
  17777. See `org-ctrl-c-ctrl-c-hook' for more information.
  17778. This hook runs after it has been established that the cursor is not in a
  17779. table, but before checking if the cursor is in a headline or if global cycling
  17780. should be done.
  17781. If any function in this hook returns t, not other actions like visibility
  17782. cycling will be done.")
  17783. (defvar org-tab-after-check-for-cycling-hook nil
  17784. "Hook for functions to attach themselves to TAB.
  17785. See `org-ctrl-c-ctrl-c-hook' for more information.
  17786. This hook runs after it has been established that not table field motion and
  17787. not visibility should be done because of current context. This is probably
  17788. the place where a package like yasnippets can hook in.")
  17789. (defvar org-tab-before-tab-emulation-hook nil
  17790. "Hook for functions to attach themselves to TAB.
  17791. See `org-ctrl-c-ctrl-c-hook' for more information.
  17792. This hook runs after every other options for TAB have been exhausted, but
  17793. before indentation and \t insertion takes place.")
  17794. (defvar org-metaleft-hook nil
  17795. "Hook for functions attaching themselves to `M-left'.
  17796. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17797. (defvar org-metaright-hook nil
  17798. "Hook for functions attaching themselves to `M-right'.
  17799. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17800. (defvar org-metaup-hook nil
  17801. "Hook for functions attaching themselves to `M-up'.
  17802. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17803. (defvar org-metadown-hook nil
  17804. "Hook for functions attaching themselves to `M-down'.
  17805. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17806. (defvar org-shiftmetaleft-hook nil
  17807. "Hook for functions attaching themselves to `M-S-left'.
  17808. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17809. (defvar org-shiftmetaright-hook nil
  17810. "Hook for functions attaching themselves to `M-S-right'.
  17811. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17812. (defvar org-shiftmetaup-hook nil
  17813. "Hook for functions attaching themselves to `M-S-up'.
  17814. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17815. (defvar org-shiftmetadown-hook nil
  17816. "Hook for functions attaching themselves to `M-S-down'.
  17817. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17818. (defvar org-metareturn-hook nil
  17819. "Hook for functions attaching themselves to `M-RET'.
  17820. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17821. (defvar org-shiftup-hook nil
  17822. "Hook for functions attaching themselves to `S-up'.
  17823. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17824. (defvar org-shiftup-final-hook nil
  17825. "Hook for functions attaching themselves to `S-up'.
  17826. This one runs after all other options except shift-select have been excluded.
  17827. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17828. (defvar org-shiftdown-hook nil
  17829. "Hook for functions attaching themselves to `S-down'.
  17830. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17831. (defvar org-shiftdown-final-hook nil
  17832. "Hook for functions attaching themselves to `S-down'.
  17833. This one runs after all other options except shift-select have been excluded.
  17834. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17835. (defvar org-shiftleft-hook nil
  17836. "Hook for functions attaching themselves to `S-left'.
  17837. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17838. (defvar org-shiftleft-final-hook nil
  17839. "Hook for functions attaching themselves to `S-left'.
  17840. This one runs after all other options except shift-select have been excluded.
  17841. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17842. (defvar org-shiftright-hook nil
  17843. "Hook for functions attaching themselves to `S-right'.
  17844. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17845. (defvar org-shiftright-final-hook nil
  17846. "Hook for functions attaching themselves to `S-right'.
  17847. This one runs after all other options except shift-select have been excluded.
  17848. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17849. (defun org-modifier-cursor-error ()
  17850. "Throw an error, a modified cursor command was applied in wrong context."
  17851. (user-error "This command is active in special context like tables, headlines or items"))
  17852. (defun org-shiftselect-error ()
  17853. "Throw an error because Shift-Cursor command was applied in wrong context."
  17854. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17855. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17856. (user-error "This command works only in special context like headlines or timestamps")))
  17857. (defun org-call-for-shift-select (cmd)
  17858. (let ((this-command-keys-shift-translated t))
  17859. (call-interactively cmd)))
  17860. (defun org-shifttab (&optional arg)
  17861. "Global visibility cycling or move to previous table field.
  17862. Call `org-table-previous-field' within a table.
  17863. When ARG is nil, cycle globally through visibility states.
  17864. When ARG is a numeric prefix, show contents of this level."
  17865. (interactive "P")
  17866. (cond
  17867. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17868. ((integerp arg)
  17869. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17870. (message "Content view to level: %d" arg)
  17871. (org-content (prefix-numeric-value arg2))
  17872. (org-cycle-show-empty-lines t)
  17873. (setq org-cycle-global-status 'overview)))
  17874. (t (call-interactively 'org-global-cycle))))
  17875. (defun org-shiftmetaleft ()
  17876. "Promote subtree or delete table column.
  17877. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17878. `org-table-delete-column', depending on context. See the
  17879. individual commands for more information."
  17880. (interactive)
  17881. (cond
  17882. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17883. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17884. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17885. ((if (not (org-region-active-p)) (org-at-item-p)
  17886. (save-excursion (goto-char (region-beginning))
  17887. (org-at-item-p)))
  17888. (call-interactively 'org-outdent-item-tree))
  17889. (t (org-modifier-cursor-error))))
  17890. (defun org-shiftmetaright ()
  17891. "Demote subtree or insert table column.
  17892. Calls `org-demote-subtree', `org-indent-item-tree', or
  17893. `org-table-insert-column', depending on context. See the
  17894. individual commands for more information."
  17895. (interactive)
  17896. (cond
  17897. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17898. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17899. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17900. ((if (not (org-region-active-p)) (org-at-item-p)
  17901. (save-excursion (goto-char (region-beginning))
  17902. (org-at-item-p)))
  17903. (call-interactively 'org-indent-item-tree))
  17904. (t (org-modifier-cursor-error))))
  17905. (defun org-shiftmetaup (&optional _arg)
  17906. "Drag the line at point up.
  17907. In a table, kill the current row.
  17908. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17909. but also adjust the previous clocked item in the clock history.
  17910. Everywhere else, drag the line at point up."
  17911. (interactive "P")
  17912. (cond
  17913. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17914. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17915. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17916. (call-interactively 'org-timestamp-up)))
  17917. (t (call-interactively 'org-drag-line-backward))))
  17918. (defun org-shiftmetadown (&optional _arg)
  17919. "Drag the line at point down.
  17920. In a table, insert an empty row at the current line.
  17921. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17922. but also adjust the previous clocked item in the clock history.
  17923. Everywhere else, drag the line at point down."
  17924. (interactive "P")
  17925. (cond
  17926. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17927. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17928. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17929. (call-interactively 'org-timestamp-down)))
  17930. (t (call-interactively 'org-drag-line-forward))))
  17931. (defsubst org-hidden-tree-error ()
  17932. (user-error
  17933. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17934. (defun org-metaleft (&optional _arg)
  17935. "Promote heading, list item at point or move table column left.
  17936. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17937. depending on context. With no specific context, calls the Emacs
  17938. default `backward-word'. See the individual commands for more
  17939. information.
  17940. This function runs the hook `org-metaleft-hook' as a first step,
  17941. and returns at first non-nil value."
  17942. (interactive "P")
  17943. (cond
  17944. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17945. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17946. ((org-with-limited-levels
  17947. (or (org-at-heading-p)
  17948. (and (org-region-active-p)
  17949. (save-excursion
  17950. (goto-char (region-beginning))
  17951. (org-at-heading-p)))))
  17952. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17953. (call-interactively 'org-do-promote))
  17954. ;; At an inline task.
  17955. ((org-at-heading-p)
  17956. (call-interactively 'org-inlinetask-promote))
  17957. ((or (org-at-item-p)
  17958. (and (org-region-active-p)
  17959. (save-excursion
  17960. (goto-char (region-beginning))
  17961. (org-at-item-p))))
  17962. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17963. (call-interactively 'org-outdent-item))
  17964. (t (call-interactively 'backward-word))))
  17965. (defun org-metaright (&optional _arg)
  17966. "Demote heading, list item at point or move table column right.
  17967. In front of a drawer or a block keyword, indent it correctly.
  17968. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17969. `org-indent-drawer' or `org-indent-block' depending on context.
  17970. With no specific context, calls the Emacs default `forward-word'.
  17971. See the individual commands for more information.
  17972. This function runs the hook `org-metaright-hook' as a first step,
  17973. and returns at first non-nil value."
  17974. (interactive "P")
  17975. (cond
  17976. ((run-hook-with-args-until-success 'org-metaright-hook))
  17977. ((org-at-table-p) (call-interactively 'org-table-move-column))
  17978. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  17979. ((org-at-block-p) (call-interactively 'org-indent-block))
  17980. ((org-with-limited-levels
  17981. (or (org-at-heading-p)
  17982. (and (org-region-active-p)
  17983. (save-excursion
  17984. (goto-char (region-beginning))
  17985. (org-at-heading-p)))))
  17986. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17987. (call-interactively 'org-do-demote))
  17988. ;; At an inline task.
  17989. ((org-at-heading-p)
  17990. (call-interactively 'org-inlinetask-demote))
  17991. ((or (org-at-item-p)
  17992. (and (org-region-active-p)
  17993. (save-excursion
  17994. (goto-char (region-beginning))
  17995. (org-at-item-p))))
  17996. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17997. (call-interactively 'org-indent-item))
  17998. (t (call-interactively 'forward-word))))
  17999. (defun org-check-for-hidden (what)
  18000. "Check if there are hidden headlines/items in the current visual line.
  18001. WHAT can be either `headlines' or `items'. If the current line is
  18002. an outline or item heading and it has a folded subtree below it,
  18003. this function returns t, nil otherwise."
  18004. (let ((re (cond
  18005. ((eq what 'headlines) org-outline-regexp-bol)
  18006. ((eq what 'items) (org-item-beginning-re))
  18007. (t (error "This should not happen"))))
  18008. beg end)
  18009. (save-excursion
  18010. (catch 'exit
  18011. (unless (org-region-active-p)
  18012. (setq beg (point-at-bol))
  18013. (beginning-of-line 2)
  18014. (while (and (not (eobp)) ;; this is like `next-line'
  18015. (get-char-property (1- (point)) 'invisible))
  18016. (beginning-of-line 2))
  18017. (setq end (point))
  18018. (goto-char beg)
  18019. (goto-char (point-at-eol))
  18020. (setq end (max end (point)))
  18021. (while (re-search-forward re end t)
  18022. (when (get-char-property (match-beginning 0) 'invisible)
  18023. (throw 'exit t))))
  18024. nil))))
  18025. (defun org-metaup (&optional _arg)
  18026. "Move subtree up or move table row up.
  18027. Calls `org-move-subtree-up' or `org-table-move-row' or
  18028. `org-move-item-up', depending on context. See the individual commands
  18029. for more information."
  18030. (interactive "P")
  18031. (cond
  18032. ((run-hook-with-args-until-success 'org-metaup-hook))
  18033. ((org-region-active-p)
  18034. (let* ((a (min (region-beginning) (region-end)))
  18035. (b (1- (max (region-beginning) (region-end))))
  18036. (c (save-excursion (goto-char a)
  18037. (move-beginning-of-line 0)))
  18038. (d (save-excursion (goto-char a)
  18039. (move-end-of-line 0) (point))))
  18040. (transpose-regions a b c d)
  18041. (goto-char c)))
  18042. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18043. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18044. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18045. (t (org-drag-element-backward))))
  18046. (defun org-metadown (&optional _arg)
  18047. "Move subtree down or move table row down.
  18048. Calls `org-move-subtree-down' or `org-table-move-row' or
  18049. `org-move-item-down', depending on context. See the individual
  18050. commands for more information."
  18051. (interactive "P")
  18052. (cond
  18053. ((run-hook-with-args-until-success 'org-metadown-hook))
  18054. ((org-region-active-p)
  18055. (let* ((a (min (region-beginning) (region-end)))
  18056. (b (max (region-beginning) (region-end)))
  18057. (c (save-excursion (goto-char b)
  18058. (move-beginning-of-line 1)))
  18059. (d (save-excursion (goto-char b)
  18060. (move-end-of-line 1) (1+ (point)))))
  18061. (transpose-regions a b c d)
  18062. (goto-char d)))
  18063. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18064. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18065. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18066. (t (org-drag-element-forward))))
  18067. (defun org-shiftup (&optional arg)
  18068. "Increase item in timestamp or increase priority of current headline.
  18069. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18070. depending on context. See the individual commands for more information."
  18071. (interactive "P")
  18072. (cond
  18073. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18074. ((and org-support-shift-select (org-region-active-p))
  18075. (org-call-for-shift-select 'previous-line))
  18076. ((org-at-timestamp-p 'lax)
  18077. (call-interactively (if org-edit-timestamp-down-means-later
  18078. 'org-timestamp-down 'org-timestamp-up)))
  18079. ((and (not (eq org-support-shift-select 'always))
  18080. org-enable-priority-commands
  18081. (org-at-heading-p))
  18082. (call-interactively 'org-priority-up))
  18083. ((and (not org-support-shift-select) (org-at-item-p))
  18084. (call-interactively 'org-previous-item))
  18085. ((org-clocktable-try-shift 'up arg))
  18086. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18087. (org-support-shift-select
  18088. (org-call-for-shift-select 'previous-line))
  18089. (t (org-shiftselect-error))))
  18090. (defun org-shiftdown (&optional arg)
  18091. "Decrease item in timestamp or decrease priority of current headline.
  18092. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18093. depending on context. See the individual commands for more information."
  18094. (interactive "P")
  18095. (cond
  18096. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18097. ((and org-support-shift-select (org-region-active-p))
  18098. (org-call-for-shift-select 'next-line))
  18099. ((org-at-timestamp-p 'lax)
  18100. (call-interactively (if org-edit-timestamp-down-means-later
  18101. 'org-timestamp-up 'org-timestamp-down)))
  18102. ((and (not (eq org-support-shift-select 'always))
  18103. org-enable-priority-commands
  18104. (org-at-heading-p))
  18105. (call-interactively 'org-priority-down))
  18106. ((and (not org-support-shift-select) (org-at-item-p))
  18107. (call-interactively 'org-next-item))
  18108. ((org-clocktable-try-shift 'down arg))
  18109. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18110. (org-support-shift-select
  18111. (org-call-for-shift-select 'next-line))
  18112. (t (org-shiftselect-error))))
  18113. (defun org-shiftright (&optional arg)
  18114. "Cycle the thing at point or in the current line, depending on context.
  18115. Depending on context, this does one of the following:
  18116. - switch a timestamp at point one day into the future
  18117. - on a headline, switch to the next TODO keyword.
  18118. - on an item, switch entire list to the next bullet type
  18119. - on a property line, switch to the next allowed value
  18120. - on a clocktable definition line, move time block into the future"
  18121. (interactive "P")
  18122. (cond
  18123. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18124. ((and org-support-shift-select (org-region-active-p))
  18125. (org-call-for-shift-select 'forward-char))
  18126. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18127. ((and (not (eq org-support-shift-select 'always))
  18128. (org-at-heading-p))
  18129. (let ((org-inhibit-logging
  18130. (not org-treat-S-cursor-todo-selection-as-state-change))
  18131. (org-inhibit-blocking
  18132. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18133. (org-call-with-arg 'org-todo 'right)))
  18134. ((or (and org-support-shift-select
  18135. (not (eq org-support-shift-select 'always))
  18136. (org-at-item-bullet-p))
  18137. (and (not org-support-shift-select) (org-at-item-p)))
  18138. (org-call-with-arg 'org-cycle-list-bullet nil))
  18139. ((and (not (eq org-support-shift-select 'always))
  18140. (org-at-property-p))
  18141. (call-interactively 'org-property-next-allowed-value))
  18142. ((org-clocktable-try-shift 'right arg))
  18143. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18144. (org-support-shift-select
  18145. (org-call-for-shift-select 'forward-char))
  18146. (t (org-shiftselect-error))))
  18147. (defun org-shiftleft (&optional arg)
  18148. "Cycle the thing at point or in the current line, depending on context.
  18149. Depending on context, this does one of the following:
  18150. - switch a timestamp at point one day into the past
  18151. - on a headline, switch to the previous TODO keyword.
  18152. - on an item, switch entire list to the previous bullet type
  18153. - on a property line, switch to the previous allowed value
  18154. - on a clocktable definition line, move time block into the past"
  18155. (interactive "P")
  18156. (cond
  18157. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18158. ((and org-support-shift-select (org-region-active-p))
  18159. (org-call-for-shift-select 'backward-char))
  18160. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18161. ((and (not (eq org-support-shift-select 'always))
  18162. (org-at-heading-p))
  18163. (let ((org-inhibit-logging
  18164. (not org-treat-S-cursor-todo-selection-as-state-change))
  18165. (org-inhibit-blocking
  18166. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18167. (org-call-with-arg 'org-todo 'left)))
  18168. ((or (and org-support-shift-select
  18169. (not (eq org-support-shift-select 'always))
  18170. (org-at-item-bullet-p))
  18171. (and (not org-support-shift-select) (org-at-item-p)))
  18172. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18173. ((and (not (eq org-support-shift-select 'always))
  18174. (org-at-property-p))
  18175. (call-interactively 'org-property-previous-allowed-value))
  18176. ((org-clocktable-try-shift 'left arg))
  18177. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18178. (org-support-shift-select
  18179. (org-call-for-shift-select 'backward-char))
  18180. (t (org-shiftselect-error))))
  18181. (defun org-shiftcontrolright ()
  18182. "Switch to next TODO set."
  18183. (interactive)
  18184. (cond
  18185. ((and org-support-shift-select (org-region-active-p))
  18186. (org-call-for-shift-select 'forward-word))
  18187. ((and (not (eq org-support-shift-select 'always))
  18188. (org-at-heading-p))
  18189. (org-call-with-arg 'org-todo 'nextset))
  18190. (org-support-shift-select
  18191. (org-call-for-shift-select 'forward-word))
  18192. (t (org-shiftselect-error))))
  18193. (defun org-shiftcontrolleft ()
  18194. "Switch to previous TODO set."
  18195. (interactive)
  18196. (cond
  18197. ((and org-support-shift-select (org-region-active-p))
  18198. (org-call-for-shift-select 'backward-word))
  18199. ((and (not (eq org-support-shift-select 'always))
  18200. (org-at-heading-p))
  18201. (org-call-with-arg 'org-todo 'previousset))
  18202. (org-support-shift-select
  18203. (org-call-for-shift-select 'backward-word))
  18204. (t (org-shiftselect-error))))
  18205. (defun org-shiftcontrolup (&optional n)
  18206. "Change timestamps synchronously up in CLOCK log lines.
  18207. Optional argument N tells to change by that many units."
  18208. (interactive "P")
  18209. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18210. (let (org-support-shift-select)
  18211. (org-clock-timestamps-up n))
  18212. (user-error "Not at a clock log")))
  18213. (defun org-shiftcontroldown (&optional n)
  18214. "Change timestamps synchronously down in CLOCK log lines.
  18215. Optional argument N tells to change by that many units."
  18216. (interactive "P")
  18217. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18218. (let (org-support-shift-select)
  18219. (org-clock-timestamps-down n))
  18220. (user-error "Not at a clock log")))
  18221. (defun org-increase-number-at-point (&optional inc)
  18222. "Increment the number at point.
  18223. With an optional prefix numeric argument INC, increment using
  18224. this numeric value."
  18225. (interactive "p")
  18226. (if (not (number-at-point))
  18227. (user-error "Not on a number")
  18228. (unless inc (setq inc 1))
  18229. (let ((pos (point))
  18230. (beg (skip-chars-backward "-+^/*0-9eE."))
  18231. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18232. (setq nap (buffer-substring-no-properties
  18233. (+ pos beg) (+ pos beg end)))
  18234. (delete-region (+ pos beg) (+ pos beg end))
  18235. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18236. (when (org-at-table-p)
  18237. (org-table-align)
  18238. (org-table-end-of-field 1))))
  18239. (defun org-decrease-number-at-point (&optional inc)
  18240. "Decrement the number at point.
  18241. With an optional prefix numeric argument INC, decrement using
  18242. this numeric value."
  18243. (interactive "p")
  18244. (org-increase-number-at-point (- (or inc 1))))
  18245. (defun org-ctrl-c-ret ()
  18246. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18247. (interactive)
  18248. (cond
  18249. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18250. (t (call-interactively 'org-insert-heading))))
  18251. (defun org-find-visible ()
  18252. (let ((s (point)))
  18253. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18254. (get-char-property s 'invisible)))
  18255. s))
  18256. (defun org-find-invisible ()
  18257. (let ((s (point)))
  18258. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18259. (not (get-char-property s 'invisible))))
  18260. s))
  18261. (defun org-copy-visible (beg end)
  18262. "Copy the visible parts of the region."
  18263. (interactive "r")
  18264. (let ((result ""))
  18265. (while (/= beg end)
  18266. (when (get-char-property beg 'invisible)
  18267. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18268. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18269. (setq result (concat result (buffer-substring beg next)))
  18270. (setq beg next)))
  18271. (kill-new result)))
  18272. (defun org-copy-special ()
  18273. "Copy region in table or copy current subtree.
  18274. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18275. context. See the individual commands for more information."
  18276. (interactive)
  18277. (call-interactively
  18278. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18279. (defun org-cut-special ()
  18280. "Cut region in table or cut current subtree.
  18281. Calls `org-table-cut-region' or `org-cut-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-cut-region #'org-cut-subtree)))
  18286. (defun org-paste-special (arg)
  18287. "Paste rectangular region into table, or past subtree relative to level.
  18288. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18289. See the individual commands for more information."
  18290. (interactive "P")
  18291. (if (org-at-table-p)
  18292. (org-table-paste-rectangle)
  18293. (org-paste-subtree arg)))
  18294. (defun org-edit-special (&optional arg)
  18295. "Call a special editor for the element at point.
  18296. When at a table, call the formula editor with `org-table-edit-formulas'.
  18297. When in a source code block, call `org-edit-src-code'.
  18298. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18299. When in an export block, call `org-edit-export-block'.
  18300. When in a LaTeX environment, call `org-edit-latex-environment'.
  18301. When at an #+INCLUDE keyword, visit the included file.
  18302. When at a footnote reference, call `org-edit-footnote-reference'
  18303. On a link, call `ffap' to visit the link at point.
  18304. Otherwise, return a user error."
  18305. (interactive "P")
  18306. (let ((element (org-element-at-point)))
  18307. (barf-if-buffer-read-only)
  18308. (pcase (org-element-type element)
  18309. (`src-block
  18310. (if (not arg) (org-edit-src-code)
  18311. (let* ((info (org-babel-get-src-block-info))
  18312. (lang (nth 0 info))
  18313. (params (nth 2 info))
  18314. (session (cdr (assq :session params))))
  18315. (if (not session) (org-edit-src-code)
  18316. ;; At a src-block with a session and function called with
  18317. ;; an ARG: switch to the buffer related to the inferior
  18318. ;; process.
  18319. (switch-to-buffer
  18320. (funcall (intern (concat "org-babel-prep-session:" lang))
  18321. session params))))))
  18322. (`keyword
  18323. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18324. (org-open-link-from-string
  18325. (format "[[%s]]"
  18326. (expand-file-name
  18327. (let ((value (org-element-property :value element)))
  18328. (cond ((org-file-url-p value)
  18329. (user-error "The file is specified as a URL, cannot be edited"))
  18330. ((not (org-string-nw-p value))
  18331. (user-error "No file to edit"))
  18332. ((string-match "\\`\"\\(.*?\\)\"" value)
  18333. (match-string 1 value))
  18334. ((string-match "\\`[^ \t\"]\\S-*" value)
  18335. (match-string 0 value))
  18336. (t (user-error "No valid file specified")))))))
  18337. (user-error "No special environment to edit here")))
  18338. (`table
  18339. (if (eq (org-element-property :type element) 'table.el)
  18340. (org-edit-table.el)
  18341. (call-interactively 'org-table-edit-formulas)))
  18342. ;; Only Org tables contain `table-row' type elements.
  18343. (`table-row (call-interactively 'org-table-edit-formulas))
  18344. (`example-block (org-edit-src-code))
  18345. (`export-block (org-edit-export-block))
  18346. (`fixed-width (org-edit-fixed-width-region))
  18347. (`latex-environment (org-edit-latex-environment))
  18348. (_
  18349. ;; No notable element at point. Though, we may be at a link or
  18350. ;; a footnote reference, which are objects. Thus, scan deeper.
  18351. (let ((context (org-element-context element)))
  18352. (pcase (org-element-type context)
  18353. (`footnote-reference (org-edit-footnote-reference))
  18354. (`inline-src-block (org-edit-inline-src-code))
  18355. (`link (call-interactively #'ffap))
  18356. (_ (user-error "No special environment to edit here"))))))))
  18357. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18358. (defun org-ctrl-c-ctrl-c (&optional arg)
  18359. "Set tags in headline, or update according to changed information at point.
  18360. This command does many different things, depending on context:
  18361. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18362. this is what we do.
  18363. - If the cursor is on a statistics cookie, update it.
  18364. - If the cursor is in a headline, prompt for tags and insert them
  18365. into the current line, aligned to `org-tags-column'. When called
  18366. with prefix arg, realign all tags in the current buffer.
  18367. - If the cursor is in one of the special #+KEYWORD lines, this
  18368. triggers scanning the buffer for these lines and updating the
  18369. information.
  18370. - If the cursor is inside a table, realign the table. This command
  18371. works even if the automatic table editor has been turned off.
  18372. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18373. the entire table.
  18374. - If the cursor is at a footnote reference or definition, jump to
  18375. the corresponding definition or references, respectively.
  18376. - If the cursor is a the beginning of a dynamic block, update it.
  18377. - If the current buffer is a capture buffer, close note and file it.
  18378. - If the cursor is on a <<<target>>>, update radio targets and
  18379. corresponding links in this buffer.
  18380. - If the cursor is on a numbered item in a plain list, renumber the
  18381. ordered list.
  18382. - If the cursor is on a checkbox, toggle it.
  18383. - If the cursor is on a code block, evaluate it. The variable
  18384. `org-confirm-babel-evaluate' can be used to control prompting
  18385. before code block evaluation, by default every code block
  18386. evaluation requires confirmation. Code block evaluation can be
  18387. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18388. (interactive "P")
  18389. (cond
  18390. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18391. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18392. (org-remove-occur-highlights)
  18393. (message "Temporary highlights/overlays removed from current buffer"))
  18394. ((and (local-variable-p 'org-finish-function)
  18395. (fboundp org-finish-function))
  18396. (funcall org-finish-function))
  18397. ((org-babel-hash-at-point))
  18398. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18399. (t
  18400. (let* ((context
  18401. (org-element-lineage
  18402. (org-element-context)
  18403. ;; Limit to supported contexts.
  18404. '(babel-call clock dynamic-block footnote-definition
  18405. footnote-reference inline-babel-call inline-src-block
  18406. inlinetask item keyword node-property paragraph
  18407. plain-list planning property-drawer radio-target
  18408. src-block statistics-cookie table table-cell table-row
  18409. timestamp)
  18410. t))
  18411. (type (org-element-type context)))
  18412. ;; For convenience: at the first line of a paragraph on the same
  18413. ;; line as an item, apply function on that item instead.
  18414. (when (eq type 'paragraph)
  18415. (let ((parent (org-element-property :parent context)))
  18416. (when (and (eq (org-element-type parent) 'item)
  18417. (= (line-beginning-position)
  18418. (org-element-property :begin parent)))
  18419. (setq context parent)
  18420. (setq type 'item))))
  18421. ;; Act according to type of element or object at point.
  18422. ;;
  18423. ;; Do nothing on a blank line, except if it is contained in
  18424. ;; a src block. Hence, we first check if point is in such
  18425. ;; a block and then if it is at a blank line.
  18426. (pcase type
  18427. ((or `inline-src-block `src-block)
  18428. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18429. (org-babel-eval-wipe-error-buffer)
  18430. (org-babel-execute-src-block
  18431. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18432. ((guard (org-match-line "[ \t]*$"))
  18433. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18434. (user-error
  18435. (substitute-command-keys
  18436. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18437. ((or `babel-call `inline-babel-call)
  18438. (let ((info (org-babel-lob-get-info context)))
  18439. (when info (org-babel-execute-src-block nil info))))
  18440. (`clock (org-clock-update-time-maybe))
  18441. (`dynamic-block
  18442. (save-excursion
  18443. (goto-char (org-element-property :post-affiliated context))
  18444. (org-update-dblock)))
  18445. (`footnote-definition
  18446. (goto-char (org-element-property :post-affiliated context))
  18447. (call-interactively 'org-footnote-action))
  18448. (`footnote-reference (call-interactively #'org-footnote-action))
  18449. ((or `headline `inlinetask)
  18450. (save-excursion (goto-char (org-element-property :begin context))
  18451. (call-interactively #'org-set-tags)))
  18452. (`item
  18453. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18454. ;; unconditionally, whereas `C-u' will toggle its presence.
  18455. ;; Without a universal argument, if the item has a checkbox,
  18456. ;; toggle it. Otherwise repair the list.
  18457. (let* ((box (org-element-property :checkbox context))
  18458. (struct (org-element-property :structure context))
  18459. (old-struct (copy-tree struct))
  18460. (parents (org-list-parents-alist struct))
  18461. (prevs (org-list-prevs-alist struct))
  18462. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18463. (org-list-set-checkbox
  18464. (org-element-property :begin context) struct
  18465. (cond ((equal arg '(16)) "[-]")
  18466. ((and (not box) (equal arg '(4))) "[ ]")
  18467. ((or (not box) (equal arg '(4))) nil)
  18468. ((eq box 'on) "[ ]")
  18469. (t "[X]")))
  18470. ;; Mimic `org-list-write-struct' but with grabbing a return
  18471. ;; value from `org-list-struct-fix-box'.
  18472. (org-list-struct-fix-ind struct parents 2)
  18473. (org-list-struct-fix-item-end struct)
  18474. (org-list-struct-fix-bul struct prevs)
  18475. (org-list-struct-fix-ind struct parents)
  18476. (let ((block-item
  18477. (org-list-struct-fix-box struct parents prevs orderedp)))
  18478. (if (and box (equal struct old-struct))
  18479. (if (equal arg '(16))
  18480. (message "Checkboxes already reset")
  18481. (user-error "Cannot toggle this checkbox: %s"
  18482. (if (eq box 'on)
  18483. "all subitems checked"
  18484. "unchecked subitems")))
  18485. (org-list-struct-apply-struct struct old-struct)
  18486. (org-update-checkbox-count-maybe))
  18487. (when block-item
  18488. (message "Checkboxes were removed due to empty box at line %d"
  18489. (org-current-line block-item))))))
  18490. (`keyword
  18491. (let ((org-inhibit-startup-visibility-stuff t)
  18492. (org-startup-align-all-tables nil))
  18493. (when (boundp 'org-table-coordinate-overlays)
  18494. (mapc #'delete-overlay org-table-coordinate-overlays)
  18495. (setq org-table-coordinate-overlays nil))
  18496. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18497. (message "Local setup has been refreshed"))
  18498. (`plain-list
  18499. ;; At a plain list, with a double C-u argument, set
  18500. ;; checkboxes of each item to "[-]", whereas a single one
  18501. ;; will toggle their presence according to the state of the
  18502. ;; first item in the list. Without an argument, repair the
  18503. ;; list.
  18504. (let* ((begin (org-element-property :contents-begin context))
  18505. (struct (org-element-property :structure context))
  18506. (old-struct (copy-tree struct))
  18507. (first-box (save-excursion
  18508. (goto-char begin)
  18509. (looking-at org-list-full-item-re)
  18510. (match-string-no-properties 3)))
  18511. (new-box (cond ((equal arg '(16)) "[-]")
  18512. ((equal arg '(4)) (unless first-box "[ ]"))
  18513. ((equal first-box "[X]") "[ ]")
  18514. (t "[X]"))))
  18515. (cond
  18516. (arg
  18517. (dolist (pos
  18518. (org-list-get-all-items
  18519. begin struct (org-list-prevs-alist struct)))
  18520. (org-list-set-checkbox pos struct new-box)))
  18521. ((and first-box (eq (point) begin))
  18522. ;; For convenience, when point is at bol on the first
  18523. ;; item of the list and no argument is provided, simply
  18524. ;; toggle checkbox of that item, if any.
  18525. (org-list-set-checkbox begin struct new-box)))
  18526. (org-list-write-struct
  18527. struct (org-list-parents-alist struct) old-struct)
  18528. (org-update-checkbox-count-maybe)))
  18529. ((or `property-drawer `node-property)
  18530. (call-interactively #'org-property-action))
  18531. (`radio-target
  18532. (call-interactively #'org-update-radio-target-regexp))
  18533. (`statistics-cookie
  18534. (call-interactively #'org-update-statistics-cookies))
  18535. ((or `table `table-cell `table-row)
  18536. ;; At a table, recalculate every field and align it. Also
  18537. ;; send the table if necessary. If the table has
  18538. ;; a `table.el' type, just give up. At a table row or cell,
  18539. ;; maybe recalculate line but always align table.
  18540. (if (eq (org-element-property :type context) 'table.el)
  18541. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18542. Use `\\[org-edit-special]' to edit table.el tables"))
  18543. (if (or (eq type 'table)
  18544. ;; Check if point is at a TBLFM line.
  18545. (and (eq type 'table-row)
  18546. (= (point) (org-element-property :end context))))
  18547. (save-excursion
  18548. (if (org-at-TBLFM-p)
  18549. (progn (require 'org-table)
  18550. (org-table-calc-current-TBLFM))
  18551. (goto-char (org-element-property :contents-begin context))
  18552. (org-call-with-arg 'org-table-recalculate (or arg t))
  18553. (orgtbl-send-table 'maybe)))
  18554. (org-table-maybe-eval-formula)
  18555. (cond (arg (call-interactively #'org-table-recalculate))
  18556. ((org-table-maybe-recalculate-line))
  18557. (t (org-table-align))))))
  18558. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18559. (org-timestamp-change 0 'day))
  18560. ((and `nil (guard (org-at-heading-p)))
  18561. ;; When point is on an unsupported object type, we can miss
  18562. ;; the fact that it also is at a heading. Handle it here.
  18563. (call-interactively #'org-set-tags))
  18564. ((guard
  18565. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18566. (_
  18567. (user-error
  18568. (substitute-command-keys
  18569. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18570. (defun org-mode-restart ()
  18571. (interactive)
  18572. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18573. (funcall major-mode)
  18574. (hack-local-variables)
  18575. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18576. (org-indent-mode -1))
  18577. (org-reset-file-cache))
  18578. (message "%s restarted" major-mode))
  18579. (defun org-kill-note-or-show-branches ()
  18580. "Abort storing current note, or call `outline-show-branches'."
  18581. (interactive)
  18582. (if (not org-finish-function)
  18583. (save-excursion
  18584. (save-restriction
  18585. (org-narrow-to-subtree)
  18586. (org-flag-subtree t)
  18587. (call-interactively 'outline-show-branches)
  18588. (org-hide-archived-subtrees (point-min) (point-max))))
  18589. (let ((org-note-abort t))
  18590. (funcall org-finish-function))))
  18591. (defun org-delete-indentation (&optional arg)
  18592. "Join current line to previous and fix whitespace at join.
  18593. If previous line is a headline add to headline title. Otherwise
  18594. the function calls `delete-indentation'.
  18595. With a non-nil optional argument, join it to the following one."
  18596. (interactive "*P")
  18597. (if (save-excursion
  18598. (beginning-of-line (if arg 1 0))
  18599. (let ((case-fold-search nil))
  18600. (looking-at org-complex-heading-regexp)))
  18601. ;; At headline.
  18602. (let ((tags-column (when (match-beginning 5)
  18603. (save-excursion (goto-char (match-beginning 5))
  18604. (current-column))))
  18605. (string (concat " " (progn (when arg (forward-line 1))
  18606. (org-trim (delete-and-extract-region
  18607. (line-beginning-position)
  18608. (line-end-position)))))))
  18609. (unless (bobp) (delete-region (point) (1- (point))))
  18610. (goto-char (or (match-end 4)
  18611. (match-beginning 5)
  18612. (match-end 0)))
  18613. (skip-chars-backward " \t")
  18614. (save-excursion (insert string))
  18615. ;; Adjust alignment of tags.
  18616. (cond
  18617. ((not tags-column)) ;no tags
  18618. (org-auto-align-tags (org-set-tags nil t))
  18619. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18620. (delete-indentation arg)))
  18621. (defun org-open-line (n)
  18622. "Insert a new row in tables, call `open-line' elsewhere.
  18623. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18624. As a special case, when a document starts with a table, allow to
  18625. call `open-line' on the very first character."
  18626. (interactive "*p")
  18627. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18628. (org-table-insert-row)
  18629. (open-line n)))
  18630. (defun org-return (&optional indent)
  18631. "Goto next table row or insert a newline.
  18632. Calls `org-table-next-row' or `newline', depending on context.
  18633. When optional INDENT argument is non-nil, call
  18634. `newline-and-indent' instead of `newline'.
  18635. When `org-return-follows-link' is non-nil and point is on
  18636. a timestamp or a link, call `org-open-at-point'. However, it
  18637. will not happen if point is in a table or on a \"dead\"
  18638. object (e.g., within a comment). In these case, you need to use
  18639. `org-open-at-point' directly."
  18640. (interactive)
  18641. (let ((context (if org-return-follows-link (org-element-context)
  18642. (org-element-at-point))))
  18643. (cond
  18644. ;; In a table, call `org-table-next-row'. However, before first
  18645. ;; column or after last one, split the table.
  18646. ((or (and (eq (org-element-type context) 'table)
  18647. (>= (point) (org-element-property :contents-begin context))
  18648. (< (point) (org-element-property :contents-end context)))
  18649. (org-element-lineage context '(table-row table-cell) t))
  18650. (if (or (looking-at-p "[ \t]*$")
  18651. (save-excursion (skip-chars-backward " \t") (bolp)))
  18652. (insert "\n")
  18653. (org-table-justify-field-maybe)
  18654. (call-interactively #'org-table-next-row)))
  18655. ;; On a link or a timestamp, call `org-open-at-point' if
  18656. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18657. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18658. ((and org-return-follows-link
  18659. (or (org-in-regexp org-ts-regexp-both nil t)
  18660. (org-in-regexp org-tsr-regexp-both nil t)
  18661. (org-in-regexp org-any-link-re nil t)))
  18662. (call-interactively #'org-open-at-point))
  18663. ;; Insert newline in heading, but preserve tags.
  18664. ((and (not (bolp))
  18665. (save-excursion (beginning-of-line)
  18666. (let ((case-fold-search nil))
  18667. (looking-at org-complex-heading-regexp))))
  18668. ;; At headline. Split line. However, if point is on keyword,
  18669. ;; priority cookie or tags, do not break any of them: add
  18670. ;; a newline after the headline instead.
  18671. (let ((tags-column (and (match-beginning 5)
  18672. (save-excursion (goto-char (match-beginning 5))
  18673. (current-column))))
  18674. (string
  18675. (when (and (match-end 4) (org-point-in-group (point) 4))
  18676. (delete-and-extract-region (point) (match-end 4)))))
  18677. ;; Adjust tag alignment.
  18678. (cond
  18679. ((not (and tags-column string)))
  18680. (org-auto-align-tags (org-set-tags nil t))
  18681. (t (org--align-tags-here tags-column))) ;preserve tags column
  18682. (end-of-line)
  18683. (org-show-entry)
  18684. (if indent (newline-and-indent) (newline))
  18685. (when string (save-excursion (insert (org-trim string))))))
  18686. ;; In a list, make sure indenting keeps trailing text within.
  18687. ((and indent
  18688. (not (eolp))
  18689. (org-element-lineage context '(item)))
  18690. (let ((trailing-data
  18691. (delete-and-extract-region (point) (line-end-position))))
  18692. (newline-and-indent)
  18693. (save-excursion (insert trailing-data))))
  18694. (t (if indent (newline-and-indent) (newline))))))
  18695. (defun org-return-indent ()
  18696. "Goto next table row or insert a newline and indent.
  18697. Calls `org-table-next-row' or `newline-and-indent', depending on
  18698. context. See the individual commands for more information."
  18699. (interactive)
  18700. (org-return t))
  18701. (defun org-ctrl-c-tab (&optional _arg)
  18702. "Toggle columns width in a table, or show children.
  18703. Call `org-table-toggle-column-width' if point is in a table.
  18704. Otherwise, call `org-show-children'."
  18705. (interactive "p")
  18706. (call-interactively
  18707. (if (org-at-table-p) #'org-table-toggle-column-width
  18708. #'org-show-children)))
  18709. (defun org-ctrl-c-star ()
  18710. "Compute table, or change heading status of lines.
  18711. Calls `org-table-recalculate' or `org-toggle-heading',
  18712. depending on context."
  18713. (interactive)
  18714. (cond
  18715. ((org-at-table-p)
  18716. (call-interactively 'org-table-recalculate))
  18717. (t
  18718. ;; Convert all lines in region to list items
  18719. (call-interactively 'org-toggle-heading))))
  18720. (defun org-ctrl-c-minus ()
  18721. "Insert separator line in table or modify bullet status of line.
  18722. Also turns a plain line or a region of lines into list items.
  18723. Calls `org-table-insert-hline', `org-toggle-item', or
  18724. `org-cycle-list-bullet', depending on context."
  18725. (interactive)
  18726. (cond
  18727. ((org-at-table-p)
  18728. (call-interactively 'org-table-insert-hline))
  18729. ((org-region-active-p)
  18730. (call-interactively 'org-toggle-item))
  18731. ((org-in-item-p)
  18732. (call-interactively 'org-cycle-list-bullet))
  18733. (t
  18734. (call-interactively 'org-toggle-item))))
  18735. (defun org-toggle-heading (&optional nstars)
  18736. "Convert headings to normal text, or items or text to headings.
  18737. If there is no active region, only convert the current line.
  18738. With a `\\[universal-argument]' prefix, convert the whole list at
  18739. point into heading.
  18740. In a region:
  18741. - If the first non blank line is a headline, remove the stars
  18742. from all headlines in the region.
  18743. - If it is a normal line, turn each and every normal line (i.e.,
  18744. not an heading or an item) in the region into headings. If you
  18745. want to convert only the first line of this region, use one
  18746. universal prefix argument.
  18747. - If it is a plain list item, turn all plain list items into headings.
  18748. When converting a line into a heading, the number of stars is chosen
  18749. such that the lines become children of the current entry. However,
  18750. when a numeric prefix argument is given, its value determines the
  18751. number of stars to add."
  18752. (interactive "P")
  18753. (let ((skip-blanks
  18754. (function
  18755. ;; Return beginning of first non-blank line, starting from
  18756. ;; line at POS.
  18757. (lambda (pos)
  18758. (save-excursion
  18759. (goto-char pos)
  18760. (while (org-at-comment-p) (forward-line))
  18761. (skip-chars-forward " \r\t\n")
  18762. (point-at-bol)))))
  18763. beg end toggled)
  18764. ;; Determine boundaries of changes. If a universal prefix has
  18765. ;; been given, put the list in a region. If region ends at a bol,
  18766. ;; do not consider the last line to be in the region.
  18767. (when (and current-prefix-arg (org-at-item-p))
  18768. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18769. (org-mark-element))
  18770. (if (org-region-active-p)
  18771. (setq beg (funcall skip-blanks (region-beginning))
  18772. end (copy-marker (save-excursion
  18773. (goto-char (region-end))
  18774. (if (bolp) (point) (point-at-eol)))))
  18775. (setq beg (funcall skip-blanks (point-at-bol))
  18776. end (copy-marker (point-at-eol))))
  18777. ;; Ensure inline tasks don't count as headings.
  18778. (org-with-limited-levels
  18779. (save-excursion
  18780. (goto-char beg)
  18781. (cond
  18782. ;; Case 1. Started at an heading: de-star headings.
  18783. ((org-at-heading-p)
  18784. (while (< (point) end)
  18785. (when (org-at-heading-p t)
  18786. (looking-at org-outline-regexp) (replace-match "")
  18787. (setq toggled t))
  18788. (forward-line)))
  18789. ;; Case 2. Started at an item: change items into headlines.
  18790. ;; One star will be added by `org-list-to-subtree'.
  18791. ((org-at-item-p)
  18792. (while (< (point) end)
  18793. (when (org-at-item-p)
  18794. ;; Pay attention to cases when region ends before list.
  18795. (let* ((struct (org-list-struct))
  18796. (list-end
  18797. (min (org-list-get-bottom-point struct) (1+ end))))
  18798. (save-restriction
  18799. (narrow-to-region (point) list-end)
  18800. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18801. (setq toggled t))
  18802. (forward-line)))
  18803. ;; Case 3. Started at normal text: make every line an heading,
  18804. ;; skipping headlines and items.
  18805. (t (let* ((stars
  18806. (make-string
  18807. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18808. (add-stars
  18809. (cond (nstars "") ; stars from prefix only
  18810. ((equal stars "") "*") ; before first heading
  18811. (org-odd-levels-only "**") ; inside heading, odd
  18812. (t "*"))) ; inside heading, oddeven
  18813. (rpl (concat stars add-stars " "))
  18814. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18815. (while (< (point) (if (equal nstars '(4)) lend end))
  18816. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18817. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18818. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18819. (forward-line)))))))
  18820. (unless toggled (message "Cannot toggle heading from here"))))
  18821. (defun org-meta-return (&optional arg)
  18822. "Insert a new heading or wrap a region in a table.
  18823. Calls `org-insert-heading', `org-insert-item' or
  18824. `org-table-wrap-region', depending on context. When called with
  18825. an argument, unconditionally call `org-insert-heading'."
  18826. (interactive "P")
  18827. (org-check-before-invisible-edit 'insert)
  18828. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18829. (call-interactively (cond (arg #'org-insert-heading)
  18830. ((org-at-table-p) #'org-table-wrap-region)
  18831. ((org-in-item-p) #'org-insert-item)
  18832. (t #'org-insert-heading)))))
  18833. ;;; Menu entries
  18834. (defsubst org-in-subtree-not-table-p ()
  18835. "Are we in a subtree and not in a table?"
  18836. (and (not (org-before-first-heading-p))
  18837. (not (org-at-table-p))))
  18838. ;; Define the Org mode menus
  18839. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18840. '("Tbl"
  18841. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18842. ["Next Field" org-cycle (org-at-table-p)]
  18843. ["Previous Field" org-shifttab (org-at-table-p)]
  18844. ["Next Row" org-return (org-at-table-p)]
  18845. "--"
  18846. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18847. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18848. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18849. "--"
  18850. ("Column"
  18851. ["Move Column Left" org-metaleft (org-at-table-p)]
  18852. ["Move Column Right" org-metaright (org-at-table-p)]
  18853. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18854. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18855. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18856. ("Row"
  18857. ["Move Row Up" org-metaup (org-at-table-p)]
  18858. ["Move Row Down" org-metadown (org-at-table-p)]
  18859. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18860. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18861. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18862. "--"
  18863. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18864. ("Rectangle"
  18865. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18866. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18867. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18868. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18869. "--"
  18870. ("Calculate"
  18871. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18872. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18873. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18874. "--"
  18875. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18876. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18877. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18878. "--"
  18879. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18880. "--"
  18881. ["Sum Column/Rectangle" org-table-sum
  18882. (or (org-at-table-p) (org-region-active-p))]
  18883. ["Which Column?" org-table-current-column (org-at-table-p)])
  18884. ["Debug Formulas"
  18885. org-table-toggle-formula-debugger
  18886. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18887. ["Show Col/Row Numbers"
  18888. org-table-toggle-coordinate-overlays
  18889. :style toggle
  18890. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18891. "--"
  18892. ["Create" org-table-create (not (org-at-table-p))]
  18893. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18894. ["Import from File" org-table-import (not (org-at-table-p))]
  18895. ["Export to File" org-table-export (org-at-table-p)]
  18896. "--"
  18897. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18898. "--"
  18899. ("Plot"
  18900. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18901. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18902. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18903. '("Org"
  18904. ("Show/Hide"
  18905. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18906. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18907. ["Sparse Tree..." org-sparse-tree t]
  18908. ["Reveal Context" org-reveal t]
  18909. ["Show All" org-show-all t]
  18910. "--"
  18911. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18912. "--"
  18913. ["New Heading" org-insert-heading t]
  18914. ("Navigate Headings"
  18915. ["Up" outline-up-heading t]
  18916. ["Next" outline-next-visible-heading t]
  18917. ["Previous" outline-previous-visible-heading t]
  18918. ["Next Same Level" outline-forward-same-level t]
  18919. ["Previous Same Level" outline-backward-same-level t]
  18920. "--"
  18921. ["Jump" org-goto t])
  18922. ("Edit Structure"
  18923. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18924. "--"
  18925. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18926. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18927. "--"
  18928. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18929. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18930. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18931. "--"
  18932. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18933. "--"
  18934. ["Copy visible text" org-copy-visible t]
  18935. "--"
  18936. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18937. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18938. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18939. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18940. "--"
  18941. ["Sort Region/Children" org-sort t]
  18942. "--"
  18943. ["Convert to odd levels" org-convert-to-odd-levels t]
  18944. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18945. ("Editing"
  18946. ["Emphasis..." org-emphasize t]
  18947. ["Edit Source Example" org-edit-special t]
  18948. "--"
  18949. ["Footnote new/jump" org-footnote-action t]
  18950. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18951. ("Archive"
  18952. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  18953. "--"
  18954. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  18955. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  18956. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  18957. )
  18958. "--"
  18959. ("Hyperlinks"
  18960. ["Store Link (Global)" org-store-link t]
  18961. ["Find existing link to here" org-occur-link-in-agenda-files t]
  18962. ["Insert Link" org-insert-link t]
  18963. ["Follow Link" org-open-at-point t]
  18964. "--"
  18965. ["Next link" org-next-link t]
  18966. ["Previous link" org-previous-link t]
  18967. "--"
  18968. ["Descriptive Links"
  18969. org-toggle-link-display
  18970. :style radio
  18971. :selected org-descriptive-links
  18972. ]
  18973. ["Literal Links"
  18974. org-toggle-link-display
  18975. :style radio
  18976. :selected (not org-descriptive-links)])
  18977. "--"
  18978. ("TODO Lists"
  18979. ["TODO/DONE/-" org-todo t]
  18980. ("Select keyword"
  18981. ["Next keyword" org-shiftright (org-at-heading-p)]
  18982. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  18983. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  18984. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  18985. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  18986. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  18987. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  18988. "--"
  18989. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  18990. :selected org-enforce-todo-dependencies :style toggle :active t]
  18991. "Settings for tree at point"
  18992. ["Do Children sequentially" org-toggle-ordered-property :style radio
  18993. :selected (org-entry-get nil "ORDERED")
  18994. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18995. ["Do Children parallel" org-toggle-ordered-property :style radio
  18996. :selected (not (org-entry-get nil "ORDERED"))
  18997. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18998. "--"
  18999. ["Set Priority" org-priority t]
  19000. ["Priority Up" org-shiftup t]
  19001. ["Priority Down" org-shiftdown t]
  19002. "--"
  19003. ["Get news from all feeds" org-feed-update-all t]
  19004. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19005. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19006. ("TAGS and Properties"
  19007. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19008. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19009. "--"
  19010. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19011. ["Column view of properties" org-columns t]
  19012. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19013. ("Dates and Scheduling"
  19014. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19015. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19016. ("Change Date"
  19017. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19018. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19019. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19020. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19021. ["Compute Time Range" org-evaluate-time-range t]
  19022. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19023. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19024. "--"
  19025. ["Custom time format" org-toggle-time-stamp-overlays
  19026. :style radio :selected org-display-custom-times]
  19027. "--"
  19028. ["Goto Calendar" org-goto-calendar t]
  19029. ["Date from Calendar" org-date-from-calendar t]
  19030. "--"
  19031. ["Start/Restart Timer" org-timer-start t]
  19032. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19033. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19034. ["Insert Timer String" org-timer t]
  19035. ["Insert Timer Item" org-timer-item t])
  19036. ("Logging work"
  19037. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19038. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19039. ["Clock out" org-clock-out t]
  19040. ["Clock cancel" org-clock-cancel t]
  19041. "--"
  19042. ["Mark as default task" org-clock-mark-default-task t]
  19043. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19044. ["Goto running clock" org-clock-goto t]
  19045. "--"
  19046. ["Display times" org-clock-display t]
  19047. ["Create clock table" org-clock-report t]
  19048. "--"
  19049. ["Record DONE time"
  19050. (progn (setq org-log-done (not org-log-done))
  19051. (message "Switching to %s will %s record a timestamp"
  19052. (car org-done-keywords)
  19053. (if org-log-done "automatically" "not")))
  19054. :style toggle :selected org-log-done])
  19055. "--"
  19056. ["Agenda Command..." org-agenda t]
  19057. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19058. ("File List for Agenda")
  19059. ("Special views current file"
  19060. ["TODO Tree" org-show-todo-tree t]
  19061. ["Check Deadlines" org-check-deadlines t]
  19062. ["Tags/Property tree" org-match-sparse-tree t])
  19063. "--"
  19064. ["Export/Publish..." org-export-dispatch t]
  19065. ("LaTeX"
  19066. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19067. :style toggle :selected org-cdlatex-mode]
  19068. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19069. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19070. ["Modify math symbol" org-cdlatex-math-modify
  19071. (org-inside-LaTeX-fragment-p)]
  19072. ["Insert citation" org-reftex-citation t])
  19073. "--"
  19074. ("MobileOrg"
  19075. ["Push Files and Views" org-mobile-push t]
  19076. ["Get Captured and Flagged" org-mobile-pull t]
  19077. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19078. "--"
  19079. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19080. "--"
  19081. ("Documentation"
  19082. ["Show Version" org-version t]
  19083. ["Info Documentation" org-info t])
  19084. ("Customize"
  19085. ["Browse Org Group" org-customize t]
  19086. "--"
  19087. ["Expand This Menu" org-create-customize-menu
  19088. (fboundp 'customize-menu-create)])
  19089. ["Send bug report" org-submit-bug-report t]
  19090. "--"
  19091. ("Refresh/Reload"
  19092. ["Refresh setup current buffer" org-mode-restart t]
  19093. ["Reload Org (after update)" org-reload t]
  19094. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19095. ))
  19096. (defun org-info (&optional node)
  19097. "Read documentation for Org in the info system.
  19098. With optional NODE, go directly to that node."
  19099. (interactive)
  19100. (info (format "(org)%s" (or node ""))))
  19101. ;;;###autoload
  19102. (defun org-submit-bug-report ()
  19103. "Submit a bug report on Org via mail.
  19104. Don't hesitate to report any problems or inaccurate documentation.
  19105. If you don't have setup sending mail from (X)Emacs, please copy the
  19106. output buffer into your mail program, as it gives us important
  19107. information about your Org version and configuration."
  19108. (interactive)
  19109. (require 'reporter)
  19110. (defvar reporter-prompt-for-summary-p)
  19111. (org-load-modules-maybe)
  19112. (org-require-autoloaded-modules)
  19113. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19114. (reporter-submit-bug-report
  19115. "emacs-orgmode@gnu.org"
  19116. (org-version nil 'full)
  19117. (let (list)
  19118. (save-window-excursion
  19119. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19120. (delete-other-windows)
  19121. (erase-buffer)
  19122. (insert "You are about to submit a bug report to the Org mailing list.
  19123. We would like to add your full Org and Outline configuration to the
  19124. bug report. This greatly simplifies the work of the maintainer and
  19125. other experts on the mailing list.
  19126. HOWEVER, some variables you have customized may contain private
  19127. information. The names of customers, colleagues, or friends, might
  19128. appear in the form of file names, tags, todo states, or search strings.
  19129. If you answer yes to the prompt, you might want to check and remove
  19130. such private information before sending the email.")
  19131. (add-text-properties (point-min) (point-max) '(face org-warning))
  19132. (when (yes-or-no-p "Include your Org configuration ")
  19133. (mapatoms
  19134. (lambda (v)
  19135. (and (boundp v)
  19136. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19137. (or (and (symbol-value v)
  19138. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19139. (and
  19140. (get v 'custom-type) (get v 'standard-value)
  19141. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19142. (push v list)))))
  19143. (kill-buffer (get-buffer "*Warn about privacy*"))
  19144. list))
  19145. nil nil
  19146. "Remember to cover the basics, that is, what you expected to happen and
  19147. what in fact did happen. You don't know how to make a good report? See
  19148. https://orgmode.org/manual/Feedback.html#Feedback
  19149. Your bug report will be posted to the Org mailing list.
  19150. ------------------------------------------------------------------------")
  19151. (save-excursion
  19152. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19153. (replace-match "\\1Bug: \\3 [\\2]")))))
  19154. (defun org-install-agenda-files-menu ()
  19155. (let ((bl (buffer-list)))
  19156. (save-excursion
  19157. (while bl
  19158. (set-buffer (pop bl))
  19159. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19160. (when (derived-mode-p 'org-mode)
  19161. (easy-menu-change
  19162. '("Org") "File List for Agenda"
  19163. (append
  19164. (list
  19165. ["Edit File List" (org-edit-agenda-file-list) t]
  19166. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19167. ["Remove Current File from List" org-remove-file t]
  19168. ["Cycle through agenda files" org-cycle-agenda-files t]
  19169. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19170. "--")
  19171. (mapcar 'org-file-menu-entry
  19172. ;; Prevent initialization from failing.
  19173. (ignore-errors (org-agenda-files t)))))))))
  19174. ;;;; Documentation
  19175. (defun org-require-autoloaded-modules ()
  19176. (interactive)
  19177. (mapc #'require
  19178. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19179. org-table org-timer)))
  19180. ;;;###autoload
  19181. (defun org-reload (&optional uncompiled)
  19182. "Reload all Org Lisp files.
  19183. With prefix arg UNCOMPILED, load the uncompiled versions."
  19184. (interactive "P")
  19185. (require 'loadhist)
  19186. (let* ((org-dir (org-find-library-dir "org"))
  19187. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19188. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19189. (remove-re (format "\\`%s\\'"
  19190. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19191. (feats (delete-dups
  19192. (mapcar 'file-name-sans-extension
  19193. (mapcar 'file-name-nondirectory
  19194. (delq nil
  19195. (mapcar 'feature-file
  19196. features))))))
  19197. (lfeat (append
  19198. (sort
  19199. (setq feats
  19200. (delq nil (mapcar
  19201. (lambda (f)
  19202. (if (and (string-match feature-re f)
  19203. (not (string-match remove-re f)))
  19204. f nil))
  19205. feats)))
  19206. 'string-lessp)
  19207. (list "org-version" "org")))
  19208. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19209. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19210. load-uncore load-misses)
  19211. (setq load-misses
  19212. (delq 't
  19213. (mapcar (lambda (f)
  19214. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19215. (and (string= org-dir contrib-dir)
  19216. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19217. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19218. (add-to-list 'load-uncore f 'append)
  19219. 't)
  19220. f))
  19221. lfeat)))
  19222. (when load-uncore
  19223. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19224. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19225. (if load-misses
  19226. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19227. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19228. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19229. ;;;###autoload
  19230. (defun org-customize ()
  19231. "Call the customize function with org as argument."
  19232. (interactive)
  19233. (org-load-modules-maybe)
  19234. (org-require-autoloaded-modules)
  19235. (customize-browse 'org))
  19236. (defun org-create-customize-menu ()
  19237. "Create a full customization menu for Org mode, insert it into the menu."
  19238. (interactive)
  19239. (org-load-modules-maybe)
  19240. (org-require-autoloaded-modules)
  19241. (if (fboundp 'customize-menu-create)
  19242. (progn
  19243. (easy-menu-change
  19244. '("Org") "Customize"
  19245. `(["Browse Org group" org-customize t]
  19246. "--"
  19247. ,(customize-menu-create 'org)
  19248. ["Set" Custom-set t]
  19249. ["Save" Custom-save t]
  19250. ["Reset to Current" Custom-reset-current t]
  19251. ["Reset to Saved" Custom-reset-saved t]
  19252. ["Reset to Standard Settings" Custom-reset-standard t]))
  19253. (message "\"Org\"-menu now contains full customization menu"))
  19254. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19255. ;;;; Miscellaneous stuff
  19256. ;;; Generally useful functions
  19257. (defun org-link-display-format (s)
  19258. "Replace links in string S with their description.
  19259. If there is no description, use the link target."
  19260. (save-match-data
  19261. (replace-regexp-in-string
  19262. org-bracket-link-analytic-regexp
  19263. (lambda (m)
  19264. (if (match-end 5) (match-string 5 m)
  19265. (concat (match-string 1 m) (match-string 3 m))))
  19266. s nil t)))
  19267. (defun org-toggle-link-display ()
  19268. "Toggle the literal or descriptive display of links."
  19269. (interactive)
  19270. (if org-descriptive-links
  19271. (progn (org-remove-from-invisibility-spec '(org-link))
  19272. (org-restart-font-lock)
  19273. (setq org-descriptive-links nil))
  19274. (progn (add-to-invisibility-spec '(org-link))
  19275. (org-restart-font-lock)
  19276. (setq org-descriptive-links t))))
  19277. (defun org-in-clocktable-p ()
  19278. "Check if the cursor is in a clocktable."
  19279. (let ((pos (point)) start)
  19280. (save-excursion
  19281. (end-of-line 1)
  19282. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19283. (setq start (match-beginning 0))
  19284. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19285. (>= (match-end 0) pos)
  19286. start))))
  19287. (defun org-in-verbatim-emphasis ()
  19288. (save-match-data
  19289. (and (org-in-regexp org-verbatim-re 2)
  19290. (>= (point) (match-beginning 3))
  19291. (<= (point) (match-end 4)))))
  19292. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19293. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19294. (if (and marker (marker-buffer marker)
  19295. (buffer-live-p (marker-buffer marker)))
  19296. (progn
  19297. (pop-to-buffer-same-window (marker-buffer marker))
  19298. (when (or (> marker (point-max)) (< marker (point-min)))
  19299. (widen))
  19300. (goto-char marker)
  19301. (org-show-context 'org-goto))
  19302. (if bookmark
  19303. (bookmark-jump bookmark)
  19304. (error "Cannot find location"))))
  19305. (defun org-quote-csv-field (s)
  19306. "Quote field for inclusion in CSV material."
  19307. (if (string-match "[\",]" s)
  19308. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19309. s))
  19310. (defun org-force-self-insert (N)
  19311. "Needed to enforce self-insert under remapping."
  19312. (interactive "p")
  19313. (self-insert-command N))
  19314. (defun org-fill-template (template alist)
  19315. "Find each %key of ALIST in TEMPLATE and replace it."
  19316. (let ((case-fold-search nil))
  19317. (dolist (entry (sort (copy-sequence alist)
  19318. (lambda (a b) (< (length (car a)) (length (car b))))))
  19319. (setq template
  19320. (replace-regexp-in-string
  19321. (concat "%" (regexp-quote (car entry)))
  19322. (or (cdr entry) "") template t t)))
  19323. template))
  19324. (defun org-quote-vert (s)
  19325. "Replace \"|\" with \"\\vert\"."
  19326. (while (string-match "|" s)
  19327. (setq s (replace-match "\\vert" t t s)))
  19328. s)
  19329. (defun org-uuidgen-p (s)
  19330. "Is S an ID created by UUIDGEN?"
  19331. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19332. (defun org-in-src-block-p (&optional inside)
  19333. "Whether point is in a code source block.
  19334. When INSIDE is non-nil, don't consider we are within a src block
  19335. when point is at #+BEGIN_SRC or #+END_SRC."
  19336. (let ((case-fold-search t))
  19337. (or (and (eq (get-char-property (point) 'src-block) t))
  19338. (and (not inside)
  19339. (save-match-data
  19340. (save-excursion
  19341. (beginning-of-line)
  19342. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19343. (defun org-context ()
  19344. "Return a list of contexts of the current cursor position.
  19345. If several contexts apply, all are returned.
  19346. Each context entry is a list with a symbol naming the context, and
  19347. two positions indicating start and end of the context. Possible
  19348. contexts are:
  19349. :headline anywhere in a headline
  19350. :headline-stars on the leading stars in a headline
  19351. :todo-keyword on a TODO keyword (including DONE) in a headline
  19352. :tags on the TAGS in a headline
  19353. :priority on the priority cookie in a headline
  19354. :item on the first line of a plain list item
  19355. :item-bullet on the bullet/number of a plain list item
  19356. :checkbox on the checkbox in a plain list item
  19357. :table in an Org table
  19358. :table-special on a special filed in a table
  19359. :table-table in a table.el table
  19360. :clocktable in a clocktable
  19361. :src-block in a source block
  19362. :link on a hyperlink
  19363. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19364. :target on a <<target>>
  19365. :radio-target on a <<<radio-target>>>
  19366. :latex-fragment on a LaTeX fragment
  19367. :latex-preview on a LaTeX fragment with overlaid preview image
  19368. This function expects the position to be visible because it uses font-lock
  19369. faces as a help to recognize the following contexts: :table-special, :link,
  19370. and :keyword."
  19371. (let* ((f (get-text-property (point) 'face))
  19372. (faces (if (listp f) f (list f)))
  19373. (case-fold-search t)
  19374. (p (point)) clist o)
  19375. ;; First the large context
  19376. (cond
  19377. ((org-at-heading-p t)
  19378. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19379. (when (progn
  19380. (beginning-of-line 1)
  19381. (looking-at org-todo-line-tags-regexp))
  19382. (push (org-point-in-group p 1 :headline-stars) clist)
  19383. (push (org-point-in-group p 2 :todo-keyword) clist)
  19384. (push (org-point-in-group p 4 :tags) clist))
  19385. (goto-char p)
  19386. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19387. (when (looking-at "\\[#[A-Z0-9]\\]")
  19388. (push (org-point-in-group p 0 :priority) clist)))
  19389. ((org-at-item-p)
  19390. (push (org-point-in-group p 2 :item-bullet) clist)
  19391. (push (list :item (point-at-bol)
  19392. (save-excursion (org-end-of-item) (point)))
  19393. clist)
  19394. (and (org-at-item-checkbox-p)
  19395. (push (org-point-in-group p 0 :checkbox) clist)))
  19396. ((org-at-table-p)
  19397. (push (list :table (org-table-begin) (org-table-end)) clist)
  19398. (when (memq 'org-formula faces)
  19399. (push (list :table-special
  19400. (previous-single-property-change p 'face)
  19401. (next-single-property-change p 'face)) clist)))
  19402. ((org-at-table-p 'any)
  19403. (push (list :table-table) clist)))
  19404. (goto-char p)
  19405. (let ((case-fold-search t))
  19406. ;; New the "medium" contexts: clocktables, source blocks
  19407. (cond ((org-in-clocktable-p)
  19408. (push (list :clocktable
  19409. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19410. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19411. (match-beginning 1))
  19412. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19413. (match-end 0))) clist))
  19414. ((org-in-src-block-p)
  19415. (push (list :src-block
  19416. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19417. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19418. (match-beginning 1))
  19419. (and (search-forward "#+END_SRC" nil t)
  19420. (match-beginning 0))) clist))))
  19421. (goto-char p)
  19422. ;; Now the small context
  19423. (cond
  19424. ((org-at-timestamp-p)
  19425. (push (org-point-in-group p 0 :timestamp) clist))
  19426. ((memq 'org-link faces)
  19427. (push (list :link
  19428. (previous-single-property-change p 'face)
  19429. (next-single-property-change p 'face)) clist))
  19430. ((memq 'org-special-keyword faces)
  19431. (push (list :keyword
  19432. (previous-single-property-change p 'face)
  19433. (next-single-property-change p 'face)) clist))
  19434. ((org-at-target-p)
  19435. (push (org-point-in-group p 0 :target) clist)
  19436. (goto-char (1- (match-beginning 0)))
  19437. (when (looking-at org-radio-target-regexp)
  19438. (push (org-point-in-group p 0 :radio-target) clist))
  19439. (goto-char p))
  19440. ((setq o (cl-some
  19441. (lambda (o)
  19442. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19443. o))
  19444. (overlays-at (point))))
  19445. (push (list :latex-fragment
  19446. (overlay-start o) (overlay-end o)) clist)
  19447. (push (list :latex-preview
  19448. (overlay-start o) (overlay-end o)) clist))
  19449. ((org-inside-LaTeX-fragment-p)
  19450. ;; FIXME: positions wrong.
  19451. (push (list :latex-fragment (point) (point)) clist)))
  19452. (setq clist (nreverse (delq nil clist)))
  19453. clist))
  19454. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19455. "Non-nil when point is between matches of START-RE and END-RE.
  19456. Also return a non-nil value when point is on one of the matches.
  19457. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19458. buffer positions. Default values are the positions of headlines
  19459. surrounding the point.
  19460. The functions returns a cons cell whose car (resp. cdr) is the
  19461. position before START-RE (resp. after END-RE)."
  19462. (save-match-data
  19463. (let ((pos (point))
  19464. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19465. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19466. beg end)
  19467. (save-excursion
  19468. ;; Point is on a block when on START-RE or if START-RE can be
  19469. ;; found before it...
  19470. (and (or (org-in-regexp start-re)
  19471. (re-search-backward start-re limit-up t))
  19472. (setq beg (match-beginning 0))
  19473. ;; ... and END-RE after it...
  19474. (goto-char (match-end 0))
  19475. (re-search-forward end-re limit-down t)
  19476. (> (setq end (match-end 0)) pos)
  19477. ;; ... without another START-RE in-between.
  19478. (goto-char (match-beginning 0))
  19479. (not (re-search-backward start-re (1+ beg) t))
  19480. ;; Return value.
  19481. (cons beg end))))))
  19482. (defun org-in-block-p (names)
  19483. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19484. NAMES is a list of strings containing names of blocks.
  19485. Return first block name matched, or nil. Beware that in case of
  19486. nested blocks, the returned name may not belong to the closest
  19487. block from point."
  19488. (save-match-data
  19489. (catch 'exit
  19490. (let ((case-fold-search t)
  19491. (lim-up (save-excursion (outline-previous-heading)))
  19492. (lim-down (save-excursion (outline-next-heading))))
  19493. (dolist (name names)
  19494. (let ((n (regexp-quote name)))
  19495. (when (org-between-regexps-p
  19496. (concat "^[ \t]*#\\+begin_" n)
  19497. (concat "^[ \t]*#\\+end_" n)
  19498. lim-up lim-down)
  19499. (throw 'exit n)))))
  19500. nil)))
  19501. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19502. "Call `multi-occur' with buffers for all agenda files."
  19503. (interactive "sOrg-files matching: ")
  19504. (let* ((files (org-agenda-files))
  19505. (tnames (mapcar #'file-truename files))
  19506. (extra org-agenda-text-search-extra-files))
  19507. (when (eq (car extra) 'agenda-archives)
  19508. (setq extra (cdr extra))
  19509. (setq files (org-add-archive-files files)))
  19510. (dolist (f extra)
  19511. (unless (member (file-truename f) tnames)
  19512. (unless (member f files) (setq files (append files (list f))))
  19513. (setq tnames (append tnames (list (file-truename f))))))
  19514. (multi-occur
  19515. (mapcar (lambda (x)
  19516. (with-current-buffer
  19517. ;; FIXME: Why not just (find-file-noselect x)?
  19518. ;; Is it to avoid the "revert buffer" prompt?
  19519. (or (get-file-buffer x) (find-file-noselect x))
  19520. (widen)
  19521. (current-buffer)))
  19522. files)
  19523. regexp)))
  19524. (add-hook 'occur-mode-find-occurrence-hook
  19525. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19526. (defun org-occur-link-in-agenda-files ()
  19527. "Create a link and search for it in the agendas.
  19528. The link is not stored in `org-stored-links', it is just created
  19529. for the search purpose."
  19530. (interactive)
  19531. (let ((link (condition-case nil
  19532. (org-store-link nil)
  19533. (error "Unable to create a link to here"))))
  19534. (org-occur-in-agenda-files (regexp-quote link))))
  19535. (defun org-back-over-empty-lines ()
  19536. "Move backwards over whitespace, to the beginning of the first empty line.
  19537. Returns the number of empty lines passed."
  19538. (let ((pos (point)))
  19539. (if (cdr (assq 'heading org-blank-before-new-entry))
  19540. (skip-chars-backward " \t\n\r")
  19541. (unless (eobp)
  19542. (forward-line -1)))
  19543. (beginning-of-line 2)
  19544. (goto-char (min (point) pos))
  19545. (count-lines (point) pos)))
  19546. (defun org-switch-to-buffer-other-window (&rest args)
  19547. "Switch to buffer in a second window on the current frame.
  19548. In particular, do not allow pop-up frames.
  19549. Returns the newly created buffer."
  19550. (org-no-popups
  19551. (apply 'switch-to-buffer-other-window args)))
  19552. (defun org-replace-escapes (string table)
  19553. "Replace %-escapes in STRING with values in TABLE.
  19554. TABLE is an association list with keys like \"%a\" and string values.
  19555. The sequences in STRING may contain normal field width and padding information,
  19556. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19557. so values can contain further %-escapes if they are define later in TABLE."
  19558. (let ((tbl (copy-alist table))
  19559. (case-fold-search nil)
  19560. (pchg 0)
  19561. re rpl)
  19562. (dolist (e tbl)
  19563. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19564. (when (and (cdr e) (string-match re (cdr e)))
  19565. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19566. (safe "SREF"))
  19567. (add-text-properties 0 3 (list 'sref sref) safe)
  19568. (setcdr e (replace-match safe t t (cdr e)))))
  19569. (while (string-match re string)
  19570. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19571. (cdr e)))
  19572. (setq string (replace-match rpl t t string))))
  19573. (while (setq pchg (next-property-change pchg string))
  19574. (let ((sref (get-text-property pchg 'sref string)))
  19575. (when (and sref (string-match "SREF" string pchg))
  19576. (setq string (replace-match sref t t string)))))
  19577. string))
  19578. ;;; TODO: Only called once, from ox-odt which should probably use
  19579. ;;; org-export-inline-image-p or something.
  19580. (defun org-file-image-p (file)
  19581. "Return non-nil if FILE is an image."
  19582. (save-match-data
  19583. (string-match (image-file-name-regexp) file)))
  19584. (defun org-get-cursor-date (&optional with-time)
  19585. "Return the date at cursor in as a time.
  19586. This works in the calendar and in the agenda, anywhere else it just
  19587. returns the current time.
  19588. If WITH-TIME is non-nil, returns the time of the event at point (in
  19589. the agenda) or the current time of the day."
  19590. (let (date day defd tp hod mod)
  19591. (when with-time
  19592. (setq tp (get-text-property (point) 'time))
  19593. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19594. (setq hod (string-to-number (match-string 1 tp))
  19595. mod (string-to-number (match-string 2 tp))))
  19596. (or tp (let ((now (decode-time)))
  19597. (setq hod (nth 2 now)
  19598. mod (nth 1 now)))))
  19599. (cond
  19600. ((eq major-mode 'calendar-mode)
  19601. (setq date (calendar-cursor-to-date)
  19602. defd (encode-time 0 (or mod 0) (or hod 0)
  19603. (nth 1 date) (nth 0 date) (nth 2 date))))
  19604. ((eq major-mode 'org-agenda-mode)
  19605. (setq day (get-text-property (point) 'day))
  19606. (when day
  19607. (setq date (calendar-gregorian-from-absolute day)
  19608. defd (encode-time 0 (or mod 0) (or hod 0)
  19609. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19610. (or defd (current-time))))
  19611. (defun org-mark-subtree (&optional up)
  19612. "Mark the current subtree.
  19613. This puts point at the start of the current subtree, and mark at
  19614. the end. If a numeric prefix UP is given, move up into the
  19615. hierarchy of headlines by UP levels before marking the subtree."
  19616. (interactive "P")
  19617. (org-with-limited-levels
  19618. (cond ((org-at-heading-p) (beginning-of-line))
  19619. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19620. (t (outline-previous-visible-heading 1))))
  19621. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19622. (if (called-interactively-p 'any)
  19623. (call-interactively 'org-mark-element)
  19624. (org-mark-element)))
  19625. (defun org-file-newer-than-p (file time)
  19626. "Non-nil if FILE is newer than TIME.
  19627. FILE is a filename, as a string, TIME is a list of integers, as
  19628. returned by, e.g., `current-time'."
  19629. (and (file-exists-p file)
  19630. ;; Only compare times up to whole seconds as some file-systems
  19631. ;; (e.g. HFS+) do not retain any finer granularity. As
  19632. ;; a consequence, make sure we return non-nil when the two
  19633. ;; times are equal.
  19634. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  19635. (cl-subseq time 0 2)))))
  19636. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  19637. "Compile a SOURCE file using PROCESS.
  19638. PROCESS is either a function or a list of shell commands, as
  19639. strings. EXT is a file extension, without the leading dot, as
  19640. a string. It is used to check if the process actually succeeded.
  19641. PROCESS must create a file with the same base name and directory
  19642. as SOURCE, but ending with EXT. The function then returns its
  19643. filename. Otherwise, it raises an error. The error message can
  19644. then be refined by providing string ERR-MSG, which is appended to
  19645. the standard message.
  19646. If PROCESS is a function, it is called with a single argument:
  19647. the SOURCE file.
  19648. If it is a list of commands, each of them is called using
  19649. `shell-command'. By default, in each command, %b, %f, %F, %o and
  19650. %O are replaced with, respectively, SOURCE base name, name, full
  19651. name, directory and absolute output file name. It is possible,
  19652. however, to use more place-holders by specifying them in optional
  19653. argument SPEC, as an alist following the pattern
  19654. (CHARACTER . REPLACEMENT-STRING).
  19655. When PROCESS is a list of commands, optional argument LOG-BUF can
  19656. be set to a buffer or a buffer name. `shell-command' then uses
  19657. it for output."
  19658. (let* ((base-name (file-name-base source))
  19659. (full-name (file-truename source))
  19660. (out-dir (or (file-name-directory source) "./"))
  19661. (output (expand-file-name (concat base-name "." ext) out-dir))
  19662. (time (current-time))
  19663. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  19664. (save-window-excursion
  19665. (pcase process
  19666. ((pred functionp) (funcall process (shell-quote-argument source)))
  19667. ((pred consp)
  19668. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  19669. (spec (append spec
  19670. `((?b . ,(shell-quote-argument base-name))
  19671. (?f . ,(shell-quote-argument source))
  19672. (?F . ,(shell-quote-argument full-name))
  19673. (?o . ,(shell-quote-argument out-dir))
  19674. (?O . ,(shell-quote-argument output))))))
  19675. (dolist (command process)
  19676. (shell-command (format-spec command spec) log-buf))
  19677. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  19678. (_ (error "No valid command to process %S%s" source err-msg))))
  19679. ;; Check for process failure. Output file is expected to be
  19680. ;; located in the same directory as SOURCE.
  19681. (unless (org-file-newer-than-p output time)
  19682. (error (format "File %S wasn't produced%s" output err-msg)))
  19683. output))
  19684. ;;; Indentation
  19685. (defvar org-element-greater-elements)
  19686. (defun org--get-expected-indentation (element contentsp)
  19687. "Expected indentation column for current line, according to ELEMENT.
  19688. ELEMENT is an element containing point. CONTENTSP is non-nil
  19689. when indentation is to be computed according to contents of
  19690. ELEMENT."
  19691. (let ((type (org-element-type element))
  19692. (start (org-element-property :begin element))
  19693. (post-affiliated (org-element-property :post-affiliated element)))
  19694. (org-with-wide-buffer
  19695. (cond
  19696. (contentsp
  19697. (cl-case type
  19698. ((diary-sexp footnote-definition) 0)
  19699. ((headline inlinetask nil)
  19700. (if (not org-adapt-indentation) 0
  19701. (let ((level (org-current-level)))
  19702. (if level (1+ level) 0))))
  19703. ((item plain-list) (org-list-item-body-column post-affiliated))
  19704. (t
  19705. (goto-char start)
  19706. (org-get-indentation))))
  19707. ((memq type '(headline inlinetask nil))
  19708. (if (org-match-line "[ \t]*$")
  19709. (org--get-expected-indentation element t)
  19710. 0))
  19711. ((memq type '(diary-sexp footnote-definition)) 0)
  19712. ;; First paragraph of a footnote definition or an item.
  19713. ;; Indent like parent.
  19714. ((< (line-beginning-position) start)
  19715. (org--get-expected-indentation
  19716. (org-element-property :parent element) t))
  19717. ;; At first line: indent according to previous sibling, if any,
  19718. ;; ignoring footnote definitions and inline tasks, or parent's
  19719. ;; contents.
  19720. ((= (line-beginning-position) start)
  19721. (catch 'exit
  19722. (while t
  19723. (if (= (point-min) start) (throw 'exit 0)
  19724. (goto-char (1- start))
  19725. (let* ((previous (org-element-at-point))
  19726. (parent previous))
  19727. (while (and parent (<= (org-element-property :end parent) start))
  19728. (setq previous parent
  19729. parent (org-element-property :parent parent)))
  19730. (cond
  19731. ((not previous) (throw 'exit 0))
  19732. ((> (org-element-property :end previous) start)
  19733. (throw 'exit (org--get-expected-indentation previous t)))
  19734. ((memq (org-element-type previous)
  19735. '(footnote-definition inlinetask))
  19736. (setq start (org-element-property :begin previous)))
  19737. (t (goto-char (org-element-property :begin previous))
  19738. (throw 'exit
  19739. (if (bolp) (org-get-indentation)
  19740. ;; At first paragraph in an item or
  19741. ;; a footnote definition.
  19742. (org--get-expected-indentation
  19743. (org-element-property :parent previous) t))))))))))
  19744. ;; Otherwise, move to the first non-blank line above.
  19745. (t
  19746. (beginning-of-line)
  19747. (let ((pos (point)))
  19748. (skip-chars-backward " \r\t\n")
  19749. (cond
  19750. ;; Two blank lines end a footnote definition or a plain
  19751. ;; list. When we indent an empty line after them, the
  19752. ;; containing list or footnote definition is over, so it
  19753. ;; qualifies as a previous sibling. Therefore, we indent
  19754. ;; like its first line.
  19755. ((and (memq type '(footnote-definition plain-list))
  19756. (> (count-lines (point) pos) 2))
  19757. (goto-char start)
  19758. (org-get-indentation))
  19759. ;; Line above is the first one of a paragraph at the
  19760. ;; beginning of an item or a footnote definition. Indent
  19761. ;; like parent.
  19762. ((< (line-beginning-position) start)
  19763. (org--get-expected-indentation
  19764. (org-element-property :parent element) t))
  19765. ;; Line above is the beginning of an element, i.e., point
  19766. ;; was originally on the blank lines between element's start
  19767. ;; and contents.
  19768. ((= (line-beginning-position) post-affiliated)
  19769. (org--get-expected-indentation element t))
  19770. ;; POS is after contents in a greater element. Indent like
  19771. ;; the beginning of the element.
  19772. ((and (memq type org-element-greater-elements)
  19773. (let ((cend (org-element-property :contents-end element)))
  19774. (and cend (<= cend pos))))
  19775. ;; As a special case, if point is at the end of a footnote
  19776. ;; definition or an item, indent like the very last element
  19777. ;; within. If that last element is an item, indent like
  19778. ;; its contents.
  19779. (if (memq type '(footnote-definition item plain-list))
  19780. (let ((last (org-element-at-point)))
  19781. (goto-char pos)
  19782. (org--get-expected-indentation
  19783. last (eq (org-element-type last) 'item)))
  19784. (goto-char start)
  19785. (org-get-indentation)))
  19786. ;; In any other case, indent like the current line.
  19787. (t (org-get-indentation)))))))))
  19788. (defun org--align-node-property ()
  19789. "Align node property at point.
  19790. Alignment is done according to `org-property-format', which see."
  19791. (when (save-excursion
  19792. (beginning-of-line)
  19793. (looking-at org-property-re))
  19794. (replace-match
  19795. (concat (match-string 4)
  19796. (org-trim
  19797. (format org-property-format (match-string 1) (match-string 3))))
  19798. t t)))
  19799. (defun org-indent-line ()
  19800. "Indent line depending on context.
  19801. Indentation is done according to the following rules:
  19802. - Footnote definitions, diary sexps, headlines and inline tasks
  19803. have to start at column 0.
  19804. - On the very first line of an element, consider, in order, the
  19805. next rules until one matches:
  19806. 1. If there's a sibling element before, ignoring footnote
  19807. definitions and inline tasks, indent like its first line.
  19808. 2. If element has a parent, indent like its contents. More
  19809. precisely, if parent is an item, indent after the
  19810. description part, if any, or the bullet (see
  19811. `org-list-description-max-indent'). Else, indent like
  19812. parent's first line.
  19813. 3. Otherwise, indent relatively to current level, if
  19814. `org-adapt-indentation' is non-nil, or to left margin.
  19815. - On a blank line at the end of an element, indent according to
  19816. the type of the element. More precisely
  19817. 1. If element is a plain list, an item, or a footnote
  19818. definition, indent like the very last element within.
  19819. 2. If element is a paragraph, indent like its last non blank
  19820. line.
  19821. 3. Otherwise, indent like its very first line.
  19822. - In the code part of a source block, use language major mode
  19823. to indent current line if `org-src-tab-acts-natively' is
  19824. non-nil. If it is nil, do nothing.
  19825. - Otherwise, indent like the first non-blank line above.
  19826. The function doesn't indent an item as it could break the whole
  19827. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19828. `\\[org-shiftmetaright]'.
  19829. Also align node properties according to `org-property-format'."
  19830. (interactive)
  19831. (cond
  19832. ((org-at-heading-p) 'noindent)
  19833. (t
  19834. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19835. (type (org-element-type element)))
  19836. (cond ((and (memq type '(plain-list item))
  19837. (= (line-beginning-position)
  19838. (org-element-property :post-affiliated element)))
  19839. 'noindent)
  19840. ((and (eq type 'latex-environment)
  19841. (>= (point) (org-element-property :post-affiliated element))
  19842. (< (point) (org-with-wide-buffer
  19843. (goto-char (org-element-property :end element))
  19844. (skip-chars-backward " \r\t\n")
  19845. (line-beginning-position 2))))
  19846. 'noindent)
  19847. ((and (eq type 'src-block)
  19848. org-src-tab-acts-natively
  19849. (> (line-beginning-position)
  19850. (org-element-property :post-affiliated element))
  19851. (< (line-beginning-position)
  19852. (org-with-wide-buffer
  19853. (goto-char (org-element-property :end element))
  19854. (skip-chars-backward " \r\t\n")
  19855. (line-beginning-position))))
  19856. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19857. (t
  19858. (let ((column (org--get-expected-indentation element nil)))
  19859. ;; Preserve current column.
  19860. (if (<= (current-column) (current-indentation))
  19861. (indent-line-to column)
  19862. (save-excursion (indent-line-to column))))
  19863. ;; Align node property. Also preserve current column.
  19864. (when (eq type 'node-property)
  19865. (let ((column (current-column)))
  19866. (org--align-node-property)
  19867. (org-move-to-column column)))))))))
  19868. (defun org-indent-region (start end)
  19869. "Indent each non-blank line in the region.
  19870. Called from a program, START and END specify the region to
  19871. indent. The function will not indent contents of example blocks,
  19872. verse blocks and export blocks as leading white spaces are
  19873. assumed to be significant there."
  19874. (interactive "r")
  19875. (save-excursion
  19876. (goto-char start)
  19877. (skip-chars-forward " \r\t\n")
  19878. (unless (eobp) (beginning-of-line))
  19879. (let ((indent-to
  19880. (lambda (ind pos)
  19881. ;; Set IND as indentation for all lines between point and
  19882. ;; POS. Blank lines are ignored. Leave point after POS
  19883. ;; once done.
  19884. (let ((limit (copy-marker pos)))
  19885. (while (< (point) limit)
  19886. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19887. (forward-line))
  19888. (set-marker limit nil))))
  19889. (end (copy-marker end)))
  19890. (while (< (point) end)
  19891. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19892. (let* ((element (org-element-at-point))
  19893. (type (org-element-type element))
  19894. (element-end (copy-marker (org-element-property :end element)))
  19895. (ind (org--get-expected-indentation element nil)))
  19896. (cond
  19897. ;; Element indented as a single block. Example blocks
  19898. ;; preserving indentation are a special case since the
  19899. ;; "contents" must not be indented whereas the block
  19900. ;; boundaries can.
  19901. ((or (memq type '(export-block latex-environment))
  19902. (and (eq type 'example-block)
  19903. (not
  19904. (or org-src-preserve-indentation
  19905. (org-element-property :preserve-indent element)))))
  19906. (let ((offset (- ind (org-get-indentation))))
  19907. (unless (zerop offset)
  19908. (indent-rigidly (org-element-property :begin element)
  19909. (org-element-property :end element)
  19910. offset)))
  19911. (goto-char element-end))
  19912. ;; Elements indented line wise. Be sure to exclude
  19913. ;; example blocks (preserving indentation) and source
  19914. ;; blocks from this category as they are treated
  19915. ;; specially later.
  19916. ((or (memq type '(paragraph table table-row))
  19917. (not (or (org-element-property :contents-begin element)
  19918. (memq type '(example-block src-block)))))
  19919. (when (eq type 'node-property)
  19920. (org--align-node-property)
  19921. (beginning-of-line))
  19922. (funcall indent-to ind (min element-end end)))
  19923. ;; Elements consisting of three parts: before the
  19924. ;; contents, the contents, and after the contents. The
  19925. ;; contents are treated specially, according to the
  19926. ;; element type, or not indented at all. Other parts are
  19927. ;; indented as a single block.
  19928. (t
  19929. (let* ((post (copy-marker
  19930. (org-element-property :post-affiliated element)))
  19931. (cbeg
  19932. (copy-marker
  19933. (cond
  19934. ((not (org-element-property :contents-begin element))
  19935. ;; Fake contents for source blocks.
  19936. (org-with-wide-buffer
  19937. (goto-char post)
  19938. (line-beginning-position 2)))
  19939. ((memq type '(footnote-definition item plain-list))
  19940. ;; Contents in these elements could start on
  19941. ;; the same line as the beginning of the
  19942. ;; element. Make sure we start indenting
  19943. ;; from the second line.
  19944. (org-with-wide-buffer
  19945. (goto-char post)
  19946. (end-of-line)
  19947. (skip-chars-forward " \r\t\n")
  19948. (if (eobp) (point) (line-beginning-position))))
  19949. (t (org-element-property :contents-begin element)))))
  19950. (cend (copy-marker
  19951. (or (org-element-property :contents-end element)
  19952. ;; Fake contents for source blocks.
  19953. (org-with-wide-buffer
  19954. (goto-char element-end)
  19955. (skip-chars-backward " \r\t\n")
  19956. (line-beginning-position)))
  19957. t)))
  19958. ;; Do not change items indentation individually as it
  19959. ;; might break the list as a whole. On the other
  19960. ;; hand, when at a plain list, indent it as a whole.
  19961. (cond ((eq type 'plain-list)
  19962. (let ((offset (- ind (org-get-indentation))))
  19963. (unless (zerop offset)
  19964. (indent-rigidly (org-element-property :begin element)
  19965. (org-element-property :end element)
  19966. offset))
  19967. (goto-char cbeg)))
  19968. ((eq type 'item) (goto-char cbeg))
  19969. (t (funcall indent-to ind (min cbeg end))))
  19970. (when (< (point) end)
  19971. (cl-case type
  19972. ((example-block verse-block))
  19973. (src-block
  19974. ;; In a source block, indent source code
  19975. ;; according to language major mode, but only if
  19976. ;; `org-src-tab-acts-natively' is non-nil.
  19977. (when (and (< (point) end) org-src-tab-acts-natively)
  19978. (ignore-errors
  19979. (org-babel-do-in-edit-buffer
  19980. (indent-region (point-min) (point-max))))))
  19981. (t (org-indent-region (point) (min cend end))))
  19982. (goto-char (min cend end))
  19983. (when (< (point) end)
  19984. (funcall indent-to ind (min element-end end))))
  19985. (set-marker post nil)
  19986. (set-marker cbeg nil)
  19987. (set-marker cend nil))))
  19988. (set-marker element-end nil))))
  19989. (set-marker end nil))))
  19990. (defun org-indent-drawer ()
  19991. "Indent the drawer at point."
  19992. (interactive)
  19993. (unless (save-excursion
  19994. (beginning-of-line)
  19995. (looking-at-p org-drawer-regexp))
  19996. (user-error "Not at a drawer"))
  19997. (let ((element (org-element-at-point)))
  19998. (unless (memq (org-element-type element) '(drawer property-drawer))
  19999. (user-error "Not at a drawer"))
  20000. (org-with-wide-buffer
  20001. (org-indent-region (org-element-property :begin element)
  20002. (org-element-property :end element))))
  20003. (message "Drawer at point indented"))
  20004. (defun org-indent-block ()
  20005. "Indent the block at point."
  20006. (interactive)
  20007. (unless (save-excursion
  20008. (beginning-of-line)
  20009. (let ((case-fold-search t))
  20010. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20011. (user-error "Not at a block"))
  20012. (let ((element (org-element-at-point)))
  20013. (unless (memq (org-element-type element)
  20014. '(comment-block center-block dynamic-block example-block
  20015. export-block quote-block special-block
  20016. src-block verse-block))
  20017. (user-error "Not at a block"))
  20018. (org-with-wide-buffer
  20019. (org-indent-region (org-element-property :begin element)
  20020. (org-element-property :end element))))
  20021. (message "Block at point indented"))
  20022. ;;; Filling
  20023. ;; We use our own fill-paragraph and auto-fill functions.
  20024. ;; `org-fill-paragraph' relies on adaptive filling and context
  20025. ;; checking. Appropriate `fill-prefix' is computed with
  20026. ;; `org-adaptive-fill-function'.
  20027. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20028. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20029. ;; `org-adaptive-fill-function' value. Internally,
  20030. ;; `org-comment-line-break-function' breaks the line.
  20031. ;; `org-setup-filling' installs filling and auto-filling related
  20032. ;; variables during `org-mode' initialization.
  20033. (defun org-setup-filling ()
  20034. (require 'org-element)
  20035. ;; Prevent auto-fill from inserting unwanted new items.
  20036. (when (boundp 'fill-nobreak-predicate)
  20037. (setq-local
  20038. fill-nobreak-predicate
  20039. (org-uniquify
  20040. (append fill-nobreak-predicate
  20041. '(org-fill-line-break-nobreak-p
  20042. org-fill-n-macro-as-item-nobreak-p
  20043. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20044. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20045. (setq-local paragraph-start paragraph-ending)
  20046. (setq-local paragraph-separate paragraph-ending))
  20047. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20048. (setq-local auto-fill-inhibit-regexp nil)
  20049. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20050. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20051. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20052. (defun org-fill-line-break-nobreak-p ()
  20053. "Non-nil when a new line at point would create an Org line break."
  20054. (save-excursion
  20055. (skip-chars-backward "[ \t]")
  20056. (skip-chars-backward "\\\\")
  20057. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20058. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20059. "Non-nil when a new line at point would split a timestamp."
  20060. (and (org-at-timestamp-p 'lax)
  20061. (not (looking-at org-ts-regexp-both))))
  20062. (defun org-fill-n-macro-as-item-nobreak-p ()
  20063. "Non-nil when a new line at point would create a new list."
  20064. ;; During export, a "n" macro followed by a dot or a closing
  20065. ;; parenthesis can end up being parsed as a new list item.
  20066. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20067. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20068. (defun org-adaptive-fill-function ()
  20069. "Compute a fill prefix for the current line.
  20070. Return fill prefix, as a string, or nil if current line isn't
  20071. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20072. matches in paragraphs or comments, use it."
  20073. (org-with-wide-buffer
  20074. (unless (org-at-heading-p)
  20075. (let* ((p (line-beginning-position))
  20076. (element (save-excursion
  20077. (beginning-of-line)
  20078. (org-element-at-point)))
  20079. (type (org-element-type element))
  20080. (post-affiliated (org-element-property :post-affiliated element)))
  20081. (unless (< p post-affiliated)
  20082. (cl-case type
  20083. (comment
  20084. (save-excursion
  20085. (beginning-of-line)
  20086. (looking-at "[ \t]*")
  20087. (concat (match-string 0) "# ")))
  20088. (footnote-definition "")
  20089. ((item plain-list)
  20090. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20091. (paragraph
  20092. ;; Fill prefix is usually the same as the current line,
  20093. ;; unless the paragraph is at the beginning of an item.
  20094. (let ((parent (org-element-property :parent element)))
  20095. (save-excursion
  20096. (beginning-of-line)
  20097. (cond ((eq (org-element-type parent) 'item)
  20098. (make-string (org-list-item-body-column
  20099. (org-element-property :begin parent))
  20100. ?\s))
  20101. ((and adaptive-fill-regexp
  20102. ;; Locally disable
  20103. ;; `adaptive-fill-function' to let
  20104. ;; `fill-context-prefix' handle
  20105. ;; `adaptive-fill-regexp' variable.
  20106. (let (adaptive-fill-function)
  20107. (fill-context-prefix
  20108. post-affiliated
  20109. (org-element-property :end element)))))
  20110. ((looking-at "[ \t]+") (match-string 0))
  20111. (t "")))))
  20112. (comment-block
  20113. ;; Only fill contents if P is within block boundaries.
  20114. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20115. (forward-line)
  20116. (point)))
  20117. (cend (save-excursion
  20118. (goto-char (org-element-property :end element))
  20119. (skip-chars-backward " \r\t\n")
  20120. (line-beginning-position))))
  20121. (when (and (>= p cbeg) (< p cend))
  20122. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20123. (match-string 0)
  20124. ""))))))))))
  20125. (defun org-fill-element (&optional justify)
  20126. "Fill element at point, when applicable.
  20127. This function only applies to comment blocks, comments, example
  20128. blocks and paragraphs. Also, as a special case, re-align table
  20129. when point is at one.
  20130. If JUSTIFY is non-nil (interactively, with prefix argument),
  20131. justify as well. If `sentence-end-double-space' is non-nil, then
  20132. period followed by one space does not end a sentence, so don't
  20133. break a line there. The variable `fill-column' controls the
  20134. width for filling.
  20135. For convenience, when point is at a plain list, an item or
  20136. a footnote definition, try to fill the first paragraph within."
  20137. (with-syntax-table org-mode-transpose-word-syntax-table
  20138. ;; Move to end of line in order to get the first paragraph within
  20139. ;; a plain list or a footnote definition.
  20140. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20141. ;; First check if point is in a blank line at the beginning of
  20142. ;; the buffer. In that case, ignore filling.
  20143. (cl-case (org-element-type element)
  20144. ;; Use major mode filling function is src blocks.
  20145. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20146. ;; Align Org tables, leave table.el tables as-is.
  20147. (table-row (org-table-align) t)
  20148. (table
  20149. (when (eq (org-element-property :type element) 'org)
  20150. (save-excursion
  20151. (goto-char (org-element-property :post-affiliated element))
  20152. (org-table-align)))
  20153. t)
  20154. (paragraph
  20155. ;; Paragraphs may contain `line-break' type objects.
  20156. (let ((beg (max (point-min)
  20157. (org-element-property :contents-begin element)))
  20158. (end (min (point-max)
  20159. (org-element-property :contents-end element))))
  20160. ;; Do nothing if point is at an affiliated keyword.
  20161. (if (< (line-end-position) beg) t
  20162. ;; Fill paragraph, taking line breaks into account.
  20163. (save-excursion
  20164. (goto-char beg)
  20165. (let ((cuts (list beg)))
  20166. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20167. (when (eq 'line-break
  20168. (org-element-type
  20169. (save-excursion (backward-char)
  20170. (org-element-context))))
  20171. (push (point) cuts)))
  20172. (dolist (c (delq end cuts))
  20173. (fill-region-as-paragraph c end justify)
  20174. (setq end c))))
  20175. t)))
  20176. ;; Contents of `comment-block' type elements should be
  20177. ;; filled as plain text, but only if point is within block
  20178. ;; markers.
  20179. (comment-block
  20180. (let* ((case-fold-search t)
  20181. (beg (save-excursion
  20182. (goto-char (org-element-property :begin element))
  20183. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20184. (forward-line)
  20185. (point)))
  20186. (end (save-excursion
  20187. (goto-char (org-element-property :end element))
  20188. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20189. (line-beginning-position))))
  20190. (if (or (< (point) beg) (> (point) end)) t
  20191. (fill-region-as-paragraph
  20192. (save-excursion (end-of-line)
  20193. (re-search-backward "^[ \t]*$" beg 'move)
  20194. (line-beginning-position))
  20195. (save-excursion (beginning-of-line)
  20196. (re-search-forward "^[ \t]*$" end 'move)
  20197. (line-beginning-position))
  20198. justify))))
  20199. ;; Fill comments.
  20200. (comment
  20201. (let ((begin (org-element-property :post-affiliated element))
  20202. (end (org-element-property :end element)))
  20203. (when (and (>= (point) begin) (<= (point) end))
  20204. (let ((begin (save-excursion
  20205. (end-of-line)
  20206. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20207. (progn (forward-line) (point))
  20208. begin)))
  20209. (end (save-excursion
  20210. (end-of-line)
  20211. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20212. (1- (line-beginning-position))
  20213. (skip-chars-backward " \r\t\n")
  20214. (line-end-position)))))
  20215. ;; Do not fill comments when at a blank line.
  20216. (when (> end begin)
  20217. (let ((fill-prefix
  20218. (save-excursion
  20219. (beginning-of-line)
  20220. (looking-at "[ \t]*#")
  20221. (let ((comment-prefix (match-string 0)))
  20222. (goto-char (match-end 0))
  20223. (if (looking-at adaptive-fill-regexp)
  20224. (concat comment-prefix (match-string 0))
  20225. (concat comment-prefix " "))))))
  20226. (save-excursion
  20227. (fill-region-as-paragraph begin end justify))))))
  20228. t))
  20229. ;; Ignore every other element.
  20230. (otherwise t)))))
  20231. (defun org-fill-paragraph (&optional justify region)
  20232. "Fill element at point, when applicable.
  20233. This function only applies to comment blocks, comments, example
  20234. blocks and paragraphs. Also, as a special case, re-align table
  20235. when point is at one.
  20236. For convenience, when point is at a plain list, an item or
  20237. a footnote definition, try to fill the first paragraph within.
  20238. If JUSTIFY is non-nil (interactively, with prefix argument),
  20239. justify as well. If `sentence-end-double-space' is non-nil, then
  20240. period followed by one space does not end a sentence, so don't
  20241. break a line there. The variable `fill-column' controls the
  20242. width for filling.
  20243. The REGION argument is non-nil if called interactively; in that
  20244. case, if Transient Mark mode is enabled and the mark is active,
  20245. fill each of the elements in the active region, instead of just
  20246. filling the current element."
  20247. (interactive (progn
  20248. (barf-if-buffer-read-only)
  20249. (list (if current-prefix-arg 'full) t)))
  20250. (cond
  20251. ((and region transient-mark-mode mark-active
  20252. (not (eq (region-beginning) (region-end))))
  20253. (let ((origin (point-marker))
  20254. (start (region-beginning)))
  20255. (unwind-protect
  20256. (progn
  20257. (goto-char (region-end))
  20258. (while (> (point) start)
  20259. (org-backward-paragraph)
  20260. (org-fill-element justify)))
  20261. (goto-char origin)
  20262. (set-marker origin nil))))
  20263. (t (org-fill-element justify))))
  20264. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  20265. (defun org-auto-fill-function ()
  20266. "Auto-fill function."
  20267. ;; Check if auto-filling is meaningful.
  20268. (let ((fc (current-fill-column)))
  20269. (when (and fc (> (current-column) fc))
  20270. (let* ((fill-prefix (org-adaptive-fill-function))
  20271. ;; Enforce empty fill prefix, if required. Otherwise, it
  20272. ;; will be computed again.
  20273. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20274. (when fill-prefix (do-auto-fill))))))
  20275. (defun org-comment-line-break-function (&optional soft)
  20276. "Break line at point and indent, continuing comment if within one.
  20277. The inserted newline is marked hard if variable
  20278. `use-hard-newlines' is true, unless optional argument SOFT is
  20279. non-nil."
  20280. (if soft (insert-and-inherit ?\n) (newline 1))
  20281. (save-excursion (forward-char -1) (delete-horizontal-space))
  20282. (delete-horizontal-space)
  20283. (indent-to-left-margin)
  20284. (insert-before-markers-and-inherit fill-prefix))
  20285. ;;; Fixed Width Areas
  20286. (defun org-toggle-fixed-width ()
  20287. "Toggle fixed-width markup.
  20288. Add or remove fixed-width markup on current line, whenever it
  20289. makes sense. Return an error otherwise.
  20290. If a region is active and if it contains only fixed-width areas
  20291. or blank lines, remove all fixed-width markup in it. If the
  20292. region contains anything else, convert all non-fixed-width lines
  20293. to fixed-width ones.
  20294. Blank lines at the end of the region are ignored unless the
  20295. region only contains such lines."
  20296. (interactive)
  20297. (if (not (org-region-active-p))
  20298. ;; No region:
  20299. ;;
  20300. ;; Remove fixed width marker only in a fixed-with element.
  20301. ;;
  20302. ;; Add fixed width maker in paragraphs, in blank lines after
  20303. ;; elements or at the beginning of a headline or an inlinetask,
  20304. ;; and before any one-line elements (e.g., a clock).
  20305. (progn
  20306. (beginning-of-line)
  20307. (let* ((element (org-element-at-point))
  20308. (type (org-element-type element)))
  20309. (cond
  20310. ((and (eq type 'fixed-width)
  20311. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20312. (replace-match
  20313. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20314. ((and (memq type '(babel-call clock comment diary-sexp headline
  20315. horizontal-rule keyword paragraph
  20316. planning))
  20317. (<= (org-element-property :post-affiliated element) (point)))
  20318. (skip-chars-forward " \t")
  20319. (insert ": "))
  20320. ((and (looking-at-p "[ \t]*$")
  20321. (or (eq type 'inlinetask)
  20322. (save-excursion
  20323. (skip-chars-forward " \r\t\n")
  20324. (<= (org-element-property :end element) (point)))))
  20325. (delete-region (point) (line-end-position))
  20326. (org-indent-line)
  20327. (insert ": "))
  20328. (t (user-error "Cannot insert a fixed-width line here")))))
  20329. ;; Region active.
  20330. (let* ((begin (save-excursion
  20331. (goto-char (region-beginning))
  20332. (line-beginning-position)))
  20333. (end (copy-marker
  20334. (save-excursion
  20335. (goto-char (region-end))
  20336. (unless (eolp) (beginning-of-line))
  20337. (if (save-excursion (re-search-backward "\\S-" begin t))
  20338. (progn (skip-chars-backward " \r\t\n") (point))
  20339. (point)))))
  20340. (all-fixed-width-p
  20341. (catch 'not-all-p
  20342. (save-excursion
  20343. (goto-char begin)
  20344. (skip-chars-forward " \r\t\n")
  20345. (when (eobp) (throw 'not-all-p nil))
  20346. (while (< (point) end)
  20347. (let ((element (org-element-at-point)))
  20348. (if (eq (org-element-type element) 'fixed-width)
  20349. (goto-char (org-element-property :end element))
  20350. (throw 'not-all-p nil))))
  20351. t))))
  20352. (if all-fixed-width-p
  20353. (save-excursion
  20354. (goto-char begin)
  20355. (while (< (point) end)
  20356. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20357. (replace-match
  20358. "" nil nil nil
  20359. (if (= (line-end-position) (match-end 0)) 0 1)))
  20360. (forward-line)))
  20361. (let ((min-ind (point-max)))
  20362. ;; Find minimum indentation across all lines.
  20363. (save-excursion
  20364. (goto-char begin)
  20365. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20366. (setq min-ind 0)
  20367. (catch 'zerop
  20368. (while (< (point) end)
  20369. (unless (looking-at-p "[ \t]*$")
  20370. (let ((ind (org-get-indentation)))
  20371. (setq min-ind (min min-ind ind))
  20372. (when (zerop ind) (throw 'zerop t))))
  20373. (forward-line)))))
  20374. ;; Loop over all lines and add fixed-width markup everywhere
  20375. ;; but in fixed-width lines.
  20376. (save-excursion
  20377. (goto-char begin)
  20378. (while (< (point) end)
  20379. (cond
  20380. ((org-at-heading-p)
  20381. (insert ": ")
  20382. (forward-line)
  20383. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20384. (insert ":")
  20385. (forward-line)))
  20386. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20387. (let* ((element (org-element-at-point))
  20388. (element-end (org-element-property :end element)))
  20389. (if (eq (org-element-type element) 'fixed-width)
  20390. (progn (goto-char element-end)
  20391. (skip-chars-backward " \r\t\n")
  20392. (forward-line))
  20393. (let ((limit (min end element-end)))
  20394. (while (< (point) limit)
  20395. (org-move-to-column min-ind t)
  20396. (insert ": ")
  20397. (forward-line))))))
  20398. (t
  20399. (org-move-to-column min-ind t)
  20400. (insert ": ")
  20401. (forward-line)))))))
  20402. (set-marker end nil))))
  20403. ;;; Blocks
  20404. (defun org-block-map (function &optional start end)
  20405. "Call FUNCTION at the head of all source blocks in the current buffer.
  20406. Optional arguments START and END can be used to limit the range."
  20407. (let ((start (or start (point-min)))
  20408. (end (or end (point-max))))
  20409. (save-excursion
  20410. (goto-char start)
  20411. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20412. (save-excursion
  20413. (save-match-data
  20414. (goto-char (match-beginning 0))
  20415. (funcall function)))))))
  20416. (defun org-next-block (arg &optional backward block-regexp)
  20417. "Jump to the next block.
  20418. With a prefix argument ARG, jump forward ARG many blocks.
  20419. When BACKWARD is non-nil, jump to the previous block.
  20420. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20421. Match data is set according to this regexp when the function
  20422. returns.
  20423. Return point at beginning of the opening line of found block.
  20424. Throw an error if no block is found."
  20425. (interactive "p")
  20426. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20427. (case-fold-search t)
  20428. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20429. (count (or arg 1))
  20430. (origin (point))
  20431. last-element)
  20432. (if backward (beginning-of-line) (end-of-line))
  20433. (while (and (> count 0) (funcall search-fn re nil t))
  20434. (let ((element (save-excursion
  20435. (goto-char (match-beginning 0))
  20436. (save-match-data (org-element-at-point)))))
  20437. (when (and (memq (org-element-type element)
  20438. '(center-block comment-block dynamic-block
  20439. example-block export-block quote-block
  20440. special-block src-block verse-block))
  20441. (<= (match-beginning 0)
  20442. (org-element-property :post-affiliated element)))
  20443. (setq last-element element)
  20444. (cl-decf count))))
  20445. (if (= count 0)
  20446. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20447. (save-match-data (org-show-context)))
  20448. (goto-char origin)
  20449. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20450. (defun org-previous-block (arg &optional block-regexp)
  20451. "Jump to the previous block.
  20452. With a prefix argument ARG, jump backward ARG many source blocks.
  20453. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20454. (interactive "p")
  20455. (org-next-block arg t block-regexp))
  20456. ;;; Comments
  20457. ;; Org comments syntax is quite complex. It requires the entire line
  20458. ;; to be just a comment. Also, even with the right syntax at the
  20459. ;; beginning of line, some elements (e.g., verse-block or
  20460. ;; example-block) don't accept comments. Usual Emacs comment commands
  20461. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20462. ;; Org still relies on `comment-dwim', but cannot trust
  20463. ;; `comment-only-p'. So, `comment-region-function' and
  20464. ;; `uncomment-region-function' both point
  20465. ;; to`org-comment-or-uncomment-region'. Eventually,
  20466. ;; `org-insert-comment' takes care of insertion of comments at the
  20467. ;; beginning of line.
  20468. ;; `org-setup-comments-handling' install comments related variables
  20469. ;; during `org-mode' initialization.
  20470. (defun org-setup-comments-handling ()
  20471. (interactive)
  20472. (setq-local comment-use-syntax nil)
  20473. (setq-local comment-start "# ")
  20474. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20475. (setq-local comment-insert-comment-function 'org-insert-comment)
  20476. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20477. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20478. (defun org-insert-comment ()
  20479. "Insert an empty comment above current line.
  20480. If the line is empty, insert comment at its beginning. When
  20481. point is within a source block, comment according to the related
  20482. major mode."
  20483. (if (let ((element (org-element-at-point)))
  20484. (and (eq (org-element-type element) 'src-block)
  20485. (< (save-excursion
  20486. (goto-char (org-element-property :post-affiliated element))
  20487. (line-end-position))
  20488. (point))
  20489. (> (save-excursion
  20490. (goto-char (org-element-property :end element))
  20491. (skip-chars-backward " \r\t\n")
  20492. (line-beginning-position))
  20493. (point))))
  20494. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20495. (beginning-of-line)
  20496. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20497. (open-line 1))
  20498. (org-indent-line)
  20499. (insert "# ")))
  20500. (defvar comment-empty-lines) ; From newcomment.el.
  20501. (defun org-comment-or-uncomment-region (beg end &rest _)
  20502. "Comment or uncomment each non-blank line in the region.
  20503. Uncomment each non-blank line between BEG and END if it only
  20504. contains commented lines. Otherwise, comment them. If region is
  20505. strictly within a source block, use appropriate comment syntax."
  20506. (if (let ((element (org-element-at-point)))
  20507. (and (eq (org-element-type element) 'src-block)
  20508. (< (save-excursion
  20509. (goto-char (org-element-property :post-affiliated element))
  20510. (line-end-position))
  20511. beg)
  20512. (>= (save-excursion
  20513. (goto-char (org-element-property :end element))
  20514. (skip-chars-backward " \r\t\n")
  20515. (line-beginning-position))
  20516. end)))
  20517. ;; Translate region boundaries for the Org buffer to the source
  20518. ;; buffer.
  20519. (let ((offset (- end beg)))
  20520. (save-excursion
  20521. (goto-char beg)
  20522. (org-babel-do-in-edit-buffer
  20523. (comment-or-uncomment-region (point) (+ offset (point))))))
  20524. (save-restriction
  20525. ;; Restrict region
  20526. (narrow-to-region (save-excursion (goto-char beg)
  20527. (skip-chars-forward " \r\t\n" end)
  20528. (line-beginning-position))
  20529. (save-excursion (goto-char end)
  20530. (skip-chars-backward " \r\t\n" beg)
  20531. (line-end-position)))
  20532. (let ((uncommentp
  20533. ;; UNCOMMENTP is non-nil when every non blank line between
  20534. ;; BEG and END is a comment.
  20535. (save-excursion
  20536. (goto-char (point-min))
  20537. (while (and (not (eobp))
  20538. (let ((element (org-element-at-point)))
  20539. (and (eq (org-element-type element) 'comment)
  20540. (goto-char (min (point-max)
  20541. (org-element-property
  20542. :end element)))))))
  20543. (eobp))))
  20544. (if uncommentp
  20545. ;; Only blank lines and comments in region: uncomment it.
  20546. (save-excursion
  20547. (goto-char (point-min))
  20548. (while (not (eobp))
  20549. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20550. (replace-match "" nil nil nil 1))
  20551. (forward-line)))
  20552. ;; Comment each line in region.
  20553. (let ((min-indent (point-max)))
  20554. ;; First find the minimum indentation across all lines.
  20555. (save-excursion
  20556. (goto-char (point-min))
  20557. (while (and (not (eobp)) (not (zerop min-indent)))
  20558. (unless (looking-at "[ \t]*$")
  20559. (setq min-indent (min min-indent (current-indentation))))
  20560. (forward-line)))
  20561. ;; Then loop over all lines.
  20562. (save-excursion
  20563. (goto-char (point-min))
  20564. (while (not (eobp))
  20565. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20566. ;; Don't get fooled by invisible text (e.g. link path)
  20567. ;; when moving to column MIN-INDENT.
  20568. (let ((buffer-invisibility-spec nil))
  20569. (org-move-to-column min-indent t))
  20570. (insert comment-start))
  20571. (forward-line)))))))))
  20572. (defun org-comment-dwim (_arg)
  20573. "Call the comment command you mean.
  20574. Call `org-toggle-comment' if on a heading, otherwise call
  20575. `comment-dwim', within a source edit buffer if needed."
  20576. (interactive "*P")
  20577. (cond ((org-at-heading-p)
  20578. (call-interactively #'org-toggle-comment))
  20579. ((org-in-src-block-p)
  20580. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20581. (t (call-interactively #'comment-dwim))))
  20582. ;;; Timestamps API
  20583. ;; This section contains tools to operate on, or create, timestamp
  20584. ;; objects, as returned by, e.g. `org-element-context'.
  20585. (defun org-timestamp-from-string (s)
  20586. "Convert Org timestamp S, as a string, into a timestamp object.
  20587. Return nil if S is not a valid timestamp string."
  20588. (when (org-string-nw-p s)
  20589. (with-temp-buffer
  20590. (save-excursion (insert s))
  20591. (org-element-timestamp-parser))))
  20592. (defun org-timestamp-from-time (time &optional with-time inactive)
  20593. "Convert a time value into a timestamp object.
  20594. TIME is an Emacs internal time representation, as returned, e.g.,
  20595. by `current-time'.
  20596. When optional argument WITH-TIME is non-nil, return a timestamp
  20597. object with a time part, i.e., with hours and minutes.
  20598. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20599. return an active timestamp."
  20600. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20601. (org-element-create 'timestamp
  20602. (list :type (if inactive 'inactive 'active)
  20603. :year-start year
  20604. :month-start month
  20605. :day-start day
  20606. :hour-start (and with-time hour)
  20607. :minute-start (and with-time minute)))))
  20608. (defun org-timestamp-to-time (timestamp &optional end)
  20609. "Convert TIMESTAMP object into an Emacs internal time value.
  20610. Use end of date range or time range when END is non-nil.
  20611. Otherwise, use its start."
  20612. (apply #'encode-time
  20613. (cons 0
  20614. (mapcar
  20615. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20616. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20617. '(:minute-start :hour-start :day-start :month-start
  20618. :year-start))))))
  20619. (defun org-timestamp-has-time-p (timestamp)
  20620. "Non-nil when TIMESTAMP has a time specified."
  20621. (org-element-property :hour-start timestamp))
  20622. (defun org-timestamp-format (timestamp format &optional end utc)
  20623. "Format a TIMESTAMP object into a string.
  20624. FORMAT is a format specifier to be passed to
  20625. `format-time-string'.
  20626. When optional argument END is non-nil, use end of date-range or
  20627. time-range, if possible.
  20628. When optional argument UTC is non-nil, time is be expressed as
  20629. Universal Time."
  20630. (format-time-string format (org-timestamp-to-time timestamp end)
  20631. (and utc t)))
  20632. (defun org-timestamp-split-range (timestamp &optional end)
  20633. "Extract a TIMESTAMP object from a date or time range.
  20634. END, when non-nil, means extract the end of the range.
  20635. Otherwise, extract its start.
  20636. Return a new timestamp object."
  20637. (let ((type (org-element-property :type timestamp)))
  20638. (if (memq type '(active inactive diary)) timestamp
  20639. (let ((split-ts (org-element-copy timestamp)))
  20640. ;; Set new type.
  20641. (org-element-put-property
  20642. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20643. ;; Copy start properties over end properties if END is
  20644. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20645. (let ((p-alist '((:minute-start . :minute-end)
  20646. (:hour-start . :hour-end)
  20647. (:day-start . :day-end)
  20648. (:month-start . :month-end)
  20649. (:year-start . :year-end))))
  20650. (dolist (p-cell p-alist)
  20651. (org-element-put-property
  20652. split-ts
  20653. (funcall (if end #'car #'cdr) p-cell)
  20654. (org-element-property
  20655. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20656. ;; Eventually refresh `:raw-value'.
  20657. (org-element-put-property split-ts :raw-value nil)
  20658. (org-element-put-property
  20659. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20660. (defun org-timestamp-translate (timestamp &optional boundary)
  20661. "Translate TIMESTAMP object to custom format.
  20662. Format string is defined in `org-time-stamp-custom-formats',
  20663. which see.
  20664. When optional argument BOUNDARY is non-nil, it is either the
  20665. symbol `start' or `end'. In this case, only translate the
  20666. starting or ending part of TIMESTAMP if it is a date or time
  20667. range. Otherwise, translate both parts.
  20668. Return timestamp as-is if `org-display-custom-times' is nil or if
  20669. it has a `diary' type."
  20670. (let ((type (org-element-property :type timestamp)))
  20671. (if (or (not org-display-custom-times) (eq type 'diary))
  20672. (org-element-interpret-data timestamp)
  20673. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20674. org-time-stamp-custom-formats)))
  20675. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20676. (concat (org-timestamp-format timestamp fmt)
  20677. "--"
  20678. (org-timestamp-format timestamp fmt t))
  20679. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20680. ;;; Other stuff.
  20681. (defvar reftex-docstruct-symbol)
  20682. (defvar org--rds)
  20683. (defun org-reftex-citation ()
  20684. "Use reftex-citation to insert a citation into the buffer.
  20685. This looks for a line like
  20686. #+BIBLIOGRAPHY: foo plain option:-d
  20687. and derives from it that foo.bib is the bibliography file relevant
  20688. for this document. It then installs the necessary environment for RefTeX
  20689. to work in this buffer and calls `reftex-citation' to insert a citation
  20690. into the buffer.
  20691. Export of such citations to both LaTeX and HTML is handled by the contributed
  20692. package ox-bibtex by Taru Karttunen."
  20693. (interactive)
  20694. (let ((reftex-docstruct-symbol 'org--rds)
  20695. org--rds bib)
  20696. (org-with-wide-buffer
  20697. (let ((case-fold-search t)
  20698. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20699. (if (not (save-excursion
  20700. (or (re-search-forward re nil t)
  20701. (re-search-backward re nil t))))
  20702. (user-error "No bibliography defined in file")
  20703. (setq bib (concat (match-string 1) ".bib")
  20704. org--rds (list (list 'bib bib))))))
  20705. (call-interactively 'reftex-citation)))
  20706. ;;;; Functions extending outline functionality
  20707. (defun org-beginning-of-line (&optional n)
  20708. "Go to the beginning of the current visible line.
  20709. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  20710. tags on the first attempt, and only move to after the tags when
  20711. the cursor is already beyond the end of the headline.
  20712. With argument N not nil or 1, move forward N - 1 lines first."
  20713. (interactive "^p")
  20714. (let ((origin (point))
  20715. (special (pcase org-special-ctrl-a/e
  20716. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20717. deactivate-mark)
  20718. ;; First move to a visible line.
  20719. (if (bound-and-true-p visual-line-mode)
  20720. (beginning-of-visual-line n)
  20721. (move-beginning-of-line n)
  20722. ;; `move-beginning-of-line' may leave point after invisible
  20723. ;; characters if line starts with such of these (e.g., with
  20724. ;; a link at column 0). Really move to the beginning of the
  20725. ;; current visible line.
  20726. (beginning-of-line))
  20727. (cond
  20728. ;; No special behavior. Point is already at the beginning of
  20729. ;; a line, logical or visual.
  20730. ((not special))
  20731. ;; `beginning-of-visual-line' left point before logical beginning
  20732. ;; of line: point is at the beginning of a visual line. Bail
  20733. ;; out.
  20734. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20735. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20736. ;; At a headline, special position is before the title, but
  20737. ;; after any TODO keyword or priority cookie.
  20738. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20739. (line-end-position)))
  20740. (bol (point)))
  20741. (if (eq special 'reversed)
  20742. (when (and (= origin bol) (eq last-command this-command))
  20743. (goto-char refpos))
  20744. (when (or (> origin refpos) (= origin bol))
  20745. (goto-char refpos)))))
  20746. ((and (looking-at org-list-full-item-re)
  20747. (memq (org-element-type (save-match-data (org-element-at-point)))
  20748. '(item plain-list)))
  20749. ;; Set special position at first white space character after
  20750. ;; bullet, and check-box, if any.
  20751. (let ((after-bullet
  20752. (let ((box (match-end 3)))
  20753. (cond ((not box) (match-end 1))
  20754. ((eq (char-after box) ?\s) (1+ box))
  20755. (t box)))))
  20756. (if (eq special 'reversed)
  20757. (when (and (= (point) origin) (eq last-command this-command))
  20758. (goto-char after-bullet))
  20759. (when (or (> origin after-bullet) (= (point) origin))
  20760. (goto-char after-bullet)))))
  20761. ;; No special context. Point is already at beginning of line.
  20762. (t nil))))
  20763. (defun org-end-of-line (&optional n)
  20764. "Go to the end of the line, but before ellipsis, if any.
  20765. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  20766. tags on the first attempt, and only move to after the tags when
  20767. the cursor is already beyond the end of the headline.
  20768. With argument N not nil or 1, move forward N - 1 lines first."
  20769. (interactive "^p")
  20770. (let ((origin (point))
  20771. (special (pcase org-special-ctrl-a/e
  20772. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20773. deactivate-mark)
  20774. ;; First move to a visible line.
  20775. (if (bound-and-true-p visual-line-mode)
  20776. (beginning-of-visual-line n)
  20777. (move-beginning-of-line n))
  20778. (cond
  20779. ;; At a headline, with tags.
  20780. ((and special
  20781. (save-excursion
  20782. (beginning-of-line)
  20783. (let ((case-fold-search nil))
  20784. (looking-at org-complex-heading-regexp)))
  20785. (match-end 5))
  20786. (let ((tags (save-excursion
  20787. (goto-char (match-beginning 5))
  20788. (skip-chars-backward " \t")
  20789. (point)))
  20790. (visual-end (and (bound-and-true-p visual-line-mode)
  20791. (save-excursion
  20792. (end-of-visual-line)
  20793. (point)))))
  20794. ;; If `end-of-visual-line' brings us before end of line or
  20795. ;; even tags, i.e., the headline spans over multiple visual
  20796. ;; lines, move there.
  20797. (cond ((and visual-end
  20798. (< visual-end tags)
  20799. (<= origin visual-end))
  20800. (goto-char visual-end))
  20801. ((eq special 'reversed)
  20802. (if (and (= origin (line-end-position))
  20803. (eq this-command last-command))
  20804. (goto-char tags)
  20805. (end-of-line)))
  20806. (t
  20807. (if (or (< origin tags) (= origin (line-end-position)))
  20808. (goto-char tags)
  20809. (end-of-line))))))
  20810. ((bound-and-true-p visual-line-mode)
  20811. (let ((bol (line-beginning-position)))
  20812. (end-of-visual-line)
  20813. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20814. ;; end of a line, backtrack and use `end-of-line' instead.
  20815. (when (/= bol (line-beginning-position))
  20816. (goto-char bol)
  20817. (end-of-line))))
  20818. (t (end-of-line)))))
  20819. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  20820. (define-key org-mode-map "\C-e" 'org-end-of-line)
  20821. (defun org-backward-sentence (&optional _arg)
  20822. "Go to beginning of sentence, or beginning of table field.
  20823. This will call `backward-sentence' or `org-table-beginning-of-field',
  20824. depending on context."
  20825. (interactive)
  20826. (let* ((element (org-element-at-point))
  20827. (contents-begin (org-element-property :contents-begin element))
  20828. (table (org-element-lineage element '(table) t)))
  20829. (if (and table
  20830. (> (point) contents-begin)
  20831. (<= (point) (org-element-property :contents-end table)))
  20832. (call-interactively #'org-table-beginning-of-field)
  20833. (save-restriction
  20834. (when (and contents-begin
  20835. (< (point-min) contents-begin)
  20836. (> (point) contents-begin))
  20837. (narrow-to-region contents-begin
  20838. (org-element-property :contents-end element)))
  20839. (call-interactively #'backward-sentence)))))
  20840. (defun org-forward-sentence (&optional _arg)
  20841. "Go to end of sentence, or end of table field.
  20842. This will call `forward-sentence' or `org-table-end-of-field',
  20843. depending on context."
  20844. (interactive)
  20845. (if (and (org-at-heading-p)
  20846. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20847. (save-restriction
  20848. (narrow-to-region (line-beginning-position) (line-end-position))
  20849. (call-interactively #'forward-sentence))
  20850. (let* ((element (org-element-at-point))
  20851. (contents-end (org-element-property :contents-end element))
  20852. (table (org-element-lineage element '(table) t)))
  20853. (if (and table
  20854. (>= (point) (org-element-property :contents-begin table))
  20855. (< (point) contents-end))
  20856. (call-interactively #'org-table-end-of-field)
  20857. (save-restriction
  20858. (when (and contents-end
  20859. (> (point-max) contents-end)
  20860. ;; Skip blank lines between elements.
  20861. (< (org-element-property :end element)
  20862. (save-excursion (goto-char contents-end)
  20863. (skip-chars-forward " \r\t\n"))))
  20864. (narrow-to-region (org-element-property :contents-begin element)
  20865. contents-end))
  20866. ;; End of heading is considered as the end of a sentence.
  20867. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20868. (call-interactively #'forward-sentence)))))))
  20869. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  20870. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  20871. (defun org-kill-line (&optional _arg)
  20872. "Kill line, to tags or end of line."
  20873. (interactive)
  20874. (cond
  20875. ((or (not org-special-ctrl-k)
  20876. (bolp)
  20877. (not (org-at-heading-p)))
  20878. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  20879. org-ctrl-k-protect-subtree
  20880. (or (eq org-ctrl-k-protect-subtree 'error)
  20881. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20882. (user-error "C-k aborted as it would kill a hidden subtree"))
  20883. (call-interactively
  20884. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20885. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  20886. (kill-region (point) (match-beginning 1))
  20887. (org-set-tags nil t))
  20888. (t (kill-region (point) (point-at-eol)))))
  20889. (define-key org-mode-map "\C-k" 'org-kill-line)
  20890. (defun org-yank (&optional arg)
  20891. "Yank. If the kill is a subtree, treat it specially.
  20892. This command will look at the current kill and check if is a single
  20893. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20894. cursor is at the beginning of a line or after the stars of a currently
  20895. empty headline, then the yank is handled specially. How exactly depends
  20896. on the value of the following variables.
  20897. `org-yank-folded-subtrees'
  20898. By default, this variable is non-nil, which results in
  20899. subtree(s) being folded after insertion, except if doing so
  20900. would swallow text after the yanked text.
  20901. `org-yank-adjusted-subtrees'
  20902. When non-nil (the default value is nil), the subtree will be
  20903. promoted or demoted in order to fit into the local outline tree
  20904. structure, which means that the level will be adjusted so that it
  20905. becomes the smaller one of the two *visible* surrounding headings.
  20906. Any prefix to this command will cause `yank' to be called directly with
  20907. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20908. will just
  20909. plainly yank the text as it is.
  20910. \[1] The test checks if the first non-white line is a heading
  20911. and if there are no other headings with fewer stars."
  20912. (interactive "P")
  20913. (org-yank-generic 'yank arg))
  20914. (defun org-yank-generic (command arg)
  20915. "Perform some yank-like command.
  20916. This function implements the behavior described in the `org-yank'
  20917. documentation. However, it has been generalized to work for any
  20918. interactive command with similar behavior."
  20919. ;; pretend to be command COMMAND
  20920. (setq this-command command)
  20921. (if arg
  20922. (call-interactively command)
  20923. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20924. (and (org-kill-is-subtree-p)
  20925. (or (bolp)
  20926. (and (looking-at "[ \t]*$")
  20927. (string-match
  20928. "\\`\\*+\\'"
  20929. (buffer-substring (point-at-bol) (point)))))))
  20930. swallowp)
  20931. (cond
  20932. ((and subtreep org-yank-folded-subtrees)
  20933. (let ((beg (point))
  20934. end)
  20935. (if (and subtreep org-yank-adjusted-subtrees)
  20936. (org-paste-subtree nil nil 'for-yank)
  20937. (call-interactively command))
  20938. (setq end (point))
  20939. (goto-char beg)
  20940. (when (and (bolp) subtreep
  20941. (not (setq swallowp
  20942. (org-yank-folding-would-swallow-text beg end))))
  20943. (org-with-limited-levels
  20944. (or (looking-at org-outline-regexp)
  20945. (re-search-forward org-outline-regexp-bol end t))
  20946. (while (and (< (point) end) (looking-at org-outline-regexp))
  20947. (outline-hide-subtree)
  20948. (org-cycle-show-empty-lines 'folded)
  20949. (condition-case nil
  20950. (outline-forward-same-level 1)
  20951. (error (goto-char end))))))
  20952. (when swallowp
  20953. (message
  20954. "Inserted text not folded because that would swallow text"))
  20955. (goto-char end)
  20956. (skip-chars-forward " \t\n\r")
  20957. (beginning-of-line 1)
  20958. (push-mark beg 'nomsg)))
  20959. ((and subtreep org-yank-adjusted-subtrees)
  20960. (let ((beg (point-at-bol)))
  20961. (org-paste-subtree nil nil 'for-yank)
  20962. (push-mark beg 'nomsg)))
  20963. (t
  20964. (call-interactively command))))))
  20965. (defun org-yank-folding-would-swallow-text (beg end)
  20966. "Would hide-subtree at BEG swallow any text after END?"
  20967. (let (level)
  20968. (org-with-limited-levels
  20969. (save-excursion
  20970. (goto-char beg)
  20971. (when (or (looking-at org-outline-regexp)
  20972. (re-search-forward org-outline-regexp-bol end t))
  20973. (setq level (org-outline-level)))
  20974. (goto-char end)
  20975. (skip-chars-forward " \t\r\n\v\f")
  20976. (not (or (eobp)
  20977. (and (bolp) (looking-at-p org-outline-regexp)
  20978. (<= (org-outline-level) level))))))))
  20979. (define-key org-mode-map "\C-y" 'org-yank)
  20980. (defun org-back-to-heading (&optional invisible-ok)
  20981. "Call `outline-back-to-heading', but provide a better error message."
  20982. (condition-case nil
  20983. (outline-back-to-heading invisible-ok)
  20984. (error (error "Before first headline at position %d in buffer %s"
  20985. (point) (current-buffer)))))
  20986. (defun org-before-first-heading-p ()
  20987. "Before first heading?"
  20988. (save-excursion
  20989. (end-of-line)
  20990. (null (re-search-backward org-outline-regexp-bol nil t))))
  20991. (defun org-at-heading-p (&optional ignored)
  20992. (outline-on-heading-p t))
  20993. (defun org-in-commented-heading-p (&optional no-inheritance)
  20994. "Non-nil if point is under a commented heading.
  20995. This function also checks ancestors of the current headline,
  20996. unless optional argument NO-INHERITANCE is non-nil."
  20997. (cond
  20998. ((org-before-first-heading-p) nil)
  20999. ((let ((headline (nth 4 (org-heading-components))))
  21000. (and headline
  21001. (let ((case-fold-search nil))
  21002. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21003. headline)))))
  21004. (no-inheritance nil)
  21005. (t
  21006. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21007. (defun org-at-comment-p nil
  21008. "Is cursor in a commented line?"
  21009. (save-excursion
  21010. (save-match-data
  21011. (beginning-of-line)
  21012. (looking-at "^[ \t]*# "))))
  21013. (defun org-at-drawer-p nil
  21014. "Is cursor at a drawer keyword?"
  21015. (save-excursion
  21016. (move-beginning-of-line 1)
  21017. (looking-at org-drawer-regexp)))
  21018. (defun org-at-block-p nil
  21019. "Is cursor at a block keyword?"
  21020. (save-excursion
  21021. (move-beginning-of-line 1)
  21022. (looking-at org-block-regexp)))
  21023. (defun org-point-at-end-of-empty-headline ()
  21024. "If point is at the end of an empty headline, return t, else nil.
  21025. If the heading only contains a TODO keyword, it is still still considered
  21026. empty."
  21027. (let ((case-fold-search nil))
  21028. (and (looking-at "[ \t]*$")
  21029. org-todo-line-regexp
  21030. (save-excursion
  21031. (beginning-of-line)
  21032. (looking-at org-todo-line-regexp)
  21033. (string= (match-string 3) "")))))
  21034. (defun org-at-heading-or-item-p ()
  21035. (or (org-at-heading-p) (org-at-item-p)))
  21036. (defun org-at-target-p ()
  21037. (or (org-in-regexp org-radio-target-regexp)
  21038. (org-in-regexp org-target-regexp)))
  21039. ;; Compatibility alias with Org versions < 7.8.03
  21040. (defalias 'org-on-target-p 'org-at-target-p)
  21041. (defun org-up-heading-all (arg)
  21042. "Move to the heading line of which the present line is a subheading.
  21043. This function considers both visible and invisible heading lines.
  21044. With argument, move up ARG levels."
  21045. (outline-up-heading arg t))
  21046. (defun org-up-heading-safe ()
  21047. "Move to the heading line of which the present line is a subheading.
  21048. This version will not throw an error. It will return the level of the
  21049. headline found, or nil if no higher level is found.
  21050. Also, this function will be a lot faster than `outline-up-heading',
  21051. because it relies on stars being the outline starters. This can really
  21052. make a significant difference in outlines with very many siblings."
  21053. (when (ignore-errors (org-back-to-heading t))
  21054. (let ((level-up (1- (funcall outline-level))))
  21055. (and (> level-up 0)
  21056. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21057. (funcall outline-level)))))
  21058. (defun org-first-sibling-p ()
  21059. "Is this heading the first child of its parents?"
  21060. (interactive)
  21061. (let ((re org-outline-regexp-bol)
  21062. level l)
  21063. (unless (org-at-heading-p t)
  21064. (user-error "Not at a heading"))
  21065. (setq level (funcall outline-level))
  21066. (save-excursion
  21067. (if (not (re-search-backward re nil t))
  21068. t
  21069. (setq l (funcall outline-level))
  21070. (< l level)))))
  21071. (defun org-goto-sibling (&optional previous)
  21072. "Goto the next sibling, even if it is invisible.
  21073. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21074. when a sibling was found. When none is found, return nil and don't
  21075. move point."
  21076. (let ((fun (if previous 're-search-backward 're-search-forward))
  21077. (pos (point))
  21078. (re org-outline-regexp-bol)
  21079. level l)
  21080. (when (ignore-errors (org-back-to-heading t))
  21081. (setq level (funcall outline-level))
  21082. (catch 'exit
  21083. (or previous (forward-char 1))
  21084. (while (funcall fun re nil t)
  21085. (setq l (funcall outline-level))
  21086. (when (< l level) (goto-char pos) (throw 'exit nil))
  21087. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21088. (goto-char pos)
  21089. nil))))
  21090. (defun org-show-siblings ()
  21091. "Show all siblings of the current headline."
  21092. (save-excursion
  21093. (while (org-goto-sibling) (org-flag-heading nil)))
  21094. (save-excursion
  21095. (while (org-goto-sibling 'previous)
  21096. (org-flag-heading nil))))
  21097. (defun org-goto-first-child ()
  21098. "Goto the first child, even if it is invisible.
  21099. Return t when a child was found. Otherwise don't move point and
  21100. return nil."
  21101. (let (level (pos (point)) (re org-outline-regexp-bol))
  21102. (when (ignore-errors (org-back-to-heading t))
  21103. (setq level (outline-level))
  21104. (forward-char 1)
  21105. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21106. (progn (goto-char (match-beginning 0)) t)
  21107. (goto-char pos) nil))))
  21108. (defun org-show-hidden-entry ()
  21109. "Show an entry where even the heading is hidden."
  21110. (save-excursion
  21111. (org-show-entry)))
  21112. (defun org-flag-heading (flag &optional entry)
  21113. "Flag the current heading. FLAG non-nil means make invisible.
  21114. When ENTRY is non-nil, show the entire entry."
  21115. (save-excursion
  21116. (org-back-to-heading t)
  21117. ;; Check if we should show the entire entry
  21118. (if (not entry)
  21119. (org-flag-region
  21120. (line-end-position 0) (line-end-position) flag 'outline)
  21121. (org-show-entry)
  21122. (save-excursion
  21123. (and (outline-next-heading)
  21124. (org-flag-heading nil))))))
  21125. (defun org-get-next-sibling ()
  21126. "Move to next heading of the same level, and return point.
  21127. If there is no such heading, return nil.
  21128. This is like outline-next-sibling, but invisible headings are ok."
  21129. (let ((level (funcall outline-level)))
  21130. (outline-next-heading)
  21131. (while (and (not (eobp)) (> (funcall outline-level) level))
  21132. (outline-next-heading))
  21133. (unless (or (eobp) (< (funcall outline-level) level))
  21134. (point))))
  21135. (defun org-get-last-sibling ()
  21136. "Move to previous heading of the same level, and return point.
  21137. If there is no such heading, return nil."
  21138. (let ((opoint (point))
  21139. (level (funcall outline-level)))
  21140. (outline-previous-heading)
  21141. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21142. (while (and (> (funcall outline-level) level)
  21143. (not (bobp)))
  21144. (outline-previous-heading))
  21145. (unless (< (funcall outline-level) level)
  21146. (point)))))
  21147. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21148. "Goto to the end of a subtree."
  21149. ;; This contains an exact copy of the original function, but it uses
  21150. ;; `org-back-to-heading', to make it work also in invisible
  21151. ;; trees. And is uses an invisible-ok argument.
  21152. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21153. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21154. ;; with many children and grandchildren etc, this can be much faster
  21155. ;; than the outline version.
  21156. (org-back-to-heading invisible-ok)
  21157. (let ((first t)
  21158. (level (funcall outline-level)))
  21159. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21160. ;; A true heading (not a plain list item), in Org
  21161. ;; This means we can easily find the end by looking
  21162. ;; only for the right number of stars. Using a regexp to do
  21163. ;; this is so much faster than using a Lisp loop.
  21164. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21165. (forward-char 1)
  21166. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21167. ;; something else, do it the slow way
  21168. (while (and (not (eobp))
  21169. (or first (> (funcall outline-level) level)))
  21170. (setq first nil)
  21171. (outline-next-heading)))
  21172. (unless to-heading
  21173. (when (memq (preceding-char) '(?\n ?\^M))
  21174. ;; Go to end of line before heading
  21175. (forward-char -1)
  21176. (when (memq (preceding-char) '(?\n ?\^M))
  21177. ;; leave blank line before heading
  21178. (forward-char -1)))))
  21179. (point))
  21180. (defun org-end-of-meta-data (&optional full)
  21181. "Skip planning line and properties drawer in current entry.
  21182. When optional argument FULL is non-nil, also skip empty lines,
  21183. clocking lines and regular drawers at the beginning of the
  21184. entry."
  21185. (org-back-to-heading t)
  21186. (forward-line)
  21187. (when (looking-at-p org-planning-line-re) (forward-line))
  21188. (when (looking-at org-property-drawer-re)
  21189. (goto-char (match-end 0))
  21190. (forward-line))
  21191. (when (and full (not (org-at-heading-p)))
  21192. (catch 'exit
  21193. (let ((end (save-excursion (outline-next-heading) (point)))
  21194. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21195. (while (not (eobp))
  21196. (cond ((looking-at-p org-drawer-regexp)
  21197. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21198. (forward-line)
  21199. (throw 'exit t)))
  21200. ((looking-at-p re) (forward-line))
  21201. (t (throw 'exit t))))))))
  21202. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21203. "Move forward to the ARG'th subheading at same level as this one.
  21204. Stop at the first and last subheadings of a superior heading.
  21205. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21206. non-nil it will also look at invisible ones."
  21207. (interactive "p")
  21208. (let ((backward? (and arg (< arg 0))))
  21209. (if (org-before-first-heading-p)
  21210. (if backward? (goto-char (point-min)) (outline-next-heading))
  21211. (org-back-to-heading invisible-ok)
  21212. (unless backward? (end-of-line)) ;do not match current headline
  21213. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21214. (f (if backward? #'re-search-backward #'re-search-forward))
  21215. (count (if arg (abs arg) 1))
  21216. (result (point)))
  21217. (while (and (> count 0)
  21218. (funcall f org-outline-regexp-bol nil 'move))
  21219. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21220. (cond ((< l level) (setq count 0))
  21221. ((and (= l level)
  21222. (or invisible-ok
  21223. (not (org-invisible-p
  21224. (line-beginning-position)))))
  21225. (cl-decf count)
  21226. (when (= l level) (setq result (point)))))))
  21227. (goto-char result))
  21228. (beginning-of-line))))
  21229. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21230. "Move backward to the ARG'th subheading at same level as this one.
  21231. Stop at the first and last subheadings of a superior heading."
  21232. (interactive "p")
  21233. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21234. (defun org-next-visible-heading (arg)
  21235. "Move to the next visible heading.
  21236. This function wraps `outline-next-visible-heading' with
  21237. `org-with-limited-levels' in order to skip over inline tasks and
  21238. respect customization of `org-odd-levels-only'."
  21239. (interactive "p")
  21240. (org-with-limited-levels
  21241. (outline-next-visible-heading arg)))
  21242. (defun org-previous-visible-heading (arg)
  21243. "Move to the previous visible heading.
  21244. This function wraps `outline-previous-visible-heading' with
  21245. `org-with-limited-levels' in order to skip over inline tasks and
  21246. respect customization of `org-odd-levels-only'."
  21247. (interactive "p")
  21248. (org-with-limited-levels
  21249. (outline-previous-visible-heading arg)))
  21250. (defun org-forward-paragraph ()
  21251. "Move forward to beginning of next paragraph or equivalent.
  21252. The function moves point to the beginning of the next visible
  21253. structural element, which can be a paragraph, a table, a list
  21254. item, etc. It also provides some special moves for convenience:
  21255. - On an affiliated keyword, jump to the beginning of the
  21256. relative element.
  21257. - On an item or a footnote definition, move to the second
  21258. element inside, if any.
  21259. - On a table or a property drawer, jump after it.
  21260. - On a verse or source block, stop after blank lines."
  21261. (interactive)
  21262. (unless (eobp)
  21263. (let* ((deactivate-mark nil)
  21264. (element (org-element-at-point))
  21265. (type (org-element-type element))
  21266. (post-affiliated (org-element-property :post-affiliated element))
  21267. (contents-begin (org-element-property :contents-begin element))
  21268. (contents-end (org-element-property :contents-end element))
  21269. (end (let ((end (org-element-property :end element)) (parent element))
  21270. (while (and (setq parent (org-element-property :parent parent))
  21271. (= (org-element-property :contents-end parent) end))
  21272. (setq end (org-element-property :end parent)))
  21273. end)))
  21274. (cond ((not element)
  21275. (skip-chars-forward " \r\t\n")
  21276. (or (eobp) (beginning-of-line)))
  21277. ;; On affiliated keywords, move to element's beginning.
  21278. ((< (point) post-affiliated)
  21279. (goto-char post-affiliated))
  21280. ;; At a table row, move to the end of the table. Similarly,
  21281. ;; at a node property, move to the end of the property
  21282. ;; drawer.
  21283. ((memq type '(node-property table-row))
  21284. (goto-char (org-element-property
  21285. :end (org-element-property :parent element))))
  21286. ((memq type '(property-drawer table)) (goto-char end))
  21287. ;; Consider blank lines as separators in verse and source
  21288. ;; blocks to ease editing.
  21289. ((memq type '(src-block verse-block))
  21290. (when (eq type 'src-block)
  21291. (setq contents-end
  21292. (save-excursion (goto-char end)
  21293. (skip-chars-backward " \r\t\n")
  21294. (line-beginning-position))))
  21295. (beginning-of-line)
  21296. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21297. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21298. (goto-char end)
  21299. (skip-chars-forward " \r\t\n")
  21300. (if (= (point) contents-end) (goto-char end)
  21301. (beginning-of-line))))
  21302. ;; With no contents, just skip element.
  21303. ((not contents-begin) (goto-char end))
  21304. ;; If contents are invisible, skip the element altogether.
  21305. ((org-invisible-p (line-end-position))
  21306. (cl-case type
  21307. (headline
  21308. (org-with-limited-levels (outline-next-visible-heading 1)))
  21309. ;; At a plain list, make sure we move to the next item
  21310. ;; instead of skipping the whole list.
  21311. (plain-list (forward-char)
  21312. (org-forward-paragraph))
  21313. (otherwise (goto-char end))))
  21314. ((>= (point) contents-end) (goto-char end))
  21315. ((>= (point) contents-begin)
  21316. ;; This can only happen on paragraphs and plain lists.
  21317. (cl-case type
  21318. (paragraph (goto-char end))
  21319. ;; At a plain list, try to move to second element in
  21320. ;; first item, if possible.
  21321. (plain-list (end-of-line)
  21322. (org-forward-paragraph))))
  21323. ;; When contents start on the middle of a line (e.g. in
  21324. ;; items and footnote definitions), try to reach first
  21325. ;; element starting after current line.
  21326. ((> (line-end-position) contents-begin)
  21327. (end-of-line)
  21328. (org-forward-paragraph))
  21329. (t (goto-char contents-begin))))))
  21330. (defun org-backward-paragraph ()
  21331. "Move backward to start of previous paragraph or equivalent.
  21332. The function moves point to the beginning of the current
  21333. structural element, which can be a paragraph, a table, a list
  21334. item, etc., or to the beginning of the previous visible one if
  21335. point is already there. It also provides some special moves for
  21336. convenience:
  21337. - On an affiliated keyword, jump to the first one.
  21338. - On a table or a property drawer, move to its beginning.
  21339. - On comment, example, export, src and verse blocks, stop
  21340. before blank lines."
  21341. (interactive)
  21342. (unless (bobp)
  21343. (let* ((deactivate-mark nil)
  21344. (element (org-element-at-point))
  21345. (type (org-element-type element))
  21346. (contents-end (org-element-property :contents-end element))
  21347. (post-affiliated (org-element-property :post-affiliated element))
  21348. (begin (org-element-property :begin element))
  21349. (special? ;blocks handled specially
  21350. (memq type '(comment-block example-block export-block src-block
  21351. verse-block)))
  21352. (contents-begin
  21353. (if special?
  21354. ;; These types have no proper contents. Fake line
  21355. ;; below the block opening line as contents beginning.
  21356. (save-excursion (goto-char begin) (line-beginning-position 2))
  21357. (org-element-property :contents-begin element))))
  21358. (cond
  21359. ((not element) (goto-char (point-min)))
  21360. ((= (point) begin)
  21361. (backward-char)
  21362. (org-backward-paragraph))
  21363. ((<= (point) post-affiliated) (goto-char begin))
  21364. ;; Special behavior: on a table or a property drawer, move to
  21365. ;; its beginning.
  21366. ((memq type '(node-property table-row))
  21367. (goto-char (org-element-property
  21368. :post-affiliated (org-element-property :parent element))))
  21369. (special?
  21370. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21371. ;; Inside a verse block, see blank lines as paragraph
  21372. ;; separators.
  21373. (let ((origin (point)))
  21374. (skip-chars-backward " \r\t\n" contents-begin)
  21375. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21376. (skip-chars-forward " \r\t\n" origin)
  21377. (if (= (point) origin) (goto-char contents-begin)
  21378. (beginning-of-line))))))
  21379. ((eq type 'paragraph) (goto-char contents-begin)
  21380. ;; When at first paragraph in an item or a footnote definition,
  21381. ;; move directly to beginning of line.
  21382. (let ((parent-contents
  21383. (org-element-property
  21384. :contents-begin (org-element-property :parent element))))
  21385. (when (and parent-contents (= parent-contents contents-begin))
  21386. (beginning-of-line))))
  21387. ;; At the end of a greater element, move to the beginning of
  21388. ;; the last element within.
  21389. ((and contents-end (>= (point) contents-end))
  21390. (goto-char (1- contents-end))
  21391. (org-backward-paragraph))
  21392. (t (goto-char (or post-affiliated begin))))
  21393. ;; Ensure we never leave point invisible.
  21394. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21395. (defun org-forward-element ()
  21396. "Move forward by one element.
  21397. Move to the next element at the same level, when possible."
  21398. (interactive)
  21399. (cond ((eobp) (user-error "Cannot move further down"))
  21400. ((org-with-limited-levels (org-at-heading-p))
  21401. (let ((origin (point)))
  21402. (goto-char (org-end-of-subtree nil t))
  21403. (unless (org-with-limited-levels (org-at-heading-p))
  21404. (goto-char origin)
  21405. (user-error "Cannot move further down"))))
  21406. (t
  21407. (let* ((elem (org-element-at-point))
  21408. (end (org-element-property :end elem))
  21409. (parent (org-element-property :parent elem)))
  21410. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21411. (goto-char (org-element-property :end parent)))
  21412. ((integer-or-marker-p end) (goto-char end))
  21413. (t (message "No element at point")))))))
  21414. (defun org-backward-element ()
  21415. "Move backward by one element.
  21416. Move to the previous element at the same level, when possible."
  21417. (interactive)
  21418. (cond ((bobp) (user-error "Cannot move further up"))
  21419. ((org-with-limited-levels (org-at-heading-p))
  21420. ;; At a headline, move to the previous one, if any, or stay
  21421. ;; here.
  21422. (let ((origin (point)))
  21423. (org-with-limited-levels (org-backward-heading-same-level 1))
  21424. ;; When current headline has no sibling above, move to its
  21425. ;; parent.
  21426. (when (= (point) origin)
  21427. (or (org-with-limited-levels (org-up-heading-safe))
  21428. (progn (goto-char origin)
  21429. (user-error "Cannot move further up"))))))
  21430. (t
  21431. (let* ((elem (org-element-at-point))
  21432. (beg (org-element-property :begin elem)))
  21433. (cond
  21434. ;; Move to beginning of current element if point isn't
  21435. ;; there already.
  21436. ((null beg) (message "No element at point"))
  21437. ((/= (point) beg) (goto-char beg))
  21438. (t (goto-char beg)
  21439. (skip-chars-backward " \r\t\n")
  21440. (unless (bobp)
  21441. (let ((prev (org-element-at-point)))
  21442. (goto-char (org-element-property :begin prev))
  21443. (while (and (setq prev (org-element-property :parent prev))
  21444. (<= (org-element-property :end prev) beg))
  21445. (goto-char (org-element-property :begin prev)))))))))))
  21446. (defun org-up-element ()
  21447. "Move to upper element."
  21448. (interactive)
  21449. (if (org-with-limited-levels (org-at-heading-p))
  21450. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21451. (let* ((elem (org-element-at-point))
  21452. (parent (org-element-property :parent elem)))
  21453. (if parent (goto-char (org-element-property :begin parent))
  21454. (if (org-with-limited-levels (org-before-first-heading-p))
  21455. (user-error "No surrounding element")
  21456. (org-with-limited-levels (org-back-to-heading)))))))
  21457. (defun org-down-element ()
  21458. "Move to inner element."
  21459. (interactive)
  21460. (let ((element (org-element-at-point)))
  21461. (cond
  21462. ((memq (org-element-type element) '(plain-list table))
  21463. (goto-char (org-element-property :contents-begin element))
  21464. (forward-char))
  21465. ((memq (org-element-type element) org-element-greater-elements)
  21466. ;; If contents are hidden, first disclose them.
  21467. (when (org-invisible-p (line-end-position)) (org-cycle))
  21468. (goto-char (or (org-element-property :contents-begin element)
  21469. (user-error "No content for this element"))))
  21470. (t (user-error "No inner element")))))
  21471. (defun org-drag-element-backward ()
  21472. "Move backward element at point."
  21473. (interactive)
  21474. (let ((elem (or (org-element-at-point)
  21475. (user-error "No element at point"))))
  21476. (if (eq (org-element-type elem) 'headline)
  21477. ;; Preserve point when moving a whole tree, even if point was
  21478. ;; on blank lines below the headline.
  21479. (let ((offset (skip-chars-backward " \t\n")))
  21480. (unwind-protect (org-move-subtree-up)
  21481. (forward-char (- offset))))
  21482. (let ((prev-elem
  21483. (save-excursion
  21484. (goto-char (org-element-property :begin elem))
  21485. (skip-chars-backward " \r\t\n")
  21486. (unless (bobp)
  21487. (let* ((beg (org-element-property :begin elem))
  21488. (prev (org-element-at-point))
  21489. (up prev))
  21490. (while (and (setq up (org-element-property :parent up))
  21491. (<= (org-element-property :end up) beg))
  21492. (setq prev up))
  21493. prev)))))
  21494. ;; Error out if no previous element or previous element is
  21495. ;; a parent of the current one.
  21496. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21497. (user-error "Cannot drag element backward")
  21498. (let ((pos (point)))
  21499. (org-element-swap-A-B prev-elem elem)
  21500. (goto-char (+ (org-element-property :begin prev-elem)
  21501. (- pos (org-element-property :begin elem))))))))))
  21502. (defun org-drag-element-forward ()
  21503. "Move forward element at point."
  21504. (interactive)
  21505. (let* ((pos (point))
  21506. (elem (or (org-element-at-point)
  21507. (user-error "No element at point"))))
  21508. (when (= (point-max) (org-element-property :end elem))
  21509. (user-error "Cannot drag element forward"))
  21510. (goto-char (org-element-property :end elem))
  21511. (let ((next-elem (org-element-at-point)))
  21512. (when (or (org-element-nested-p elem next-elem)
  21513. (and (eq (org-element-type next-elem) 'headline)
  21514. (not (eq (org-element-type elem) 'headline))))
  21515. (goto-char pos)
  21516. (user-error "Cannot drag element forward"))
  21517. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21518. ;; body's length (without final blanks) and by the length of
  21519. ;; blanks between ELEM and NEXT-ELEM.
  21520. (let ((size-next (- (save-excursion
  21521. (goto-char (org-element-property :end next-elem))
  21522. (skip-chars-backward " \r\t\n")
  21523. (forward-line)
  21524. ;; Small correction if buffer doesn't end
  21525. ;; with a newline character.
  21526. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21527. (org-element-property :begin next-elem)))
  21528. (size-blank (- (org-element-property :end elem)
  21529. (save-excursion
  21530. (goto-char (org-element-property :end elem))
  21531. (skip-chars-backward " \r\t\n")
  21532. (forward-line)
  21533. (point)))))
  21534. (org-element-swap-A-B elem next-elem)
  21535. (goto-char (+ pos size-next size-blank))))))
  21536. (defun org-drag-line-forward (arg)
  21537. "Drag the line at point ARG lines forward."
  21538. (interactive "p")
  21539. (dotimes (_ (abs arg))
  21540. (let ((c (current-column)))
  21541. (if (< 0 arg)
  21542. (progn
  21543. (beginning-of-line 2)
  21544. (transpose-lines 1)
  21545. (beginning-of-line 0))
  21546. (transpose-lines 1)
  21547. (beginning-of-line -1))
  21548. (org-move-to-column c))))
  21549. (defun org-drag-line-backward (arg)
  21550. "Drag the line at point ARG lines backward."
  21551. (interactive "p")
  21552. (org-drag-line-forward (- arg)))
  21553. (defun org-mark-element ()
  21554. "Put point at beginning of this element, mark at end.
  21555. Interactively, if this command is repeated or (in Transient Mark
  21556. mode) if the mark is active, it marks the next element after the
  21557. ones already marked."
  21558. (interactive)
  21559. (let (deactivate-mark)
  21560. (if (and (called-interactively-p 'any)
  21561. (or (and (eq last-command this-command) (mark t))
  21562. (and transient-mark-mode mark-active)))
  21563. (set-mark
  21564. (save-excursion
  21565. (goto-char (mark))
  21566. (goto-char (org-element-property :end (org-element-at-point)))))
  21567. (let ((element (org-element-at-point)))
  21568. (end-of-line)
  21569. (push-mark (org-element-property :end element) t t)
  21570. (goto-char (org-element-property :begin element))))))
  21571. (defun org-narrow-to-element ()
  21572. "Narrow buffer to current element."
  21573. (interactive)
  21574. (let ((elem (org-element-at-point)))
  21575. (cond
  21576. ((eq (car elem) 'headline)
  21577. (narrow-to-region
  21578. (org-element-property :begin elem)
  21579. (org-element-property :end elem)))
  21580. ((memq (car elem) org-element-greater-elements)
  21581. (narrow-to-region
  21582. (org-element-property :contents-begin elem)
  21583. (org-element-property :contents-end elem)))
  21584. (t
  21585. (narrow-to-region
  21586. (org-element-property :begin elem)
  21587. (org-element-property :end elem))))))
  21588. (defun org-transpose-element ()
  21589. "Transpose current and previous elements, keeping blank lines between.
  21590. Point is moved after both elements."
  21591. (interactive)
  21592. (org-skip-whitespace)
  21593. (let ((end (org-element-property :end (org-element-at-point))))
  21594. (org-drag-element-backward)
  21595. (goto-char end)))
  21596. (defun org-unindent-buffer ()
  21597. "Un-indent the visible part of the buffer.
  21598. Relative indentation (between items, inside blocks, etc.) isn't
  21599. modified."
  21600. (interactive)
  21601. (unless (eq major-mode 'org-mode)
  21602. (user-error "Cannot un-indent a buffer not in Org mode"))
  21603. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21604. (unindent-tree
  21605. (lambda (contents)
  21606. (dolist (element (reverse contents))
  21607. (if (memq (org-element-type element) '(headline section))
  21608. (funcall unindent-tree (org-element-contents element))
  21609. (save-excursion
  21610. (save-restriction
  21611. (narrow-to-region
  21612. (org-element-property :begin element)
  21613. (org-element-property :end element))
  21614. (org-do-remove-indentation))))))))
  21615. (funcall unindent-tree (org-element-contents parse-tree))))
  21616. (defun org-make-options-regexp (kwds &optional extra)
  21617. "Make a regular expression for keyword lines.
  21618. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21619. when non-nil, is a regexp matching keywords names."
  21620. (concat "^[ \t]*#\\+\\("
  21621. (regexp-opt kwds)
  21622. (and extra (concat (and kwds "\\|") extra))
  21623. "\\):[ \t]*\\(.*\\)"))
  21624. ;;; Finish up
  21625. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21626. (lambda () (add-hook 'change-major-mode-hook
  21627. 'org-show-all 'append 'local)))
  21628. (provide 'org)
  21629. (run-hooks 'org-load-hook)
  21630. ;;; org.el ends here