org.el 896 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.1.10
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (require 'org-macs)
  84. (require 'org-compat)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  100. (declare-function org-add-archive-files "org-archive" (files))
  101. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  102. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  103. (declare-function org-agenda-redo "org-agenda" (&optional all))
  104. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  105. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  106. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  107. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  108. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  109. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  110. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  111. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  112. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  113. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  114. (declare-function org-clock-update-time-maybe "org-clock" ())
  115. (declare-function org-clocking-buffer "org-clock" ())
  116. (declare-function org-clocktable-shift "org-clock" (dir n))
  117. (declare-function
  118. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  119. (declare-function org-element-at-point "org-element" ())
  120. (declare-function org-element-cache-refresh "org-element" (pos))
  121. (declare-function org-element-cache-reset "org-element" (&optional all))
  122. (declare-function org-element-contents "org-element" (element))
  123. (declare-function org-element-context "org-element" (&optional element))
  124. (declare-function org-element-copy "org-element" (datum))
  125. (declare-function org-element-interpret-data "org-element" (data))
  126. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  127. (declare-function org-element-link-parser "org-element" ())
  128. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  129. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  130. (declare-function org-element-property "org-element" (property element))
  131. (declare-function org-element-put-property "org-element" (element property value))
  132. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  133. (declare-function org-element-type "org-element" (element))
  134. (declare-function org-element-update-syntax "org-element" ())
  135. (declare-function org-id-find-id-file "org-id" (id))
  136. (declare-function org-id-get-create "org-id" (&optional force))
  137. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  138. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  139. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  140. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  141. (declare-function org-table-align "org-table" ())
  142. (declare-function org-table-begin "org-table" (&optional table-type))
  143. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  144. (declare-function org-table-blank-field "org-table" ())
  145. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  146. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  147. (declare-function org-table-cut-region "org-table" (beg end))
  148. (declare-function org-table-edit-field "org-table" (arg))
  149. (declare-function org-table-end "org-table" (&optional table-type))
  150. (declare-function org-table-end-of-field "org-table" (&optional n))
  151. (declare-function org-table-insert-row "org-table" (&optional arg))
  152. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  153. (declare-function org-table-maybe-eval-formula "org-table" ())
  154. (declare-function org-table-maybe-recalculate-line "org-table" ())
  155. (declare-function org-table-next-row "org-table" ())
  156. (declare-function org-table-paste-rectangle "org-table" ())
  157. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  158. (declare-function
  159. org-table-sort-lines "org-table"
  160. (&optional with-case sorting-type getkey-func compare-func interactive?))
  161. (declare-function org-table-shrink "org-table" (&optional begin end))
  162. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  163. (declare-function org-table-wrap-region "org-table" (arg))
  164. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  165. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  166. (declare-function orgtbl-mode "org-table" (&optional arg))
  167. (declare-function org-export-get-backend "ox" (name))
  168. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  169. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  170. (defvar ffap-url-regexp)
  171. (defvar org-element-paragraph-separate)
  172. ;; load languages based on value of `org-babel-load-languages'
  173. (defvar org-babel-load-languages)
  174. ;;;###autoload
  175. (defun org-babel-do-load-languages (sym value)
  176. "Load the languages defined in `org-babel-load-languages'."
  177. (set-default sym value)
  178. (dolist (pair org-babel-load-languages)
  179. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  180. (if active
  181. (require (intern (concat "ob-" lang)))
  182. (funcall 'fmakunbound
  183. (intern (concat "org-babel-execute:" lang)))
  184. (funcall 'fmakunbound
  185. (intern (concat "org-babel-expand-body:" lang)))))))
  186. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  187. ;;;###autoload
  188. (defun org-babel-load-file (file &optional compile)
  189. "Load Emacs Lisp source code blocks in the Org FILE.
  190. This function exports the source code using `org-babel-tangle'
  191. and then loads the resulting file using `load-file'. With prefix
  192. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  193. file to byte-code before it is loaded."
  194. (interactive "fFile to load: \nP")
  195. (let* ((age (lambda (file)
  196. (float-time
  197. (time-subtract (current-time)
  198. (nth 5 (or (file-attributes (file-truename file))
  199. (file-attributes file)))))))
  200. (base-name (file-name-sans-extension file))
  201. (exported-file (concat base-name ".el")))
  202. ;; tangle if the Org file is newer than the elisp file
  203. (unless (and (file-exists-p exported-file)
  204. (> (funcall age file) (funcall age exported-file)))
  205. ;; Tangle-file traversal returns reversed list of tangled files
  206. ;; and we want to evaluate the first target.
  207. (setq exported-file
  208. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  209. (message "%s %s"
  210. (if compile
  211. (progn (byte-compile-file exported-file 'load)
  212. "Compiled and loaded")
  213. (progn (load-file exported-file) "Loaded"))
  214. exported-file)))
  215. (defcustom org-babel-load-languages '((emacs-lisp . t))
  216. "Languages which can be evaluated in Org buffers.
  217. This list can be used to load support for any of the languages
  218. below, note that each language will depend on a different set of
  219. system executables and/or Emacs modes. When a language is
  220. \"loaded\", then code blocks in that language can be evaluated
  221. with `org-babel-execute-src-block' bound by default to C-c
  222. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  223. be set to remove code block evaluation from the C-c C-c
  224. keybinding. By default only Emacs Lisp (which has no
  225. requirements) is loaded."
  226. :group 'org-babel
  227. :set 'org-babel-do-load-languages
  228. :version "24.1"
  229. :type '(alist :tag "Babel Languages"
  230. :key-type
  231. (choice
  232. (const :tag "Awk" awk)
  233. (const :tag "C" C)
  234. (const :tag "R" R)
  235. (const :tag "Asymptote" asymptote)
  236. (const :tag "Calc" calc)
  237. (const :tag "Clojure" clojure)
  238. (const :tag "CSS" css)
  239. (const :tag "Ditaa" ditaa)
  240. (const :tag "Dot" dot)
  241. (const :tag "Ebnf2ps" ebnf2ps)
  242. (const :tag "Emacs Lisp" emacs-lisp)
  243. (const :tag "Forth" forth)
  244. (const :tag "Fortran" fortran)
  245. (const :tag "Gnuplot" gnuplot)
  246. (const :tag "Haskell" haskell)
  247. (const :tag "hledger" hledger)
  248. (const :tag "IO" io)
  249. (const :tag "J" J)
  250. (const :tag "Java" java)
  251. (const :tag "Javascript" js)
  252. (const :tag "LaTeX" latex)
  253. (const :tag "Ledger" ledger)
  254. (const :tag "Lilypond" lilypond)
  255. (const :tag "Lisp" lisp)
  256. (const :tag "Makefile" makefile)
  257. (const :tag "Maxima" maxima)
  258. (const :tag "Matlab" matlab)
  259. (const :tag "Mscgen" mscgen)
  260. (const :tag "Ocaml" ocaml)
  261. (const :tag "Octave" octave)
  262. (const :tag "Org" org)
  263. (const :tag "Perl" perl)
  264. (const :tag "Pico Lisp" picolisp)
  265. (const :tag "PlantUML" plantuml)
  266. (const :tag "Python" python)
  267. (const :tag "Ruby" ruby)
  268. (const :tag "Sass" sass)
  269. (const :tag "Scala" scala)
  270. (const :tag "Scheme" scheme)
  271. (const :tag "Screen" screen)
  272. (const :tag "Shell Script" shell)
  273. (const :tag "Shen" shen)
  274. (const :tag "Sql" sql)
  275. (const :tag "Sqlite" sqlite)
  276. (const :tag "Stan" stan)
  277. (const :tag "Vala" vala))
  278. :value-type (boolean :tag "Activate" :value t)))
  279. ;;;; Customization variables
  280. (defcustom org-clone-delete-id nil
  281. "Remove ID property of clones of a subtree.
  282. When non-nil, clones of a subtree don't inherit the ID property.
  283. Otherwise they inherit the ID property with a new unique
  284. identifier."
  285. :type 'boolean
  286. :version "24.1"
  287. :group 'org-id)
  288. ;;; Version
  289. (org-check-version)
  290. ;;;###autoload
  291. (defun org-version (&optional here full message)
  292. "Show the Org version.
  293. Interactively, or when MESSAGE is non-nil, show it in echo area.
  294. With prefix argument, or when HERE is non-nil, insert it at point.
  295. In non-interactive uses, a reduced version string is output unless
  296. FULL is given."
  297. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  298. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  299. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  300. (load-suffixes (list ".el"))
  301. (org-install-dir
  302. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  303. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  304. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  305. (let* ((load-suffixes save-load-suffixes)
  306. (release (org-release))
  307. (git-version (org-git-version))
  308. (version (format "Org mode version %s (%s @ %s)"
  309. release
  310. git-version
  311. (if org-install-dir
  312. (if (string= org-dir org-install-dir)
  313. org-install-dir
  314. (concat "mixed installation! "
  315. org-install-dir
  316. " and "
  317. org-dir))
  318. "org-loaddefs.el can not be found!")))
  319. (version1 (if full version release)))
  320. (when here (insert version1))
  321. (when message (message "%s" version1))
  322. version1)))
  323. (defconst org-version (org-version))
  324. ;;; Syntax Constants
  325. ;;;; Block
  326. (defconst org-block-regexp
  327. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  328. "Regular expression for hiding blocks.")
  329. (defconst org-dblock-start-re
  330. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  331. "Matches the start line of a dynamic block, with parameters.")
  332. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  333. "Matches the end of a dynamic block.")
  334. ;;;; Clock and Planning
  335. (defconst org-clock-string "CLOCK:"
  336. "String used as prefix for timestamps clocking work hours on an item.")
  337. (defvar org-closed-string "CLOSED:"
  338. "String used as the prefix for timestamps logging closing a TODO entry.")
  339. (defvar org-deadline-string "DEADLINE:"
  340. "String to mark deadline entries.
  341. \\<org-mode-map>
  342. A deadline is this string, followed by a time stamp. It must be
  343. a word, terminated by a colon. You can insert a schedule keyword
  344. and a timestamp with `\\[org-deadline]'.")
  345. (defvar org-scheduled-string "SCHEDULED:"
  346. "String to mark scheduled TODO entries.
  347. \\<org-mode-map>
  348. A schedule is this string, followed by a time stamp. It must be
  349. a word, terminated by a colon. You can insert a schedule keyword
  350. and a timestamp with `\\[org-schedule]'.")
  351. (defconst org-ds-keyword-length
  352. (+ 2
  353. (apply #'max
  354. (mapcar #'length
  355. (list org-deadline-string org-scheduled-string
  356. org-clock-string org-closed-string))))
  357. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  358. (defconst org-planning-line-re
  359. (concat "^[ \t]*"
  360. (regexp-opt
  361. (list org-closed-string org-deadline-string org-scheduled-string)
  362. t))
  363. "Matches a line with planning info.
  364. Matched keyword is in group 1.")
  365. (defconst org-clock-line-re
  366. (concat "^[ \t]*" org-clock-string)
  367. "Matches a line with clock info.")
  368. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  369. "Matches the DEADLINE keyword.")
  370. (defconst org-deadline-time-regexp
  371. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  372. "Matches the DEADLINE keyword together with a time stamp.")
  373. (defconst org-deadline-time-hour-regexp
  374. (concat "\\<" org-deadline-string
  375. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  376. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  377. (defconst org-deadline-line-regexp
  378. (concat "\\<\\(" org-deadline-string "\\).*")
  379. "Matches the DEADLINE keyword and the rest of the line.")
  380. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  381. "Matches the SCHEDULED keyword.")
  382. (defconst org-scheduled-time-regexp
  383. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  384. "Matches the SCHEDULED keyword together with a time stamp.")
  385. (defconst org-scheduled-time-hour-regexp
  386. (concat "\\<" org-scheduled-string
  387. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  388. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  389. (defconst org-closed-time-regexp
  390. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  391. "Matches the CLOSED keyword together with a time stamp.")
  392. (defconst org-keyword-time-regexp
  393. (concat "\\<"
  394. (regexp-opt
  395. (list org-scheduled-string org-deadline-string org-closed-string
  396. org-clock-string)
  397. t)
  398. " *[[<]\\([^]>]+\\)[]>]")
  399. "Matches any of the 4 keywords, together with the time stamp.")
  400. (defconst org-keyword-time-not-clock-regexp
  401. (concat
  402. "\\<"
  403. (regexp-opt
  404. (list org-scheduled-string org-deadline-string org-closed-string) t)
  405. " *[[<]\\([^]>]+\\)[]>]")
  406. "Matches any of the 3 keywords, together with the time stamp.")
  407. (defconst org-maybe-keyword-time-regexp
  408. (concat "\\(\\<"
  409. (regexp-opt
  410. (list org-scheduled-string org-deadline-string org-closed-string
  411. org-clock-string)
  412. t)
  413. "\\)?"
  414. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  415. "\\|"
  416. "<%%([^\r\n>]*>\\)")
  417. "Matches a timestamp, possibly preceded by a keyword.")
  418. (defconst org-all-time-keywords
  419. (mapcar (lambda (w) (substring w 0 -1))
  420. (list org-scheduled-string org-deadline-string
  421. org-clock-string org-closed-string))
  422. "List of time keywords.")
  423. ;;;; Drawer
  424. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  425. "Matches first or last line of a hidden block.
  426. Group 1 contains drawer's name or \"END\".")
  427. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  428. "Regular expression matching the first line of a property drawer.")
  429. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  430. "Regular expression matching the last line of a property drawer.")
  431. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  432. "Regular expression matching the first line of a clock drawer.")
  433. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  434. "Regular expression matching the last line of a clock drawer.")
  435. (defconst org-property-drawer-re
  436. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  437. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  438. "[ \t]*:END:[ \t]*$")
  439. "Matches an entire property drawer.")
  440. (defconst org-clock-drawer-re
  441. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  442. org-clock-drawer-end-re "\\)\n?")
  443. "Matches an entire clock drawer.")
  444. ;;;; Headline
  445. (defconst org-heading-keyword-regexp-format
  446. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  447. "Printf format for a regexp matching a headline with some keyword.
  448. This regexp will match the headline of any node which has the
  449. exact keyword that is put into the format. The keyword isn't in
  450. any group by default, but the stars and the body are.")
  451. (defconst org-heading-keyword-maybe-regexp-format
  452. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  453. "Printf format for a regexp matching a headline, possibly with some keyword.
  454. This regexp can match any headline with the specified keyword, or
  455. without a keyword. The keyword isn't in any group by default,
  456. but the stars and the body are.")
  457. (defconst org-archive-tag "ARCHIVE"
  458. "The tag that marks a subtree as archived.
  459. An archived subtree does not open during visibility cycling, and does
  460. not contribute to the agenda listings.")
  461. (defconst org-tag-line-re
  462. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  463. "Regexp matching tags in a headline.
  464. Tags are stored in match group 1. Match group 2 stores the tags
  465. without the enclosing colons.")
  466. (eval-and-compile
  467. (defconst org-comment-string "COMMENT"
  468. "Entries starting with this keyword will never be exported.
  469. \\<org-mode-map>
  470. An entry can be toggled between COMMENT and normal with
  471. `\\[org-toggle-comment]'."))
  472. ;;;; LaTeX Environments and Fragments
  473. (defconst org-latex-regexps
  474. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  475. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  476. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  477. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  478. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  479. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  480. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  481. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  482. "Regular expressions for matching embedded LaTeX.")
  483. ;;;; Node Property
  484. (defconst org-effort-property "Effort"
  485. "The property that is being used to keep track of effort estimates.
  486. Effort estimates given in this property need to have the format H:MM.")
  487. ;;;; Table
  488. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  489. "Detect an org-type or table-type table.")
  490. (defconst org-table-line-regexp "^[ \t]*|"
  491. "Detect an org-type table line.")
  492. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  493. "Detect an org-type table line.")
  494. (defconst org-table-hline-regexp "^[ \t]*|-"
  495. "Detect an org-type table hline.")
  496. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  497. "Detect a table-type table hline.")
  498. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  499. "Detect the first line outside a table when searching from within it.
  500. This works for both table types.")
  501. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  502. "Detect a #+TBLFM line.")
  503. ;;;; Timestamp
  504. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  505. "Regular expression for fast time stamp matching.")
  506. (defconst org-ts-regexp-inactive
  507. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  508. "Regular expression for fast inactive time stamp matching.")
  509. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  510. "Regular expression for fast time stamp matching.")
  511. (defconst org-ts-regexp0
  512. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  513. "Regular expression matching time strings for analysis.
  514. This one does not require the space after the date, so it can be used
  515. on a string that terminates immediately after the date.")
  516. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  517. "Regular expression matching time strings for analysis.")
  518. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  519. "Regular expression matching time stamps, with groups.")
  520. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  521. "Regular expression matching time stamps (also [..]), with groups.")
  522. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  523. "Regular expression matching a time stamp range.")
  524. (defconst org-tr-regexp-both
  525. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  526. "Regular expression matching a time stamp range.")
  527. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  528. org-ts-regexp "\\)?")
  529. "Regular expression matching a time stamp or time stamp range.")
  530. (defconst org-tsr-regexp-both
  531. (concat org-ts-regexp-both "\\(--?-?"
  532. org-ts-regexp-both "\\)?")
  533. "Regular expression matching a time stamp or time stamp range.
  534. The time stamps may be either active or inactive.")
  535. (defconst org-repeat-re
  536. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  537. "Regular expression for specifying repeated events.
  538. After a match, group 1 contains the repeat expression.")
  539. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  540. "Formats for `format-time-string' which are used for time stamps.")
  541. ;;; The custom variables
  542. (defgroup org nil
  543. "Outline-based notes management and organizer."
  544. :tag "Org"
  545. :group 'outlines
  546. :group 'calendar)
  547. (defcustom org-mode-hook nil
  548. "Mode hook for Org mode, run after the mode was turned on."
  549. :group 'org
  550. :type 'hook)
  551. (defcustom org-load-hook nil
  552. "Hook that is run after org.el has been loaded."
  553. :group 'org
  554. :type 'hook)
  555. (defcustom org-log-buffer-setup-hook nil
  556. "Hook that is run after an Org log buffer is created."
  557. :group 'org
  558. :version "24.1"
  559. :type 'hook)
  560. (defvar org-modules) ; defined below
  561. (defvar org-modules-loaded nil
  562. "Have the modules been loaded already?")
  563. (defun org-load-modules-maybe (&optional force)
  564. "Load all extensions listed in `org-modules'."
  565. (when (or force (not org-modules-loaded))
  566. (dolist (ext org-modules)
  567. (condition-case nil (require ext)
  568. (error (message "Problems while trying to load feature `%s'" ext))))
  569. (setq org-modules-loaded t)))
  570. (defun org-set-modules (var value)
  571. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  572. (set var value)
  573. (when (featurep 'org)
  574. (org-load-modules-maybe 'force)
  575. (org-element-cache-reset 'all)))
  576. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  577. "Modules that should always be loaded together with org.el.
  578. If a description starts with <C>, the file is not part of Emacs
  579. and loading it will require that you have downloaded and properly
  580. installed the Org mode distribution.
  581. You can also use this system to load external packages (i.e. neither Org
  582. core modules, nor modules from the CONTRIB directory). Just add symbols
  583. to the end of the list. If the package is called org-xyz.el, then you need
  584. to add the symbol `xyz', and the package must have a call to:
  585. (provide \\='org-xyz)
  586. For export specific modules, see also `org-export-backends'."
  587. :group 'org
  588. :set 'org-set-modules
  589. :version "24.4"
  590. :package-version '(Org . "8.0")
  591. :type
  592. '(set :greedy t
  593. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  594. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  595. (const :tag " crypt: Encryption of subtrees" org-crypt)
  596. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  597. (const :tag " docview: Links to doc-view buffers" org-docview)
  598. (const :tag " eww: Store link to url of eww" org-eww)
  599. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  600. (const :tag " habit: Track your consistency with habits" org-habit)
  601. (const :tag " id: Global IDs for identifying entries" org-id)
  602. (const :tag " info: Links to Info nodes" org-info)
  603. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  604. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  605. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  606. (const :tag " mouse: Additional mouse support" org-mouse)
  607. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  608. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  609. (const :tag " tempo: Fast completion for structures" org-tempo)
  610. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  611. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  612. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  613. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  614. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  615. (const :tag "C collector: Collect properties into tables" org-collector)
  616. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  617. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  618. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  619. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  620. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  621. (const :tag "C eval: Include command output as text" org-eval)
  622. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  623. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  624. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  625. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  626. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  627. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  628. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  629. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  630. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  631. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  632. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  633. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  634. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  635. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  636. (const :tag "C registry: A registry for Org links" org-registry)
  637. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  638. (const :tag "C secretary: Team management with Org" org-secretary)
  639. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  640. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  641. (const :tag "C track: Keep up with Org mode development" org-track)
  642. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  643. (const :tag "C vm: Links to VM folders/messages" org-vm)
  644. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  645. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  646. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  647. (defvar org-export-registered-backends) ; From ox.el.
  648. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  649. (declare-function org-export-backend-name "ox" (backend) t)
  650. (defcustom org-export-backends '(ascii html icalendar latex odt)
  651. "List of export back-ends that should be always available.
  652. If a description starts with <C>, the file is not part of Emacs
  653. and loading it will require that you have downloaded and properly
  654. installed the Org mode distribution.
  655. Unlike to `org-modules', libraries in this list will not be
  656. loaded along with Org, but only once the export framework is
  657. needed.
  658. This variable needs to be set before org.el is loaded. If you
  659. need to make a change while Emacs is running, use the customize
  660. interface or run the following code, where VAL stands for the new
  661. value of the variable, after updating it:
  662. (progn
  663. (setq org-export-registered-backends
  664. (cl-remove-if-not
  665. (lambda (backend)
  666. (let ((name (org-export-backend-name backend)))
  667. (or (memq name val)
  668. (catch \\='parentp
  669. (dolist (b val)
  670. (and (org-export-derived-backend-p b name)
  671. (throw \\='parentp t)))))))
  672. org-export-registered-backends))
  673. (let ((new-list (mapcar #\\='org-export-backend-name
  674. org-export-registered-backends)))
  675. (dolist (backend val)
  676. (cond
  677. ((not (load (format \"ox-%s\" backend) t t))
  678. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  679. backend))
  680. ((not (memq backend new-list)) (push backend new-list))))
  681. (set-default \\='org-export-backends new-list)))
  682. Adding a back-end to this list will also pull the back-end it
  683. depends on, if any."
  684. :group 'org
  685. :group 'org-export
  686. :version "26.1"
  687. :package-version '(Org . "9.0")
  688. :initialize 'custom-initialize-set
  689. :set (lambda (var val)
  690. (if (not (featurep 'ox)) (set-default var val)
  691. ;; Any back-end not required anymore (not present in VAL and not
  692. ;; a parent of any back-end in the new value) is removed from the
  693. ;; list of registered back-ends.
  694. (setq org-export-registered-backends
  695. (cl-remove-if-not
  696. (lambda (backend)
  697. (let ((name (org-export-backend-name backend)))
  698. (or (memq name val)
  699. (catch 'parentp
  700. (dolist (b val)
  701. (and (org-export-derived-backend-p b name)
  702. (throw 'parentp t)))))))
  703. org-export-registered-backends))
  704. ;; Now build NEW-LIST of both new back-ends and required
  705. ;; parents.
  706. (let ((new-list (mapcar #'org-export-backend-name
  707. org-export-registered-backends)))
  708. (dolist (backend val)
  709. (cond
  710. ((not (load (format "ox-%s" backend) t t))
  711. (message "Problems while trying to load export back-end `%s'"
  712. backend))
  713. ((not (memq backend new-list)) (push backend new-list))))
  714. ;; Set VAR to that list with fixed dependencies.
  715. (set-default var new-list))))
  716. :type '(set :greedy t
  717. (const :tag " ascii Export buffer to ASCII format" ascii)
  718. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  719. (const :tag " html Export buffer to HTML format" html)
  720. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  721. (const :tag " latex Export buffer to LaTeX format" latex)
  722. (const :tag " man Export buffer to MAN format" man)
  723. (const :tag " md Export buffer to Markdown format" md)
  724. (const :tag " odt Export buffer to ODT format" odt)
  725. (const :tag " org Export buffer to Org format" org)
  726. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  727. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  728. (const :tag "C deck Export buffer to deck.js presentations" deck)
  729. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  730. (const :tag "C groff Export buffer to Groff format" groff)
  731. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  732. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  733. (const :tag "C s5 Export buffer to s5 presentations" s5)
  734. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  735. (eval-after-load 'ox
  736. '(dolist (backend org-export-backends)
  737. (condition-case nil (require (intern (format "ox-%s" backend)))
  738. (error (message "Problems while trying to load export back-end `%s'"
  739. backend)))))
  740. (defcustom org-support-shift-select nil
  741. "Non-nil means make shift-cursor commands select text when possible.
  742. \\<org-mode-map>\
  743. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  744. start selecting a region, or enlarge regions started in this way.
  745. In Org mode, in special contexts, these same keys are used for
  746. other purposes, important enough to compete with shift selection.
  747. Org tries to balance these needs by supporting `shift-select-mode'
  748. outside these special contexts, under control of this variable.
  749. The default of this variable is nil, to avoid confusing behavior. Shifted
  750. cursor keys will then execute Org commands in the following contexts:
  751. - on a headline, changing TODO state (left/right) and priority (up/down)
  752. - on a time stamp, changing the time
  753. - in a plain list item, changing the bullet type
  754. - in a property definition line, switching between allowed values
  755. - in the BEGIN line of a clock table (changing the time block).
  756. Outside these contexts, the commands will throw an error.
  757. When this variable is t and the cursor is not in a special
  758. context, Org mode will support shift-selection for making and
  759. enlarging regions. To make this more effective, the bullet
  760. cycling will no longer happen anywhere in an item line, but only
  761. if the cursor is exactly on the bullet.
  762. If you set this variable to the symbol `always', then the keys
  763. will not be special in headlines, property lines, and item lines,
  764. to make shift selection work there as well. If this is what you
  765. want, you can use the following alternative commands:
  766. `\\[org-todo]' and `\\[org-priority]' \
  767. to change TODO state and priority,
  768. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  769. can be used to switch TODO sets,
  770. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  771. and properties can be edited by hand or in column view.
  772. However, when the cursor is on a timestamp, shift-cursor commands
  773. will still edit the time stamp - this is just too good to give up."
  774. :group 'org
  775. :type '(choice
  776. (const :tag "Never" nil)
  777. (const :tag "When outside special context" t)
  778. (const :tag "Everywhere except timestamps" always)))
  779. (defcustom org-loop-over-headlines-in-active-region nil
  780. "Shall some commands act upon headlines in the active region?
  781. When set to t, some commands will be performed in all headlines
  782. within the active region.
  783. When set to `start-level', some commands will be performed in all
  784. headlines within the active region, provided that these headlines
  785. are of the same level than the first one.
  786. When set to a string, those commands will be performed on the
  787. matching headlines within the active region. Such string must be
  788. a tags/property/todo match as it is used in the agenda tags view.
  789. The list of commands is: `org-schedule', `org-deadline',
  790. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  791. `org-archive-to-archive-sibling'. The archiving commands skip
  792. already archived entries."
  793. :type '(choice (const :tag "Don't loop" nil)
  794. (const :tag "All headlines in active region" t)
  795. (const :tag "In active region, headlines at the same level than the first one" start-level)
  796. (string :tag "Tags/Property/Todo matcher"))
  797. :version "24.1"
  798. :group 'org-todo
  799. :group 'org-archive)
  800. (defcustom org-startup-folded t
  801. "Non-nil means entering Org mode will switch to OVERVIEW.
  802. This can also be configured on a per-file basis by adding one of
  803. the following lines anywhere in the buffer:
  804. #+STARTUP: fold (or `overview', this is equivalent)
  805. #+STARTUP: nofold (or `showall', this is equivalent)
  806. #+STARTUP: content
  807. #+STARTUP: showeverything
  808. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  809. to ignore this option when Org opens agenda files for the first
  810. time."
  811. :group 'org-startup
  812. :type '(choice
  813. (const :tag "nofold: show all" nil)
  814. (const :tag "fold: overview" t)
  815. (const :tag "content: all headlines" content)
  816. (const :tag "show everything, even drawers" showeverything)))
  817. (defcustom org-startup-truncated t
  818. "Non-nil means entering Org mode will set `truncate-lines'.
  819. This is useful since some lines containing links can be very long and
  820. uninteresting. Also tables look terrible when wrapped.
  821. The variable `org-startup-truncated' allows to configure
  822. truncation for Org mode different to the other modes that use the
  823. variable `truncate-lines' and as a shortcut instead of putting
  824. the variable `truncate-lines' into the `org-mode-hook'. If one
  825. wants to configure truncation for Org mode not statically but
  826. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  827. the variable `truncate-lines' has to be used because in such a
  828. case it is too late to set the variable `org-startup-truncated'."
  829. :group 'org-startup
  830. :type 'boolean)
  831. (defcustom org-startup-indented nil
  832. "Non-nil means turn on `org-indent-mode' on startup.
  833. This can also be configured on a per-file basis by adding one of
  834. the following lines anywhere in the buffer:
  835. #+STARTUP: indent
  836. #+STARTUP: noindent"
  837. :group 'org-structure
  838. :type '(choice
  839. (const :tag "Not" nil)
  840. (const :tag "Globally (slow on startup in large files)" t)))
  841. (defcustom org-use-sub-superscripts t
  842. "Non-nil means interpret \"_\" and \"^\" for display.
  843. If you want to control how Org exports those characters, see
  844. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  845. used to be an alias for `org-export-with-sub-superscripts' in
  846. Org <8.0, it is not anymore.
  847. When this option is turned on, you can use TeX-like syntax for
  848. sub- and superscripts within the buffer. Several characters after
  849. \"_\" or \"^\" will be considered as a single item - so grouping
  850. with {} is normally not needed. For example, the following things
  851. will be parsed as single sub- or superscripts:
  852. 10^24 or 10^tau several digits will be considered 1 item.
  853. 10^-12 or 10^-tau a leading sign with digits or a word
  854. x^2-y^3 will be read as x^2 - y^3, because items are
  855. terminated by almost any nonword/nondigit char.
  856. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  857. Still, ambiguity is possible. So when in doubt, use {} to enclose
  858. the sub/superscript. If you set this variable to the symbol `{}',
  859. the braces are *required* in order to trigger interpretations as
  860. sub/superscript. This can be helpful in documents that need \"_\"
  861. frequently in plain text."
  862. :group 'org-startup
  863. :version "24.4"
  864. :package-version '(Org . "8.0")
  865. :type '(choice
  866. (const :tag "Always interpret" t)
  867. (const :tag "Only with braces" {})
  868. (const :tag "Never interpret" nil)))
  869. (defcustom org-startup-with-beamer-mode nil
  870. "Non-nil means turn on `org-beamer-mode' on startup.
  871. This can also be configured on a per-file basis by adding one of
  872. the following lines anywhere in the buffer:
  873. #+STARTUP: beamer"
  874. :group 'org-startup
  875. :version "24.1"
  876. :type 'boolean)
  877. (defcustom org-startup-align-all-tables nil
  878. "Non-nil means align all tables when visiting a file.
  879. This can also be configured on a per-file basis by adding one of
  880. the following lines anywhere in the buffer:
  881. #+STARTUP: align
  882. #+STARTUP: noalign"
  883. :group 'org-startup
  884. :type 'boolean)
  885. (defcustom org-startup-shrink-all-tables nil
  886. "Non-nil means shrink all table columns with a width cookie.
  887. This can also be configured on a per-file basis by adding one of
  888. the following lines anywhere in the buffer:
  889. #+STARTUP: shrink"
  890. :group 'org-startup
  891. :type 'boolean
  892. :version "27.1"
  893. :package-version '(Org . "9.2")
  894. :safe #'booleanp)
  895. (defcustom org-startup-with-inline-images nil
  896. "Non-nil means show inline images when loading a new Org file.
  897. This can also be configured on a per-file basis by adding one of
  898. the following lines anywhere in the buffer:
  899. #+STARTUP: inlineimages
  900. #+STARTUP: noinlineimages"
  901. :group 'org-startup
  902. :version "24.1"
  903. :type 'boolean)
  904. (defcustom org-startup-with-latex-preview nil
  905. "Non-nil means preview LaTeX fragments when loading a new Org file.
  906. This can also be configured on a per-file basis by adding one of
  907. the following lines anywhere in the buffer:
  908. #+STARTUP: latexpreview
  909. #+STARTUP: nolatexpreview"
  910. :group 'org-startup
  911. :version "24.4"
  912. :package-version '(Org . "8.0")
  913. :type 'boolean)
  914. (defcustom org-insert-mode-line-in-empty-file nil
  915. "Non-nil means insert the first line setting Org mode in empty files.
  916. When the function `org-mode' is called interactively in an empty file, this
  917. normally means that the file name does not automatically trigger Org mode.
  918. To ensure that the file will always be in Org mode in the future, a
  919. line enforcing Org mode will be inserted into the buffer, if this option
  920. has been set."
  921. :group 'org-startup
  922. :type 'boolean)
  923. (defcustom org-replace-disputed-keys nil
  924. "Non-nil means use alternative key bindings for some keys.
  925. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  926. These keys are also used by other packages like Shift Select mode,
  927. CUA mode or Windmove. If you want to use Org mode together with
  928. one of these other modes, or more generally if you would like to
  929. move some Org mode commands to other keys, set this variable and
  930. configure the keys with the variable `org-disputed-keys'.
  931. This option is only relevant at load-time of Org mode, and must be set
  932. *before* org.el is loaded. Changing it requires a restart of Emacs to
  933. become effective."
  934. :group 'org-startup
  935. :type 'boolean)
  936. (defcustom org-use-extra-keys nil
  937. "Non-nil means use extra key sequence definitions for certain commands.
  938. This happens automatically if `window-system' is nil. This
  939. variable lets you do the same manually. You must set it before
  940. loading Org."
  941. :group 'org-startup
  942. :type 'boolean)
  943. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  944. (defcustom org-disputed-keys
  945. '(([(shift up)] . [(meta p)])
  946. ([(shift down)] . [(meta n)])
  947. ([(shift left)] . [(meta -)])
  948. ([(shift right)] . [(meta +)])
  949. ([(control shift right)] . [(meta shift +)])
  950. ([(control shift left)] . [(meta shift -)]))
  951. "Keys for which Org mode and other modes compete.
  952. This is an alist, cars are the default keys, second element specifies
  953. the alternative to use when `org-replace-disputed-keys' is t.
  954. Keys can be specified in any syntax supported by `define-key'.
  955. The value of this option takes effect only at Org mode startup,
  956. therefore you'll have to restart Emacs to apply it after changing."
  957. :group 'org-startup
  958. :type 'alist)
  959. (defun org-key (key)
  960. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  961. Or return the original if not disputed."
  962. (when org-replace-disputed-keys
  963. (let* ((nkey (key-description key))
  964. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  965. org-disputed-keys)))
  966. (setq key (if x (cdr x) key))))
  967. key)
  968. (defun org-defkey (keymap key def)
  969. "Define a key, possibly translated, as returned by `org-key'."
  970. (define-key keymap (org-key key) def))
  971. (defcustom org-ellipsis nil
  972. "The ellipsis to use in the Org mode outline.
  973. When nil, just use the standard three dots. When a non-empty string,
  974. use that string instead.
  975. The change affects only Org mode (which will then use its own display table).
  976. Changing this requires executing `\\[org-mode]' in a buffer to become
  977. effective."
  978. :group 'org-startup
  979. :type '(choice (const :tag "Default" nil)
  980. (string :tag "String" :value "...#"))
  981. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  982. (defvar org-display-table nil
  983. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  984. (defgroup org-keywords nil
  985. "Keywords in Org mode."
  986. :tag "Org Keywords"
  987. :group 'org)
  988. (defcustom org-closed-keep-when-no-todo nil
  989. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  990. :group 'org-todo
  991. :group 'org-keywords
  992. :version "24.4"
  993. :package-version '(Org . "8.0")
  994. :type 'boolean)
  995. (defgroup org-structure nil
  996. "Options concerning the general structure of Org files."
  997. :tag "Org Structure"
  998. :group 'org)
  999. (defgroup org-reveal-location nil
  1000. "Options about how to make context of a location visible."
  1001. :tag "Org Reveal Location"
  1002. :group 'org-structure)
  1003. (defcustom org-show-context-detail '((agenda . local)
  1004. (bookmark-jump . lineage)
  1005. (isearch . lineage)
  1006. (default . ancestors))
  1007. "Alist between context and visibility span when revealing a location.
  1008. \\<org-mode-map>Some actions may move point into invisible
  1009. locations. As a consequence, Org always expose a neighborhood
  1010. around point. How much is shown depends on the initial action,
  1011. or context. Valid contexts are
  1012. agenda when exposing an entry from the agenda
  1013. org-goto when using the command `org-goto' (`\\[org-goto]')
  1014. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1015. tags-tree when constructing a sparse tree based on tags matches
  1016. link-search when exposing search matches associated with a link
  1017. mark-goto when exposing the jump goal of a mark
  1018. bookmark-jump when exposing a bookmark location
  1019. isearch when exiting from an incremental search
  1020. default default for all contexts not set explicitly
  1021. Allowed visibility spans are
  1022. minimal show current headline; if point is not on headline,
  1023. also show entry
  1024. local show current headline, entry and next headline
  1025. ancestors show current headline and its direct ancestors; if
  1026. point is not on headline, also show entry
  1027. lineage show current headline, its direct ancestors and all
  1028. their children; if point is not on headline, also show
  1029. entry and first child
  1030. tree show current headline, its direct ancestors and all
  1031. their children; if point is not on headline, also show
  1032. entry and all children
  1033. canonical show current headline, its direct ancestors along with
  1034. their entries and children; if point is not located on
  1035. the headline, also show current entry and all children
  1036. As special cases, a nil or t value means show all contexts in
  1037. `minimal' or `canonical' view, respectively.
  1038. Some views can make displayed information very compact, but also
  1039. make it harder to edit the location of the match. In such
  1040. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1041. more context."
  1042. :group 'org-reveal-location
  1043. :version "26.1"
  1044. :package-version '(Org . "9.0")
  1045. :type '(choice
  1046. (const :tag "Canonical" t)
  1047. (const :tag "Minimal" nil)
  1048. (repeat :greedy t :tag "Individual contexts"
  1049. (cons
  1050. (choice :tag "Context"
  1051. (const agenda)
  1052. (const org-goto)
  1053. (const occur-tree)
  1054. (const tags-tree)
  1055. (const link-search)
  1056. (const mark-goto)
  1057. (const bookmark-jump)
  1058. (const isearch)
  1059. (const default))
  1060. (choice :tag "Detail level"
  1061. (const minimal)
  1062. (const local)
  1063. (const ancestors)
  1064. (const lineage)
  1065. (const tree)
  1066. (const canonical))))))
  1067. (defcustom org-indirect-buffer-display 'other-window
  1068. "How should indirect tree buffers be displayed?
  1069. This applies to indirect buffers created with the commands
  1070. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1071. Valid values are:
  1072. current-window Display in the current window
  1073. other-window Just display in another window.
  1074. dedicated-frame Create one new frame, and re-use it each time.
  1075. new-frame Make a new frame each time. Note that in this case
  1076. previously-made indirect buffers are kept, and you need to
  1077. kill these buffers yourself."
  1078. :group 'org-structure
  1079. :group 'org-agenda-windows
  1080. :type '(choice
  1081. (const :tag "In current window" current-window)
  1082. (const :tag "In current frame, other window" other-window)
  1083. (const :tag "Each time a new frame" new-frame)
  1084. (const :tag "One dedicated frame" dedicated-frame)))
  1085. (defcustom org-use-speed-commands nil
  1086. "Non-nil means activate single letter commands at beginning of a headline.
  1087. This may also be a function to test for appropriate locations where speed
  1088. commands should be active.
  1089. For example, to activate speed commands when the point is on any
  1090. star at the beginning of the headline, you can do this:
  1091. (setq org-use-speed-commands
  1092. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1093. :group 'org-structure
  1094. :type '(choice
  1095. (const :tag "Never" nil)
  1096. (const :tag "At beginning of headline stars" t)
  1097. (function)))
  1098. (defcustom org-speed-commands-user nil
  1099. "Alist of additional speed commands.
  1100. This list will be checked before `org-speed-commands-default'
  1101. when the variable `org-use-speed-commands' is non-nil
  1102. and when the cursor is at the beginning of a headline.
  1103. The car of each entry is a string with a single letter, which must
  1104. be assigned to `self-insert-command' in the global map.
  1105. The cdr is either a command to be called interactively, a function
  1106. to be called, or a form to be evaluated.
  1107. An entry that is just a list with a single string will be interpreted
  1108. as a descriptive headline that will be added when listing the speed
  1109. commands in the Help buffer using the `?' speed command."
  1110. :group 'org-structure
  1111. :type '(repeat :value ("k" . ignore)
  1112. (choice :value ("k" . ignore)
  1113. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1114. (cons :tag "Letter and Command"
  1115. (string :tag "Command letter")
  1116. (choice
  1117. (function)
  1118. (sexp))))))
  1119. (defcustom org-bookmark-names-plist
  1120. '(:last-capture "org-capture-last-stored"
  1121. :last-refile "org-refile-last-stored"
  1122. :last-capture-marker "org-capture-last-stored-marker")
  1123. "Names for bookmarks automatically set by some Org commands.
  1124. This can provide strings as names for a number of bookmarks Org sets
  1125. automatically. The following keys are currently implemented:
  1126. :last-capture
  1127. :last-capture-marker
  1128. :last-refile
  1129. When a key does not show up in the property list, the corresponding bookmark
  1130. is not set."
  1131. :group 'org-structure
  1132. :type 'plist)
  1133. (defgroup org-cycle nil
  1134. "Options concerning visibility cycling in Org mode."
  1135. :tag "Org Cycle"
  1136. :group 'org-structure)
  1137. (defcustom org-cycle-skip-children-state-if-no-children t
  1138. "Non-nil means skip CHILDREN state in entries that don't have any."
  1139. :group 'org-cycle
  1140. :type 'boolean)
  1141. (defcustom org-cycle-max-level nil
  1142. "Maximum level which should still be subject to visibility cycling.
  1143. Levels higher than this will, for cycling, be treated as text, not a headline.
  1144. When `org-odd-levels-only' is set, a value of N in this variable actually
  1145. means 2N-1 stars as the limiting headline.
  1146. When nil, cycle all levels.
  1147. Note that the limiting level of cycling is also influenced by
  1148. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1149. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1150. than its value."
  1151. :group 'org-cycle
  1152. :type '(choice
  1153. (const :tag "No limit" nil)
  1154. (integer :tag "Maximum level")))
  1155. (defcustom org-hide-block-startup nil
  1156. "Non-nil means entering Org mode will fold all blocks.
  1157. This can also be set in on a per-file basis with
  1158. #+STARTUP: hideblocks
  1159. #+STARTUP: showblocks"
  1160. :group 'org-startup
  1161. :group 'org-cycle
  1162. :type 'boolean)
  1163. (defcustom org-cycle-global-at-bob nil
  1164. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1165. This makes it possible to do global cycling without having to use `S-TAB'
  1166. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1167. line of the buffer
  1168. must not be a headline -- it may be empty or some other text.
  1169. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1170. sure the cursor stays at the beginning of the buffer.
  1171. When this option is nil, don't do anything special at the beginning of
  1172. the buffer."
  1173. :group 'org-cycle
  1174. :type 'boolean)
  1175. (defcustom org-cycle-level-after-item/entry-creation t
  1176. "Non-nil means cycle entry level or item indentation in new empty entries.
  1177. When the cursor is at the end of an empty headline, i.e., with only stars
  1178. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1179. and then all possible ancestor states, before returning to the original state.
  1180. This makes data entry extremely fast: M-RET to create a new headline,
  1181. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1182. When the cursor is at the end of an empty plain list item, one TAB will
  1183. make it a subitem, two or more tabs will back up to make this an item
  1184. higher up in the item hierarchy."
  1185. :group 'org-cycle
  1186. :type 'boolean)
  1187. (defcustom org-cycle-emulate-tab t
  1188. "Where should `org-cycle' emulate TAB.
  1189. nil Never
  1190. white Only in completely white lines
  1191. whitestart Only at the beginning of lines, before the first non-white char
  1192. t Everywhere except in headlines
  1193. exc-hl-bol Everywhere except at the start of a headline
  1194. If TAB is used in a place where it does not emulate TAB, the current subtree
  1195. visibility is cycled."
  1196. :group 'org-cycle
  1197. :type '(choice (const :tag "Never" nil)
  1198. (const :tag "Only in completely white lines" white)
  1199. (const :tag "Before first char in a line" whitestart)
  1200. (const :tag "Everywhere except in headlines" t)
  1201. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1202. (defcustom org-cycle-separator-lines 2
  1203. "Number of empty lines needed to keep an empty line between collapsed trees.
  1204. If you leave an empty line between the end of a subtree and the following
  1205. headline, this empty line is hidden when the subtree is folded.
  1206. Org mode will leave (exactly) one empty line visible if the number of
  1207. empty lines is equal or larger to the number given in this variable.
  1208. So the default 2 means at least 2 empty lines after the end of a subtree
  1209. are needed to produce free space between a collapsed subtree and the
  1210. following headline.
  1211. If the number is negative, and the number of empty lines is at least -N,
  1212. all empty lines are shown.
  1213. Special case: when 0, never leave empty lines in collapsed view."
  1214. :group 'org-cycle
  1215. :type 'integer)
  1216. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1217. (defcustom org-pre-cycle-hook nil
  1218. "Hook that is run before visibility cycling is happening.
  1219. The function(s) in this hook must accept a single argument which indicates
  1220. the new state that will be set right after running this hook. The
  1221. argument is a symbol. Before a global state change, it can have the values
  1222. `overview', `content', or `all'. Before a local state change, it can have
  1223. the values `folded', `children', or `subtree'."
  1224. :group 'org-cycle
  1225. :type 'hook)
  1226. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1227. org-cycle-show-empty-lines
  1228. org-optimize-window-after-visibility-change)
  1229. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1230. The function(s) in this hook must accept a single argument which indicates
  1231. the new state that was set by the most recent `org-cycle' command. The
  1232. argument is a symbol. After a global state change, it can have the values
  1233. `overview', `contents', or `all'. After a local state change, it can have
  1234. the values `folded', `children', or `subtree'."
  1235. :group 'org-cycle
  1236. :type 'hook
  1237. :version "26.1"
  1238. :package-version '(Org . "8.3"))
  1239. (defgroup org-edit-structure nil
  1240. "Options concerning structure editing in Org mode."
  1241. :tag "Org Edit Structure"
  1242. :group 'org-structure)
  1243. (defcustom org-odd-levels-only nil
  1244. "Non-nil means skip even levels and only use odd levels for the outline.
  1245. This has the effect that two stars are being added/taken away in
  1246. promotion/demotion commands. It also influences how levels are
  1247. handled by the exporters.
  1248. Changing it requires restart of `font-lock-mode' to become effective
  1249. for fontification also in regions already fontified.
  1250. You may also set this on a per-file basis by adding one of the following
  1251. lines to the buffer:
  1252. #+STARTUP: odd
  1253. #+STARTUP: oddeven"
  1254. :group 'org-edit-structure
  1255. :group 'org-appearance
  1256. :type 'boolean)
  1257. (defcustom org-adapt-indentation t
  1258. "Non-nil means adapt indentation to outline node level.
  1259. When this variable is set, Org assumes that you write outlines by
  1260. indenting text in each node to align with the headline (after the
  1261. stars). The following issues are influenced by this variable:
  1262. - The indentation is increased by one space in a demotion
  1263. command, and decreased by one in a promotion command. However,
  1264. in the latter case, if shifting some line in the entry body
  1265. would alter document structure (e.g., insert a new headline),
  1266. indentation is not changed at all.
  1267. - Property drawers and planning information is inserted indented
  1268. when this variable is set. When nil, they will not be indented.
  1269. - TAB indents a line relative to current level. The lines below
  1270. a headline will be indented when this variable is set.
  1271. Note that this is all about true indentation, by adding and
  1272. removing space characters. See also \"org-indent.el\" which does
  1273. level-dependent indentation in a virtual way, i.e. at display
  1274. time in Emacs."
  1275. :group 'org-edit-structure
  1276. :type 'boolean
  1277. :safe #'booleanp)
  1278. (defcustom org-special-ctrl-a/e nil
  1279. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1280. When t, `C-a' will bring back the cursor to the beginning of the
  1281. headline text, i.e. after the stars and after a possible TODO
  1282. keyword. In an item, this will be the position after bullet and
  1283. check-box, if any. When the cursor is already at that position,
  1284. another `C-a' will bring it to the beginning of the line.
  1285. `C-e' will jump to the end of the headline, ignoring the presence
  1286. of tags in the headline. A second `C-e' will then jump to the
  1287. true end of the line, after any tags. This also means that, when
  1288. this variable is non-nil, `C-e' also will never jump beyond the
  1289. end of the heading of a folded section, i.e. not after the
  1290. ellipses.
  1291. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1292. normally, going to the true line boundary first. Only a directly
  1293. following, identical keypress will bring the cursor to the
  1294. special positions.
  1295. This may also be a cons cell where the behavior for `C-a' and
  1296. `C-e' is set separately."
  1297. :group 'org-edit-structure
  1298. :type '(choice
  1299. (const :tag "off" nil)
  1300. (const :tag "on: after stars/bullet and before tags first" t)
  1301. (const :tag "reversed: true line boundary first" reversed)
  1302. (cons :tag "Set C-a and C-e separately"
  1303. (choice :tag "Special C-a"
  1304. (const :tag "off" nil)
  1305. (const :tag "on: after stars/bullet first" t)
  1306. (const :tag "reversed: before stars/bullet first" reversed))
  1307. (choice :tag "Special C-e"
  1308. (const :tag "off" nil)
  1309. (const :tag "on: before tags first" t)
  1310. (const :tag "reversed: after tags first" reversed)))))
  1311. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1312. (defcustom org-special-ctrl-k nil
  1313. "Non-nil means `C-k' will behave specially in headlines.
  1314. When nil, `C-k' will call the default `kill-line' command.
  1315. When t, the following will happen while the cursor is in the headline:
  1316. - When the cursor is at the beginning of a headline, kill the entire
  1317. line and possible the folded subtree below the line.
  1318. - When in the middle of the headline text, kill the headline up to the tags.
  1319. - When after the headline text, kill the tags."
  1320. :group 'org-edit-structure
  1321. :type 'boolean)
  1322. (defcustom org-ctrl-k-protect-subtree nil
  1323. "Non-nil means, do not delete a hidden subtree with C-k.
  1324. When set to the symbol `error', simply throw an error when C-k is
  1325. used to kill (part-of) a headline that has hidden text behind it.
  1326. Any other non-nil value will result in a query to the user, if it is
  1327. OK to kill that hidden subtree. When nil, kill without remorse."
  1328. :group 'org-edit-structure
  1329. :version "24.1"
  1330. :type '(choice
  1331. (const :tag "Do not protect hidden subtrees" nil)
  1332. (const :tag "Protect hidden subtrees with a security query" t)
  1333. (const :tag "Never kill a hidden subtree with C-k" error)))
  1334. (defcustom org-special-ctrl-o t
  1335. "Non-nil means, make `C-o' insert a row in tables."
  1336. :group 'org-edit-structure
  1337. :type 'boolean)
  1338. (defcustom org-catch-invisible-edits nil
  1339. "Check if in invisible region before inserting or deleting a character.
  1340. Valid values are:
  1341. nil Do not check, so just do invisible edits.
  1342. error Throw an error and do nothing.
  1343. show Make point visible, and do the requested edit.
  1344. show-and-error Make point visible, then throw an error and abort the edit.
  1345. smart Make point visible, and do insertion/deletion if it is
  1346. adjacent to visible text and the change feels predictable.
  1347. Never delete a previously invisible character or add in the
  1348. middle or right after an invisible region. Basically, this
  1349. allows insertion and backward-delete right before ellipses.
  1350. FIXME: maybe in this case we should not even show?"
  1351. :group 'org-edit-structure
  1352. :version "24.1"
  1353. :type '(choice
  1354. (const :tag "Do not check" nil)
  1355. (const :tag "Throw error when trying to edit" error)
  1356. (const :tag "Unhide, but do not do the edit" show-and-error)
  1357. (const :tag "Show invisible part and do the edit" show)
  1358. (const :tag "Be smart and do the right thing" smart)))
  1359. (defcustom org-yank-folded-subtrees t
  1360. "Non-nil means when yanking subtrees, fold them.
  1361. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1362. it starts with a heading and all other headings in it are either children
  1363. or siblings, then fold all the subtrees. However, do this only if no
  1364. text after the yank would be swallowed into a folded tree by this action."
  1365. :group 'org-edit-structure
  1366. :type 'boolean)
  1367. (defcustom org-yank-adjusted-subtrees nil
  1368. "Non-nil means when yanking subtrees, adjust the level.
  1369. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1370. this function for details."
  1371. :group 'org-edit-structure
  1372. :type 'boolean)
  1373. (defcustom org-M-RET-may-split-line '((default . t))
  1374. "Non-nil means M-RET will split the line at the cursor position.
  1375. When nil, it will go to the end of the line before making a
  1376. new line.
  1377. You may also set this option in a different way for different
  1378. contexts. Valid contexts are:
  1379. headline when creating a new headline
  1380. item when creating a new item
  1381. table in a table field
  1382. default the value to be used for all contexts not explicitly
  1383. customized"
  1384. :group 'org-structure
  1385. :group 'org-table
  1386. :type '(choice
  1387. (const :tag "Always" t)
  1388. (const :tag "Never" nil)
  1389. (repeat :greedy t :tag "Individual contexts"
  1390. (cons
  1391. (choice :tag "Context"
  1392. (const headline)
  1393. (const item)
  1394. (const table)
  1395. (const default))
  1396. (boolean)))))
  1397. (defcustom org-insert-heading-respect-content nil
  1398. "Non-nil means insert new headings after the current subtree.
  1399. \\<org-mode-map>
  1400. When nil, the new heading is created directly after the current line.
  1401. The commands `\\[org-insert-heading-respect-content]' and \
  1402. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1403. for the duration of the command."
  1404. :group 'org-structure
  1405. :type 'boolean)
  1406. (defcustom org-blank-before-new-entry '((heading . auto)
  1407. (plain-list-item . auto))
  1408. "Should `org-insert-heading' leave a blank line before new heading/item?
  1409. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1410. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1411. which case Org will look at the surrounding headings/items and try to
  1412. make an intelligent decision whether to insert a blank line or not."
  1413. :group 'org-edit-structure
  1414. :type '(list
  1415. (cons (const heading)
  1416. (choice (const :tag "Never" nil)
  1417. (const :tag "Always" t)
  1418. (const :tag "Auto" auto)))
  1419. (cons (const plain-list-item)
  1420. (choice (const :tag "Never" nil)
  1421. (const :tag "Always" t)
  1422. (const :tag "Auto" auto)))))
  1423. (defcustom org-insert-heading-hook nil
  1424. "Hook being run after inserting a new heading."
  1425. :group 'org-edit-structure
  1426. :type 'hook)
  1427. (defcustom org-enable-fixed-width-editor t
  1428. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1429. This currently only means they are never auto-wrapped.
  1430. When nil, such lines will be treated like ordinary lines."
  1431. :group 'org-edit-structure
  1432. :type 'boolean)
  1433. (defgroup org-sparse-trees nil
  1434. "Options concerning sparse trees in Org mode."
  1435. :tag "Org Sparse Trees"
  1436. :group 'org-structure)
  1437. (defcustom org-highlight-sparse-tree-matches t
  1438. "Non-nil means highlight all matches that define a sparse tree.
  1439. The highlights will automatically disappear the next time the buffer is
  1440. changed by an edit command."
  1441. :group 'org-sparse-trees
  1442. :type 'boolean)
  1443. (defcustom org-remove-highlights-with-change t
  1444. "Non-nil means any change to the buffer will remove temporary highlights.
  1445. \\<org-mode-map>\
  1446. Such highlights are created by `org-occur' and `org-clock-display'.
  1447. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1448. to get rid of the highlights.
  1449. The highlights created by `org-toggle-latex-fragment' always need
  1450. `\\[org-toggle-latex-fragment]' to be removed."
  1451. :group 'org-sparse-trees
  1452. :group 'org-time
  1453. :type 'boolean)
  1454. (defcustom org-occur-case-fold-search t
  1455. "Non-nil means `org-occur' should be case-insensitive.
  1456. If set to `smart' the search will be case-insensitive only if it
  1457. doesn't specify any upper case character."
  1458. :group 'org-sparse-trees
  1459. :version "26.1"
  1460. :type '(choice
  1461. (const :tag "Case-sensitive" nil)
  1462. (const :tag "Case-insensitive" t)
  1463. (const :tag "Case-insensitive for lower case searches only" smart)))
  1464. (defcustom org-occur-hook '(org-first-headline-recenter)
  1465. "Hook that is run after `org-occur' has constructed a sparse tree.
  1466. This can be used to recenter the window to show as much of the structure
  1467. as possible."
  1468. :group 'org-sparse-trees
  1469. :type 'hook)
  1470. (defgroup org-table nil
  1471. "Options concerning tables in Org mode."
  1472. :tag "Org Table"
  1473. :group 'org)
  1474. (defcustom org-self-insert-cluster-for-undo nil
  1475. "Non-nil means cluster self-insert commands for undo when possible.
  1476. If this is set, then, like in the Emacs command loop, 20 consecutive
  1477. characters will be undone together.
  1478. This is configurable, because there is some impact on typing performance."
  1479. :group 'org-table
  1480. :type 'boolean)
  1481. (defcustom org-table-tab-recognizes-table.el t
  1482. "Non-nil means TAB will automatically notice a table.el table.
  1483. When it sees such a table, it moves point into it and - if necessary -
  1484. calls `table-recognize-table'."
  1485. :group 'org-table-editing
  1486. :type 'boolean)
  1487. (defgroup org-link nil
  1488. "Options concerning links in Org mode."
  1489. :tag "Org Link"
  1490. :group 'org)
  1491. (defvar-local org-link-abbrev-alist-local nil
  1492. "Buffer-local version of `org-link-abbrev-alist', which see.
  1493. The value of this is taken from the #+LINK lines.")
  1494. (defcustom org-link-parameters
  1495. '(("doi" :follow org--open-doi-link)
  1496. ("elisp" :follow org--open-elisp-link)
  1497. ("file" :complete org-file-complete-link)
  1498. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1499. ("help" :follow org--open-help-link)
  1500. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1501. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1502. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1503. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1504. ("shell" :follow org--open-shell-link))
  1505. "An alist of properties that defines all the links in Org mode.
  1506. The key in each association is a string of the link type.
  1507. Subsequent optional elements make up a p-list of link properties.
  1508. :follow - A function that takes the link path as an argument.
  1509. :export - A function that takes the link path, description and
  1510. export-backend as arguments.
  1511. :store - A function responsible for storing the link. See the
  1512. function `org-store-link-functions'.
  1513. :complete - A function that inserts a link with completion. The
  1514. function takes one optional prefix arg.
  1515. :face - A face for the link, or a function that returns a face.
  1516. The function takes one argument which is the link path. The
  1517. default face is `org-link'.
  1518. :mouse-face - The mouse-face. The default is `highlight'.
  1519. :display - `full' will not fold the link in descriptive
  1520. display. Default is `org-link'.
  1521. :help-echo - A string or function that takes (window object position)
  1522. as arguments and returns a string.
  1523. :keymap - A keymap that is active on the link. The default is
  1524. `org-mouse-map'.
  1525. :htmlize-link - A function for the htmlize-link. Defaults
  1526. to (list :uri \"type:path\")
  1527. :activate-func - A function to run at the end of font-lock
  1528. activation. The function must accept (link-start link-end path bracketp)
  1529. as arguments."
  1530. :group 'org-link
  1531. :type '(alist :tag "Link display parameters"
  1532. :value-type plist)
  1533. :version "26.1"
  1534. :package-version '(Org . "9.1"))
  1535. (defun org-link-get-parameter (type key)
  1536. "Get TYPE link property for KEY.
  1537. TYPE is a string and KEY is a plist keyword."
  1538. (plist-get
  1539. (cdr (assoc type org-link-parameters))
  1540. key))
  1541. (defun org-link-set-parameters (type &rest parameters)
  1542. "Set link TYPE properties to PARAMETERS.
  1543. PARAMETERS should be :key val pairs."
  1544. (let ((data (assoc type org-link-parameters)))
  1545. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1546. (push (cons type parameters) org-link-parameters)
  1547. (org-make-link-regexps)
  1548. (org-element-update-syntax))))
  1549. (defun org-link-types ()
  1550. "Return a list of known link types."
  1551. (mapcar #'car org-link-parameters))
  1552. (defcustom org-link-abbrev-alist nil
  1553. "Alist of link abbreviations.
  1554. The car of each element is a string, to be replaced at the start of a link.
  1555. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1556. links in Org buffers can have an optional tag after a double colon, e.g.,
  1557. [[linkkey:tag][description]]
  1558. The `linkkey' must be a single word, starting with a letter, followed
  1559. by letters, numbers, `-' or `_'.
  1560. If REPLACE is a string, the tag will simply be appended to create the link.
  1561. If the string contains \"%s\", the tag will be inserted there. If the string
  1562. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1563. at that point (see the function `url-hexify-string'). If the string contains
  1564. the specifier \"%(my-function)\", then the custom function `my-function' will
  1565. be invoked: this function takes the tag as its only argument and must return
  1566. a string.
  1567. REPLACE may also be a function that will be called with the tag as the
  1568. only argument to create the link, which should be returned as a string.
  1569. See the manual for examples."
  1570. :group 'org-link
  1571. :type '(repeat
  1572. (cons
  1573. (string :tag "Protocol")
  1574. (choice
  1575. (string :tag "Format")
  1576. (function)))))
  1577. (defcustom org-descriptive-links t
  1578. "Non-nil means Org will display descriptive links.
  1579. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1580. \"Org Website\", hiding the link itself and just displaying its
  1581. description. When set to nil, Org will display the full links
  1582. literally.
  1583. You can interactively set the value of this variable by calling
  1584. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1585. :group 'org-link
  1586. :type 'boolean)
  1587. (defcustom org-link-file-path-type 'adaptive
  1588. "How the path name in file links should be stored.
  1589. Valid values are:
  1590. relative Relative to the current directory, i.e. the directory of the file
  1591. into which the link is being inserted.
  1592. absolute Absolute path, if possible with ~ for home directory.
  1593. noabbrev Absolute path, no abbreviation of home directory.
  1594. adaptive Use relative path for files in the current directory and sub-
  1595. directories of it. For other files, use an absolute path."
  1596. :group 'org-link
  1597. :type '(choice
  1598. (const relative)
  1599. (const absolute)
  1600. (const noabbrev)
  1601. (const adaptive)))
  1602. (defvaralias 'org-activate-links 'org-highlight-links)
  1603. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1604. "Types of links that should be highlighted in Org files.
  1605. This is a list of symbols, each one of them leading to the
  1606. highlighting of a certain link type.
  1607. You can still open links that are not highlighted.
  1608. In principle, it does not hurt to turn on highlighting for all
  1609. link types. There may be a small gain when turning off unused
  1610. link types. The types are:
  1611. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1612. angle Links in angular brackets that may contain whitespace like
  1613. <bbdb:Carsten Dominik>.
  1614. plain Plain links in normal text, no whitespace, like http://google.com.
  1615. radio Text that is matched by a radio target, see manual for details.
  1616. tag Tag settings in a headline (link to tag search).
  1617. date Time stamps (link to calendar).
  1618. footnote Footnote labels.
  1619. If you set this variable during an Emacs session, use `org-mode-restart'
  1620. in the Org buffer so that the change takes effect."
  1621. :group 'org-link
  1622. :group 'org-appearance
  1623. :type '(set :greedy t
  1624. (const :tag "Double bracket links" bracket)
  1625. (const :tag "Angular bracket links" angle)
  1626. (const :tag "Plain text links" plain)
  1627. (const :tag "Radio target matches" radio)
  1628. (const :tag "Tags" tag)
  1629. (const :tag "Timestamps" date)
  1630. (const :tag "Footnotes" footnote)))
  1631. (defcustom org-make-link-description-function nil
  1632. "Function to use for generating link descriptions from links.
  1633. This function must take two parameters: the first one is the
  1634. link, the second one is the description generated by
  1635. `org-insert-link'. The function should return the description to
  1636. use."
  1637. :group 'org-link
  1638. :type '(choice (const nil) (function)))
  1639. (defgroup org-link-store nil
  1640. "Options concerning storing links in Org mode."
  1641. :tag "Org Store Link"
  1642. :group 'org-link)
  1643. (defcustom org-url-hexify-p t
  1644. "When non-nil, hexify URL when creating a link."
  1645. :type 'boolean
  1646. :version "24.3"
  1647. :group 'org-link-store)
  1648. (defcustom org-email-link-description-format "Email %c: %.30s"
  1649. "Format of the description part of a link to an email or usenet message.
  1650. The following %-escapes will be replaced by corresponding information:
  1651. %F full \"From\" field
  1652. %f name, taken from \"From\" field, address if no name
  1653. %T full \"To\" field
  1654. %t first name in \"To\" field, address if no name
  1655. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1656. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1657. %s subject
  1658. %d date
  1659. %m message-id.
  1660. You may use normal field width specification between the % and the letter.
  1661. This is for example useful to limit the length of the subject.
  1662. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1663. :group 'org-link-store
  1664. :type 'string)
  1665. (defcustom org-from-is-user-regexp
  1666. (let (r1 r2)
  1667. (when (and user-mail-address (not (string= user-mail-address "")))
  1668. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1669. (when (and user-full-name (not (string= user-full-name "")))
  1670. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1671. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1672. "Regexp matched against the \"From:\" header of an email or usenet message.
  1673. It should match if the message is from the user him/herself."
  1674. :group 'org-link-store
  1675. :type 'regexp)
  1676. (defcustom org-context-in-file-links t
  1677. "Non-nil means file links from `org-store-link' contain context.
  1678. \\<org-mode-map>
  1679. A search string will be added to the file name with :: as separator
  1680. and used to find the context when the link is activated by the command
  1681. `org-open-at-point'. When this option is t, the entire active region
  1682. will be placed in the search string of the file link. If set to a
  1683. positive integer, only the first n lines of context will be stored.
  1684. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1685. \\[org-store-link]')
  1686. negates this setting for the duration of the command."
  1687. :group 'org-link-store
  1688. :type '(choice boolean integer))
  1689. (defcustom org-keep-stored-link-after-insertion nil
  1690. "Non-nil means keep link in list for entire session.
  1691. \\<org-mode-map>
  1692. The command `org-store-link' adds a link pointing to the current
  1693. location to an internal list. These links accumulate during a session.
  1694. The command `org-insert-link' can be used to insert links into any
  1695. Org file (offering completion for all stored links).
  1696. When this option is nil, every link which has been inserted once using
  1697. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1698. unused
  1699. links more efficient."
  1700. :group 'org-link-store
  1701. :type 'boolean)
  1702. (defgroup org-link-follow nil
  1703. "Options concerning following links in Org mode."
  1704. :tag "Org Follow Link"
  1705. :group 'org-link)
  1706. (defcustom org-link-translation-function nil
  1707. "Function to translate links with different syntax to Org syntax.
  1708. This can be used to translate links created for example by the Planner
  1709. or emacs-wiki packages to Org syntax.
  1710. The function must accept two parameters, a TYPE containing the link
  1711. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1712. which is everything after the link protocol. It should return a cons
  1713. with possibly modified values of type and path.
  1714. Org contains a function for this, so if you set this variable to
  1715. `org-translate-link-from-planner', you should be able follow many
  1716. links created by planner."
  1717. :group 'org-link-follow
  1718. :type '(choice (const nil) (function)))
  1719. (defcustom org-follow-link-hook nil
  1720. "Hook that is run after a link has been followed."
  1721. :group 'org-link-follow
  1722. :type 'hook)
  1723. (defcustom org-tab-follows-link nil
  1724. "Non-nil means on links TAB will follow the link.
  1725. Needs to be set before org.el is loaded.
  1726. This really should not be used, it does not make sense, and the
  1727. implementation is bad."
  1728. :group 'org-link-follow
  1729. :type 'boolean)
  1730. (defcustom org-return-follows-link nil
  1731. "Non-nil means on links RET will follow the link.
  1732. In tables, the special behavior of RET has precedence."
  1733. :group 'org-link-follow
  1734. :type 'boolean)
  1735. (defcustom org-mouse-1-follows-link
  1736. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1737. "Non-nil means mouse-1 on a link will follow the link.
  1738. A longer mouse click will still set point. Needs to be set
  1739. before org.el is loaded."
  1740. :group 'org-link-follow
  1741. :version "26.1"
  1742. :package-version '(Org . "8.3")
  1743. :type '(choice
  1744. (const :tag "A double click follows the link" double)
  1745. (const :tag "Unconditionally follow the link with mouse-1" t)
  1746. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1747. (defcustom org-mark-ring-length 4
  1748. "Number of different positions to be recorded in the ring.
  1749. Changing this requires a restart of Emacs to work correctly."
  1750. :group 'org-link-follow
  1751. :type 'integer)
  1752. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1753. "Non-nil means internal fuzzy links can only match headlines.
  1754. When nil, the a fuzzy link may point to a target or a named
  1755. construct in the document. When set to the special value
  1756. `query-to-create', offer to create a new headline when none
  1757. matched.
  1758. Spaces and statistics cookies are ignored during heading searches."
  1759. :group 'org-link-follow
  1760. :version "24.1"
  1761. :type '(choice
  1762. (const :tag "Use fuzzy text search" nil)
  1763. (const :tag "Match only exact headline" t)
  1764. (const :tag "Match exact headline or query to create it"
  1765. query-to-create))
  1766. :safe #'symbolp)
  1767. (defcustom org-link-frame-setup
  1768. '((vm . vm-visit-folder-other-frame)
  1769. (vm-imap . vm-visit-imap-folder-other-frame)
  1770. (gnus . org-gnus-no-new-news)
  1771. (file . find-file-other-window)
  1772. (wl . wl-other-frame))
  1773. "Setup the frame configuration for following links.
  1774. When following a link with Emacs, it may often be useful to display
  1775. this link in another window or frame. This variable can be used to
  1776. set this up for the different types of links.
  1777. For VM, use any of
  1778. `vm-visit-folder'
  1779. `vm-visit-folder-other-window'
  1780. `vm-visit-folder-other-frame'
  1781. For Gnus, use any of
  1782. `gnus'
  1783. `gnus-other-frame'
  1784. `org-gnus-no-new-news'
  1785. For FILE, use any of
  1786. `find-file'
  1787. `find-file-other-window'
  1788. `find-file-other-frame'
  1789. For Wanderlust use any of
  1790. `wl'
  1791. `wl-other-frame'
  1792. For the calendar, use the variable `calendar-setup'.
  1793. For BBDB, it is currently only possible to display the matches in
  1794. another window."
  1795. :group 'org-link-follow
  1796. :type '(list
  1797. (cons (const vm)
  1798. (choice
  1799. (const vm-visit-folder)
  1800. (const vm-visit-folder-other-window)
  1801. (const vm-visit-folder-other-frame)))
  1802. (cons (const vm-imap)
  1803. (choice
  1804. (const vm-visit-imap-folder)
  1805. (const vm-visit-imap-folder-other-window)
  1806. (const vm-visit-imap-folder-other-frame)))
  1807. (cons (const gnus)
  1808. (choice
  1809. (const gnus)
  1810. (const gnus-other-frame)
  1811. (const org-gnus-no-new-news)))
  1812. (cons (const file)
  1813. (choice
  1814. (const find-file)
  1815. (const find-file-other-window)
  1816. (const find-file-other-frame)))
  1817. (cons (const wl)
  1818. (choice
  1819. (const wl)
  1820. (const wl-other-frame)))))
  1821. (defcustom org-display-internal-link-with-indirect-buffer nil
  1822. "Non-nil means use indirect buffer to display infile links.
  1823. Activating internal links (from one location in a file to another location
  1824. in the same file) normally just jumps to the location. When the link is
  1825. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1826. is displayed in
  1827. another window. When this option is set, the other window actually displays
  1828. an indirect buffer clone of the current buffer, to avoid any visibility
  1829. changes to the current buffer."
  1830. :group 'org-link-follow
  1831. :type 'boolean)
  1832. (defcustom org-open-non-existing-files nil
  1833. "Non-nil means `org-open-file' will open non-existing files.
  1834. When nil, an error will be generated.
  1835. This variable applies only to external applications because they
  1836. might choke on non-existing files. If the link is to a file that
  1837. will be opened in Emacs, the variable is ignored."
  1838. :group 'org-link-follow
  1839. :type 'boolean)
  1840. (defcustom org-open-directory-means-index-dot-org nil
  1841. "Non-nil means a link to a directory really means to index.org.
  1842. When nil, following a directory link will run dired or open a finder/explorer
  1843. window on that directory."
  1844. :group 'org-link-follow
  1845. :type 'boolean)
  1846. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1847. "Non-nil means ask for confirmation before executing shell links.
  1848. Shell links can be dangerous: just think about a link
  1849. [[shell:rm -rf ~/*][Google Search]]
  1850. This link would show up in your Org document as \"Google Search\",
  1851. but really it would remove your entire home directory.
  1852. Therefore we advise against setting this variable to nil.
  1853. Just change it to `y-or-n-p' if you want to confirm with a
  1854. single keystroke rather than having to type \"yes\"."
  1855. :group 'org-link-follow
  1856. :type '(choice
  1857. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1858. (const :tag "with y-or-n (faster)" y-or-n-p)
  1859. (const :tag "no confirmation (dangerous)" nil)))
  1860. (put 'org-confirm-shell-link-function
  1861. 'safe-local-variable
  1862. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1863. (defcustom org-confirm-shell-link-not-regexp ""
  1864. "A regexp to skip confirmation for shell links."
  1865. :group 'org-link-follow
  1866. :version "24.1"
  1867. :type 'regexp)
  1868. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1869. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1870. Elisp links can be dangerous: just think about a link
  1871. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1872. This link would show up in your Org document as \"Google Search\",
  1873. but really it would remove your entire home directory.
  1874. Therefore we advise against setting this variable to nil.
  1875. Just change it to `y-or-n-p' if you want to confirm with a
  1876. single keystroke rather than having to type \"yes\"."
  1877. :group 'org-link-follow
  1878. :type '(choice
  1879. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1880. (const :tag "with y-or-n (faster)" y-or-n-p)
  1881. (const :tag "no confirmation (dangerous)" nil)))
  1882. (put 'org-confirm-shell-link-function
  1883. 'safe-local-variable
  1884. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1885. (defcustom org-confirm-elisp-link-not-regexp ""
  1886. "A regexp to skip confirmation for Elisp links."
  1887. :group 'org-link-follow
  1888. :version "24.1"
  1889. :type 'regexp)
  1890. (defconst org-file-apps-defaults-gnu
  1891. '((remote . emacs)
  1892. (system . mailcap)
  1893. (t . mailcap))
  1894. "Default file applications on a UNIX or GNU/Linux system.
  1895. See `org-file-apps'.")
  1896. (defconst org-file-apps-defaults-macosx
  1897. '((remote . emacs)
  1898. (system . "open %s")
  1899. ("ps.gz" . "gv %s")
  1900. ("eps.gz" . "gv %s")
  1901. ("dvi" . "xdvi %s")
  1902. ("fig" . "xfig %s")
  1903. (t . "open %s"))
  1904. "Default file applications on a macOS system.
  1905. The system \"open\" is known as a default, but we use X11 applications
  1906. for some files for which the OS does not have a good default.
  1907. See `org-file-apps'.")
  1908. (defconst org-file-apps-defaults-windowsnt
  1909. (list '(remote . emacs)
  1910. (cons 'system (lambda (file _path)
  1911. (with-no-warnings (w32-shell-execute "open" file))))
  1912. (cons t (lambda (file _path)
  1913. (with-no-warnings (w32-shell-execute "open" file)))))
  1914. "Default file applications on a Windows NT system.
  1915. The system \"open\" is used for most files.
  1916. See `org-file-apps'.")
  1917. (defcustom org-file-apps
  1918. '((auto-mode . emacs)
  1919. ("\\.mm\\'" . default)
  1920. ("\\.x?html?\\'" . default)
  1921. ("\\.pdf\\'" . default))
  1922. "External applications for opening `file:path' items in a document.
  1923. \\<org-mode-map>\
  1924. Org mode uses system defaults for different file types, but
  1925. you can use this variable to set the application for a given file
  1926. extension. The entries in this list are cons cells where the car identifies
  1927. files and the cdr the corresponding command.
  1928. Possible values for the file identifier are:
  1929. \"string\" A string as a file identifier can be interpreted in different
  1930. ways, depending on its contents:
  1931. - Alphanumeric characters only:
  1932. Match links with this file extension.
  1933. Example: (\"pdf\" . \"evince %s\")
  1934. to open PDFs with evince.
  1935. - Regular expression: Match links where the
  1936. filename matches the regexp. If you want to
  1937. use groups here, use shy groups.
  1938. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1939. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1940. to open *.html and *.xhtml with firefox.
  1941. - Regular expression which contains (non-shy) groups:
  1942. Match links where the whole link, including \"::\", and
  1943. anything after that, matches the regexp.
  1944. In a custom command string, %1, %2, etc. are replaced with
  1945. the parts of the link that were matched by the groups.
  1946. For backwards compatibility, if a command string is given
  1947. that does not use any of the group matches, this case is
  1948. handled identically to the second one (i.e. match against
  1949. file name only).
  1950. In a custom function, you can access the group matches with
  1951. (match-string n link).
  1952. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1953. \"evince -p %1 %s\")
  1954. to open [[file:document.pdf::5]] with evince at page 5.
  1955. `directory' Matches a directory
  1956. `remote' Matches a remote file, accessible through tramp or efs.
  1957. Remote files most likely should be visited through Emacs
  1958. because external applications cannot handle such paths.
  1959. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1960. so all files Emacs knows how to handle. Using this with
  1961. command `emacs' will open most files in Emacs. Beware that this
  1962. will also open html files inside Emacs, unless you add
  1963. (\"html\" . default) to the list as well.
  1964. `system' The system command to open files, like `open' on Windows
  1965. and macOS, and mailcap under GNU/Linux. This is the command
  1966. that will be selected if you call `org-open-at-point' with a
  1967. double prefix argument (`\\[universal-argument] \
  1968. \\[universal-argument] \\[org-open-at-point]').
  1969. t Default for files not matched by any of the other options.
  1970. Possible values for the command are:
  1971. `emacs' The file will be visited by the current Emacs process.
  1972. `default' Use the default application for this file type, which is the
  1973. association for t in the list, most likely in the system-specific
  1974. part. This can be used to overrule an unwanted setting in the
  1975. system-specific variable.
  1976. `system' Use the system command for opening files, like \"open\".
  1977. This command is specified by the entry whose car is `system'.
  1978. Most likely, the system-specific version of this variable
  1979. does define this command, but you can overrule/replace it
  1980. here.
  1981. `mailcap' Use command specified in the mailcaps.
  1982. string A command to be executed by a shell; %s will be replaced
  1983. by the path to the file.
  1984. function A Lisp function, which will be called with two arguments:
  1985. the file path and the original link string, without the
  1986. \"file:\" prefix.
  1987. For more examples, see the system specific constants
  1988. `org-file-apps-defaults-macosx'
  1989. `org-file-apps-defaults-windowsnt'
  1990. `org-file-apps-defaults-gnu'."
  1991. :group 'org-link-follow
  1992. :type '(repeat
  1993. (cons (choice :value ""
  1994. (string :tag "Extension")
  1995. (const :tag "System command to open files" system)
  1996. (const :tag "Default for unrecognized files" t)
  1997. (const :tag "Remote file" remote)
  1998. (const :tag "Links to a directory" directory)
  1999. (const :tag "Any files that have Emacs modes"
  2000. auto-mode))
  2001. (choice :value ""
  2002. (const :tag "Visit with Emacs" emacs)
  2003. (const :tag "Use default" default)
  2004. (const :tag "Use the system command" system)
  2005. (string :tag "Command")
  2006. (function :tag "Function")))))
  2007. (defcustom org-doi-server-url "http://dx.doi.org/"
  2008. "The URL of the DOI server."
  2009. :type 'string
  2010. :version "24.3"
  2011. :group 'org-link-follow)
  2012. (defgroup org-refile nil
  2013. "Options concerning refiling entries in Org mode."
  2014. :tag "Org Refile"
  2015. :group 'org)
  2016. (defcustom org-directory "~/org"
  2017. "Directory with Org files.
  2018. This is just a default location to look for Org files. There is no need
  2019. at all to put your files into this directory. It is used in the
  2020. following situations:
  2021. 1. When a capture template specifies a target file that is not an
  2022. absolute path. The path will then be interpreted relative to
  2023. `org-directory'
  2024. 2. When the value of variable `org-agenda-files' is a single file, any
  2025. relative paths in this file will be taken as relative to
  2026. `org-directory'."
  2027. :group 'org-refile
  2028. :group 'org-capture
  2029. :type 'directory)
  2030. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2031. "Default target for storing notes.
  2032. Used as a fall back file for org-capture.el, for templates that
  2033. do not specify a target file."
  2034. :group 'org-refile
  2035. :group 'org-capture
  2036. :type 'file)
  2037. (defcustom org-reverse-note-order nil
  2038. "Non-nil means store new notes at the beginning of a file or entry.
  2039. When nil, new notes will be filed to the end of a file or entry.
  2040. This can also be a list with cons cells of regular expressions that
  2041. are matched against file names, and values."
  2042. :group 'org-capture
  2043. :group 'org-refile
  2044. :type '(choice
  2045. (const :tag "Reverse always" t)
  2046. (const :tag "Reverse never" nil)
  2047. (repeat :tag "By file name regexp"
  2048. (cons regexp boolean))))
  2049. (defcustom org-log-refile nil
  2050. "Information to record when a task is refiled.
  2051. Possible values are:
  2052. nil Don't add anything
  2053. time Add a time stamp to the task
  2054. note Prompt for a note and add it with template `org-log-note-headings'
  2055. This option can also be set with on a per-file-basis with
  2056. #+STARTUP: nologrefile
  2057. #+STARTUP: logrefile
  2058. #+STARTUP: lognoterefile
  2059. You can have local logging settings for a subtree by setting the LOGGING
  2060. property to one or more of these keywords.
  2061. When bulk-refiling from the agenda, the value `note' is forbidden and
  2062. will temporarily be changed to `time'."
  2063. :group 'org-refile
  2064. :group 'org-progress
  2065. :version "24.1"
  2066. :type '(choice
  2067. (const :tag "No logging" nil)
  2068. (const :tag "Record timestamp" time)
  2069. (const :tag "Record timestamp with note." note)))
  2070. (defcustom org-refile-targets nil
  2071. "Targets for refiling entries with `\\[org-refile]'.
  2072. This is a list of cons cells. Each cell contains:
  2073. - a specification of the files to be considered, either a list of files,
  2074. or a symbol whose function or variable value will be used to retrieve
  2075. a file name or a list of file names. If you use `org-agenda-files' for
  2076. that, all agenda files will be scanned for targets. Nil means consider
  2077. headings in the current buffer.
  2078. - A specification of how to find candidate refile targets. This may be
  2079. any of:
  2080. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2081. This tag has to be present in all target headlines, inheritance will
  2082. not be considered.
  2083. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2084. todo keyword.
  2085. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2086. headlines that are refiling targets.
  2087. - a cons cell (:level . N). Any headline of level N is considered a target.
  2088. Note that, when `org-odd-levels-only' is set, level corresponds to
  2089. order in hierarchy, not to the number of stars.
  2090. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2091. Note that, when `org-odd-levels-only' is set, level corresponds to
  2092. order in hierarchy, not to the number of stars.
  2093. Each element of this list generates a set of possible targets.
  2094. The union of these sets is presented (with completion) to
  2095. the user by `org-refile'.
  2096. You can set the variable `org-refile-target-verify-function' to a function
  2097. to verify each headline found by the simple criteria above.
  2098. When this variable is nil, all top-level headlines in the current buffer
  2099. are used, equivalent to the value `((nil . (:level . 1))'."
  2100. :group 'org-refile
  2101. :type '(repeat
  2102. (cons
  2103. (choice :value org-agenda-files
  2104. (const :tag "All agenda files" org-agenda-files)
  2105. (const :tag "Current buffer" nil)
  2106. (function) (variable) (file))
  2107. (choice :tag "Identify target headline by"
  2108. (cons :tag "Specific tag" (const :value :tag) (string))
  2109. (cons :tag "TODO keyword" (const :value :todo) (string))
  2110. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2111. (cons :tag "Level number" (const :value :level) (integer))
  2112. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2113. (defcustom org-refile-target-verify-function nil
  2114. "Function to verify if the headline at point should be a refile target.
  2115. The function will be called without arguments, with point at the
  2116. beginning of the headline. It should return t and leave point
  2117. where it is if the headline is a valid target for refiling.
  2118. If the target should not be selected, the function must return nil.
  2119. In addition to this, it may move point to a place from where the search
  2120. should be continued. For example, the function may decide that the entire
  2121. subtree of the current entry should be excluded and move point to the end
  2122. of the subtree."
  2123. :group 'org-refile
  2124. :type '(choice
  2125. (const nil)
  2126. (function)))
  2127. (defcustom org-refile-use-cache nil
  2128. "Non-nil means cache refile targets to speed up the process.
  2129. \\<org-mode-map>\
  2130. The cache for a particular file will be updated automatically when
  2131. the buffer has been killed, or when any of the marker used for flagging
  2132. refile targets no longer points at a live buffer.
  2133. If you have added new entries to a buffer that might themselves be targets,
  2134. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2135. if you find that easier, \
  2136. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2137. \\[org-refile]'."
  2138. :group 'org-refile
  2139. :version "24.1"
  2140. :type 'boolean)
  2141. (defcustom org-refile-use-outline-path nil
  2142. "Non-nil means provide refile targets as paths.
  2143. So a level 3 headline will be available as level1/level2/level3.
  2144. When the value is `file', also include the file name (without directory)
  2145. into the path. In this case, you can also stop the completion after
  2146. the file name, to get entries inserted as top level in the file.
  2147. When `full-file-path', include the full file path.
  2148. When `buffer-name', use the buffer name."
  2149. :group 'org-refile
  2150. :type '(choice
  2151. (const :tag "Not" nil)
  2152. (const :tag "Yes" t)
  2153. (const :tag "Start with file name" file)
  2154. (const :tag "Start with full file path" full-file-path)
  2155. (const :tag "Start with buffer name" buffer-name)))
  2156. (defcustom org-outline-path-complete-in-steps t
  2157. "Non-nil means complete the outline path in hierarchical steps.
  2158. When Org uses the refile interface to select an outline path (see
  2159. `org-refile-use-outline-path'), the completion of the path can be
  2160. done in a single go, or it can be done in steps down the headline
  2161. hierarchy. Going in steps is probably the best if you do not use
  2162. a special completion package like `ido' or `icicles'. However,
  2163. when using these packages, going in one step can be very fast,
  2164. while still showing the whole path to the entry."
  2165. :group 'org-refile
  2166. :type 'boolean)
  2167. (defcustom org-refile-allow-creating-parent-nodes nil
  2168. "Non-nil means allow the creation of new nodes as refile targets.
  2169. New nodes are then created by adding \"/new node name\" to the completion
  2170. of an existing node. When the value of this variable is `confirm',
  2171. new node creation must be confirmed by the user (recommended).
  2172. When nil, the completion must match an existing entry.
  2173. Note that, if the new heading is not seen by the criteria
  2174. listed in `org-refile-targets', multiple instances of the same
  2175. heading would be created by trying again to file under the new
  2176. heading."
  2177. :group 'org-refile
  2178. :type '(choice
  2179. (const :tag "Never" nil)
  2180. (const :tag "Always" t)
  2181. (const :tag "Prompt for confirmation" confirm)))
  2182. (defcustom org-refile-active-region-within-subtree nil
  2183. "Non-nil means also refile active region within a subtree.
  2184. By default `org-refile' doesn't allow refiling regions if they
  2185. don't contain a set of subtrees, but it might be convenient to
  2186. do so sometimes: in that case, the first line of the region is
  2187. converted to a headline before refiling."
  2188. :group 'org-refile
  2189. :version "24.1"
  2190. :type 'boolean)
  2191. (defgroup org-todo nil
  2192. "Options concerning TODO items in Org mode."
  2193. :tag "Org TODO"
  2194. :group 'org)
  2195. (defgroup org-progress nil
  2196. "Options concerning Progress logging in Org mode."
  2197. :tag "Org Progress"
  2198. :group 'org-time)
  2199. (defvar org-todo-interpretation-widgets
  2200. '((:tag "Sequence (cycling hits every state)" sequence)
  2201. (:tag "Type (cycling directly to DONE)" type))
  2202. "The available interpretation symbols for customizing `org-todo-keywords'.
  2203. Interested libraries should add to this list.")
  2204. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2205. "List of TODO entry keyword sequences and their interpretation.
  2206. \\<org-mode-map>This is a list of sequences.
  2207. Each sequence starts with a symbol, either `sequence' or `type',
  2208. indicating if the keywords should be interpreted as a sequence of
  2209. action steps, or as different types of TODO items. The first
  2210. keywords are states requiring action - these states will select a headline
  2211. for inclusion into the global TODO list Org produces. If one of the
  2212. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2213. signify that no further action is necessary. If \"|\" is not found,
  2214. the last keyword is treated as the only DONE state of the sequence.
  2215. The command `\\[org-todo]' cycles an entry through these states, and one
  2216. additional state where no keyword is present. For details about this
  2217. cycling, see the manual.
  2218. TODO keywords and interpretation can also be set on a per-file basis with
  2219. the special #+SEQ_TODO and #+TYP_TODO lines.
  2220. Each keyword can optionally specify a character for fast state selection
  2221. \(in combination with the variable `org-use-fast-todo-selection')
  2222. and specifiers for state change logging, using the same syntax that
  2223. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2224. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2225. indicates to record a time stamp each time this state is selected.
  2226. Each keyword may also specify if a timestamp or a note should be
  2227. recorded when entering or leaving the state, by adding additional
  2228. characters in the parenthesis after the keyword. This looks like this:
  2229. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2230. record only the time of the state change. With X and Y being either
  2231. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2232. Y when leaving the state if and only if the *target* state does not
  2233. define X. You may omit any of the fast-selection key or X or /Y,
  2234. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2235. For backward compatibility, this variable may also be just a list
  2236. of keywords. In this case the interpretation (sequence or type) will be
  2237. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2238. :group 'org-todo
  2239. :group 'org-keywords
  2240. :type '(choice
  2241. (repeat :tag "Old syntax, just keywords"
  2242. (string :tag "Keyword"))
  2243. (repeat :tag "New syntax"
  2244. (cons
  2245. (choice
  2246. :tag "Interpretation"
  2247. ;;Quick and dirty way to see
  2248. ;;`org-todo-interpretations'. This takes the
  2249. ;;place of item arguments
  2250. :convert-widget
  2251. (lambda (widget)
  2252. (widget-put widget
  2253. :args (mapcar
  2254. (lambda (x)
  2255. (widget-convert
  2256. (cons 'const x)))
  2257. org-todo-interpretation-widgets))
  2258. widget))
  2259. (repeat
  2260. (string :tag "Keyword"))))))
  2261. (defvar-local org-todo-keywords-1 nil
  2262. "All TODO and DONE keywords active in a buffer.")
  2263. (defvar org-todo-keywords-for-agenda nil)
  2264. (defvar org-done-keywords-for-agenda nil)
  2265. (defvar org-todo-keyword-alist-for-agenda nil)
  2266. (defvar org-tag-alist-for-agenda nil
  2267. "Alist of all tags from all agenda files.")
  2268. (defvar org-tag-groups-alist-for-agenda nil
  2269. "Alist of all groups tags from all current agenda files.")
  2270. (defvar-local org-tag-groups-alist nil)
  2271. (defvar org-agenda-contributing-files nil)
  2272. (defvar-local org-current-tag-alist nil
  2273. "Alist of all tag groups in current buffer.
  2274. This variable takes into consideration `org-tag-alist',
  2275. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2276. (defvar-local org-not-done-keywords nil)
  2277. (defvar-local org-done-keywords nil)
  2278. (defvar-local org-todo-heads nil)
  2279. (defvar-local org-todo-sets nil)
  2280. (defvar-local org-todo-log-states nil)
  2281. (defvar-local org-todo-kwd-alist nil)
  2282. (defvar-local org-todo-key-alist nil)
  2283. (defvar-local org-todo-key-trigger nil)
  2284. (defcustom org-todo-interpretation 'sequence
  2285. "Controls how TODO keywords are interpreted.
  2286. This variable is in principle obsolete and is only used for
  2287. backward compatibility, if the interpretation of todo keywords is
  2288. not given already in `org-todo-keywords'. See that variable for
  2289. more information."
  2290. :group 'org-todo
  2291. :group 'org-keywords
  2292. :type '(choice (const sequence)
  2293. (const type)))
  2294. (defcustom org-use-fast-todo-selection t
  2295. "\\<org-mode-map>\
  2296. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2297. This variable describes if and under what circumstances the cycling
  2298. mechanism for TODO keywords will be replaced by a single-key, direct
  2299. selection scheme.
  2300. When nil, fast selection is never used.
  2301. When the symbol `prefix', it will be used when `org-todo' is called
  2302. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2303. in an Org buffer, and
  2304. `\\[universal-argument] t' in an agenda buffer.
  2305. When t, fast selection is used by default. In this case, the prefix
  2306. argument forces cycling instead.
  2307. In all cases, the special interface is only used if access keys have
  2308. actually been assigned by the user, i.e. if keywords in the configuration
  2309. are followed by a letter in parenthesis, like TODO(t)."
  2310. :group 'org-todo
  2311. :type '(choice
  2312. (const :tag "Never" nil)
  2313. (const :tag "By default" t)
  2314. (const :tag "Only with C-u C-c C-t" prefix)))
  2315. (defcustom org-provide-todo-statistics t
  2316. "Non-nil means update todo statistics after insert and toggle.
  2317. ALL-HEADLINES means update todo statistics by including headlines
  2318. with no TODO keyword as well, counting them as not done.
  2319. A list of TODO keywords means the same, but skip keywords that are
  2320. not in this list.
  2321. When set to a list of two lists, the first list contains keywords
  2322. to consider as TODO keywords, the second list contains keywords
  2323. to consider as DONE keywords.
  2324. When this is set, todo statistics is updated in the parent of the
  2325. current entry each time a todo state is changed."
  2326. :group 'org-todo
  2327. :type '(choice
  2328. (const :tag "Yes, only for TODO entries" t)
  2329. (const :tag "Yes, including all entries" all-headlines)
  2330. (repeat :tag "Yes, for TODOs in this list"
  2331. (string :tag "TODO keyword"))
  2332. (list :tag "Yes, for TODOs and DONEs in these lists"
  2333. (repeat (string :tag "TODO keyword"))
  2334. (repeat (string :tag "DONE keyword")))
  2335. (other :tag "No TODO statistics" nil)))
  2336. (defcustom org-hierarchical-todo-statistics t
  2337. "Non-nil means TODO statistics covers just direct children.
  2338. When nil, all entries in the subtree are considered.
  2339. This has only an effect if `org-provide-todo-statistics' is set.
  2340. To set this to nil for only a single subtree, use a COOKIE_DATA
  2341. property and include the word \"recursive\" into the value."
  2342. :group 'org-todo
  2343. :type 'boolean)
  2344. (defcustom org-after-todo-state-change-hook nil
  2345. "Hook which is run after the state of a TODO item was changed.
  2346. The new state (a string with a TODO keyword, or nil) is available in the
  2347. Lisp variable `org-state'."
  2348. :group 'org-todo
  2349. :type 'hook)
  2350. (defvar org-blocker-hook nil
  2351. "Hook for functions that are allowed to block a state change.
  2352. Functions in this hook should not modify the buffer.
  2353. Each function gets as its single argument a property list,
  2354. see `org-trigger-hook' for more information about this list.
  2355. If any of the functions in this hook returns nil, the state change
  2356. is blocked.")
  2357. (defvar org-trigger-hook nil
  2358. "Hook for functions that are triggered by a state change.
  2359. Each function gets as its single argument a property list with at
  2360. least the following elements:
  2361. (:type type-of-change :position pos-at-entry-start
  2362. :from old-state :to new-state)
  2363. Depending on the type, more properties may be present.
  2364. This mechanism is currently implemented for:
  2365. TODO state changes
  2366. ------------------
  2367. :type todo-state-change
  2368. :from previous state (keyword as a string), or nil, or a symbol
  2369. `todo' or `done', to indicate the general type of state.
  2370. :to new state, like in :from")
  2371. (defcustom org-enforce-todo-dependencies nil
  2372. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2373. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2374. be blocked if any prior sibling is not yet done.
  2375. Finally, if the parent is blocked because of ordered siblings of its own,
  2376. the child will also be blocked."
  2377. :set (lambda (var val)
  2378. (set var val)
  2379. (if val
  2380. (add-hook 'org-blocker-hook
  2381. 'org-block-todo-from-children-or-siblings-or-parent)
  2382. (remove-hook 'org-blocker-hook
  2383. 'org-block-todo-from-children-or-siblings-or-parent)))
  2384. :group 'org-todo
  2385. :type 'boolean)
  2386. (defcustom org-enforce-todo-checkbox-dependencies nil
  2387. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2388. When this is nil, checkboxes have no influence on switching TODO states.
  2389. When non-nil, you first need to check off all check boxes before the TODO
  2390. entry can be switched to DONE.
  2391. This variable needs to be set before org.el is loaded, and you need to
  2392. restart Emacs after a change to make the change effective. The only way
  2393. to change is while Emacs is running is through the customize interface."
  2394. :set (lambda (var val)
  2395. (set var val)
  2396. (if val
  2397. (add-hook 'org-blocker-hook
  2398. 'org-block-todo-from-checkboxes)
  2399. (remove-hook 'org-blocker-hook
  2400. 'org-block-todo-from-checkboxes)))
  2401. :group 'org-todo
  2402. :type 'boolean)
  2403. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2404. "Non-nil means inserting a TODO heading is treated as state change.
  2405. So when the command `\\[org-insert-todo-heading]' is used, state change
  2406. logging will apply if appropriate. When nil, the new TODO item will
  2407. be inserted directly, and no logging will take place."
  2408. :group 'org-todo
  2409. :type 'boolean)
  2410. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2411. "Non-nil means switching TODO states with S-cursor counts as state change.
  2412. This is the default behavior. However, setting this to nil allows a
  2413. convenient way to select a TODO state and bypass any logging associated
  2414. with that."
  2415. :group 'org-todo
  2416. :type 'boolean)
  2417. (defcustom org-todo-state-tags-triggers nil
  2418. "Tag changes that should be triggered by TODO state changes.
  2419. This is a list. Each entry is
  2420. (state-change (tag . flag) .......)
  2421. State-change can be a string with a state, and empty string to indicate the
  2422. state that has no TODO keyword, or it can be one of the symbols `todo'
  2423. or `done', meaning any not-done or done state, respectively."
  2424. :group 'org-todo
  2425. :group 'org-tags
  2426. :type '(repeat
  2427. (cons (choice :tag "When changing to"
  2428. (const :tag "Not-done state" todo)
  2429. (const :tag "Done state" done)
  2430. (string :tag "State"))
  2431. (repeat
  2432. (cons :tag "Tag action"
  2433. (string :tag "Tag")
  2434. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2435. (defcustom org-log-done nil
  2436. "Information to record when a task moves to the DONE state.
  2437. Possible values are:
  2438. nil Don't add anything, just change the keyword
  2439. time Add a time stamp to the task
  2440. note Prompt for a note and add it with template `org-log-note-headings'
  2441. This option can also be set with on a per-file-basis with
  2442. #+STARTUP: nologdone
  2443. #+STARTUP: logdone
  2444. #+STARTUP: lognotedone
  2445. You can have local logging settings for a subtree by setting the LOGGING
  2446. property to one or more of these keywords."
  2447. :group 'org-todo
  2448. :group 'org-progress
  2449. :type '(choice
  2450. (const :tag "No logging" nil)
  2451. (const :tag "Record CLOSED timestamp" time)
  2452. (const :tag "Record CLOSED timestamp with note." note)))
  2453. ;; Normalize old uses of org-log-done.
  2454. (cond
  2455. ((eq org-log-done t) (setq org-log-done 'time))
  2456. ((and (listp org-log-done) (memq 'done org-log-done))
  2457. (setq org-log-done 'note)))
  2458. (defcustom org-log-reschedule nil
  2459. "Information to record when the scheduling date of a tasks is modified.
  2460. Possible values are:
  2461. nil Don't add anything, just change the date
  2462. time Add a time stamp to the task
  2463. note Prompt for a note and add it with template `org-log-note-headings'
  2464. This option can also be set with on a per-file-basis with
  2465. #+STARTUP: nologreschedule
  2466. #+STARTUP: logreschedule
  2467. #+STARTUP: lognotereschedule"
  2468. :group 'org-todo
  2469. :group 'org-progress
  2470. :type '(choice
  2471. (const :tag "No logging" nil)
  2472. (const :tag "Record timestamp" time)
  2473. (const :tag "Record timestamp with note." note)))
  2474. (defcustom org-log-redeadline nil
  2475. "Information to record when the deadline date of a tasks is modified.
  2476. Possible values are:
  2477. nil Don't add anything, just change the date
  2478. time Add a time stamp to the task
  2479. note Prompt for a note and add it with template `org-log-note-headings'
  2480. This option can also be set with on a per-file-basis with
  2481. #+STARTUP: nologredeadline
  2482. #+STARTUP: logredeadline
  2483. #+STARTUP: lognoteredeadline
  2484. You can have local logging settings for a subtree by setting the LOGGING
  2485. property to one or more of these keywords."
  2486. :group 'org-todo
  2487. :group 'org-progress
  2488. :type '(choice
  2489. (const :tag "No logging" nil)
  2490. (const :tag "Record timestamp" time)
  2491. (const :tag "Record timestamp with note." note)))
  2492. (defcustom org-log-note-clock-out nil
  2493. "Non-nil means record a note when clocking out of an item.
  2494. This can also be configured on a per-file basis by adding one of
  2495. the following lines anywhere in the buffer:
  2496. #+STARTUP: lognoteclock-out
  2497. #+STARTUP: nolognoteclock-out"
  2498. :group 'org-todo
  2499. :group 'org-progress
  2500. :type 'boolean)
  2501. (defcustom org-log-done-with-time t
  2502. "Non-nil means the CLOSED time stamp will contain date and time.
  2503. When nil, only the date will be recorded."
  2504. :group 'org-progress
  2505. :type 'boolean)
  2506. (defcustom org-log-note-headings
  2507. '((done . "CLOSING NOTE %t")
  2508. (state . "State %-12s from %-12S %t")
  2509. (note . "Note taken on %t")
  2510. (reschedule . "Rescheduled from %S on %t")
  2511. (delschedule . "Not scheduled, was %S on %t")
  2512. (redeadline . "New deadline from %S on %t")
  2513. (deldeadline . "Removed deadline, was %S on %t")
  2514. (refile . "Refiled on %t")
  2515. (clock-out . ""))
  2516. "Headings for notes added to entries.
  2517. The value is an alist, with the car being a symbol indicating the
  2518. note context, and the cdr is the heading to be used. The heading
  2519. may also be the empty string. The following placeholders can be
  2520. used:
  2521. %t a time stamp.
  2522. %T an active time stamp instead the default inactive one
  2523. %d a short-format time stamp.
  2524. %D an active short-format time stamp.
  2525. %s the new TODO state or time stamp (inactive), in double quotes.
  2526. %S the old TODO state or time stamp (inactive), in double quotes.
  2527. %u the user name.
  2528. %U full user name.
  2529. In fact, it is not a good idea to change the `state' entry,
  2530. because Agenda Log mode depends on the format of these entries."
  2531. :group 'org-todo
  2532. :group 'org-progress
  2533. :type '(list :greedy t
  2534. (cons (const :tag "Heading when closing an item" done) string)
  2535. (cons (const :tag
  2536. "Heading when changing todo state (todo sequence only)"
  2537. state) string)
  2538. (cons (const :tag "Heading when just taking a note" note) string)
  2539. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2540. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2541. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2542. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2543. (cons (const :tag "Heading when refiling" refile) string)
  2544. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2545. (unless (assq 'note org-log-note-headings)
  2546. (push '(note . "%t") org-log-note-headings))
  2547. (defcustom org-log-into-drawer nil
  2548. "Non-nil means insert state change notes and time stamps into a drawer.
  2549. When nil, state changes notes will be inserted after the headline and
  2550. any scheduling and clock lines, but not inside a drawer.
  2551. The value of this variable should be the name of the drawer to use.
  2552. LOGBOOK is proposed as the default drawer for this purpose, you can
  2553. also set this to a string to define the drawer of your choice.
  2554. A value of t is also allowed, representing \"LOGBOOK\".
  2555. A value of t or nil can also be set with on a per-file-basis with
  2556. #+STARTUP: logdrawer
  2557. #+STARTUP: nologdrawer
  2558. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2559. will be ignored.
  2560. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2561. a subtree.
  2562. Do not check directly this variable in a Lisp program. Call
  2563. function `org-log-into-drawer' instead."
  2564. :group 'org-todo
  2565. :group 'org-progress
  2566. :type '(choice
  2567. (const :tag "Not into a drawer" nil)
  2568. (const :tag "LOGBOOK" t)
  2569. (string :tag "Other")))
  2570. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2571. (defun org-log-into-drawer ()
  2572. "Name of the log drawer, as a string, or nil.
  2573. This is the value of `org-log-into-drawer'. However, if the
  2574. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2575. be used instead of the default value."
  2576. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2577. (cond ((equal p "nil") nil)
  2578. ((equal p "t") "LOGBOOK")
  2579. ((stringp p) p)
  2580. (p "LOGBOOK")
  2581. ((stringp org-log-into-drawer) org-log-into-drawer)
  2582. (org-log-into-drawer "LOGBOOK"))))
  2583. (defcustom org-log-state-notes-insert-after-drawers nil
  2584. "Non-nil means insert state change notes after any drawers in entry.
  2585. Only the drawers that *immediately* follow the headline and the
  2586. deadline/scheduled line are skipped.
  2587. When nil, insert notes right after the heading and perhaps the line
  2588. with deadline/scheduling if present.
  2589. This variable will have no effect if `org-log-into-drawer' is
  2590. set."
  2591. :group 'org-todo
  2592. :group 'org-progress
  2593. :type 'boolean)
  2594. (defcustom org-log-states-order-reversed t
  2595. "Non-nil means the latest state note will be directly after heading.
  2596. When nil, the state change notes will be ordered according to time.
  2597. This option can also be set with on a per-file-basis with
  2598. #+STARTUP: logstatesreversed
  2599. #+STARTUP: nologstatesreversed"
  2600. :group 'org-todo
  2601. :group 'org-progress
  2602. :type 'boolean)
  2603. (defcustom org-todo-repeat-to-state nil
  2604. "The TODO state to which a repeater should return the repeating task.
  2605. By default this is the first task of a TODO sequence or the
  2606. previous state of a TYPE_TODO set. But you can specify to use
  2607. the previous state in a TODO sequence or a string.
  2608. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2609. entry, which has precedence over this option."
  2610. :group 'org-todo
  2611. :version "24.1"
  2612. :type '(choice (const :tag "Use the previous TODO state" t)
  2613. (const :tag "Use the head of the TODO sequence" nil)
  2614. (string :tag "Use a specific TODO state")))
  2615. (defcustom org-log-repeat 'time
  2616. "Non-nil means record moving through the DONE state when triggering repeat.
  2617. An auto-repeating task is immediately switched back to TODO when
  2618. marked DONE. If you are not logging state changes (by adding \"@\"
  2619. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2620. record a closing note, there will be no record of the task moving
  2621. through DONE. This variable forces taking a note anyway.
  2622. nil Don't force a record
  2623. time Record a time stamp
  2624. note Prompt for a note and add it with template `org-log-note-headings'
  2625. This option can also be set with on a per-file-basis with
  2626. #+STARTUP: nologrepeat
  2627. #+STARTUP: logrepeat
  2628. #+STARTUP: lognoterepeat
  2629. You can have local logging settings for a subtree by setting the LOGGING
  2630. property to one or more of these keywords."
  2631. :group 'org-todo
  2632. :group 'org-progress
  2633. :type '(choice
  2634. (const :tag "Don't force a record" nil)
  2635. (const :tag "Force recording the DONE state" time)
  2636. (const :tag "Force recording a note with the DONE state" note)))
  2637. (defgroup org-priorities nil
  2638. "Priorities in Org mode."
  2639. :tag "Org Priorities"
  2640. :group 'org-todo)
  2641. (defcustom org-enable-priority-commands t
  2642. "Non-nil means priority commands are active.
  2643. When nil, these commands will be disabled, so that you never accidentally
  2644. set a priority."
  2645. :group 'org-priorities
  2646. :type 'boolean)
  2647. (defcustom org-highest-priority ?A
  2648. "The highest priority of TODO items. A character like ?A, ?B etc.
  2649. Must have a smaller ASCII number than `org-lowest-priority'."
  2650. :group 'org-priorities
  2651. :type 'character)
  2652. (defcustom org-lowest-priority ?C
  2653. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2654. Must have a larger ASCII number than `org-highest-priority'."
  2655. :group 'org-priorities
  2656. :type 'character)
  2657. (defcustom org-default-priority ?B
  2658. "The default priority of TODO items.
  2659. This is the priority an item gets if no explicit priority is given.
  2660. When starting to cycle on an empty priority the first step in the cycle
  2661. depends on `org-priority-start-cycle-with-default'. The resulting first
  2662. step priority must not exceed the range from `org-highest-priority' to
  2663. `org-lowest-priority' which means that `org-default-priority' has to be
  2664. in this range exclusive or inclusive the range boundaries. Else the
  2665. first step refuses to set the default and the second will fall back
  2666. to (depending on the command used) the highest or lowest priority."
  2667. :group 'org-priorities
  2668. :type 'character)
  2669. (defcustom org-priority-start-cycle-with-default t
  2670. "Non-nil means start with default priority when starting to cycle.
  2671. When this is nil, the first step in the cycle will be (depending on the
  2672. command used) one higher or lower than the default priority.
  2673. See also `org-default-priority'."
  2674. :group 'org-priorities
  2675. :type 'boolean)
  2676. (defcustom org-get-priority-function nil
  2677. "Function to extract the priority from a string.
  2678. The string is normally the headline. If this is nil Org computes the
  2679. priority from the priority cookie like [#A] in the headline. It returns
  2680. an integer, increasing by 1000 for each priority level.
  2681. The user can set a different function here, which should take a string
  2682. as an argument and return the numeric priority."
  2683. :group 'org-priorities
  2684. :version "24.1"
  2685. :type '(choice
  2686. (const nil)
  2687. (function)))
  2688. (defgroup org-time nil
  2689. "Options concerning time stamps and deadlines in Org mode."
  2690. :tag "Org Time"
  2691. :group 'org)
  2692. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2693. "Number of minutes to round time stamps to.
  2694. \\<org-mode-map>\
  2695. These are two values, the first applies when first creating a time stamp.
  2696. The second applies when changing it with the commands `S-up' and `S-down'.
  2697. When changing the time stamp, this means that it will change in steps
  2698. of N minutes, as given by the second value.
  2699. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2700. numbers should be factors of 60, so for example 5, 10, 15.
  2701. When this is larger than 1, you can still force an exact time stamp by using
  2702. a double prefix argument to a time stamp command like \
  2703. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2704. and by using a prefix arg to `S-up/down' to specify the exact number
  2705. of minutes to shift."
  2706. :group 'org-time
  2707. :get (lambda (var) ; Make sure both elements are there
  2708. (if (integerp (default-value var))
  2709. (list (default-value var) 5)
  2710. (default-value var)))
  2711. :type '(list
  2712. (integer :tag "when inserting times")
  2713. (integer :tag "when modifying times")))
  2714. ;; Normalize old customizations of this variable.
  2715. (when (integerp org-time-stamp-rounding-minutes)
  2716. (setq org-time-stamp-rounding-minutes
  2717. (list org-time-stamp-rounding-minutes
  2718. org-time-stamp-rounding-minutes)))
  2719. (defcustom org-display-custom-times nil
  2720. "Non-nil means overlay custom formats over all time stamps.
  2721. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2722. To turn this on on a per-file basis, insert anywhere in the file:
  2723. #+STARTUP: customtime"
  2724. :group 'org-time
  2725. :set 'set-default
  2726. :type 'sexp)
  2727. (make-variable-buffer-local 'org-display-custom-times)
  2728. (defcustom org-time-stamp-custom-formats
  2729. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2730. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2731. These are overlaid over the default ISO format if the variable
  2732. `org-display-custom-times' is set. Time like %H:%M should be at the
  2733. end of the second format. The custom formats are also honored by export
  2734. commands, if custom time display is turned on at the time of export."
  2735. :group 'org-time
  2736. :type 'sexp)
  2737. (defun org-time-stamp-format (&optional long inactive)
  2738. "Get the right format for a time string."
  2739. (let ((f (if long (cdr org-time-stamp-formats)
  2740. (car org-time-stamp-formats))))
  2741. (if inactive
  2742. (concat "[" (substring f 1 -1) "]")
  2743. f)))
  2744. (defcustom org-deadline-warning-days 14
  2745. "Number of days before expiration during which a deadline becomes active.
  2746. This variable governs the display in sparse trees and in the agenda.
  2747. When 0 or negative, it means use this number (the absolute value of it)
  2748. even if a deadline has a different individual lead time specified.
  2749. Custom commands can set this variable in the options section."
  2750. :group 'org-time
  2751. :group 'org-agenda-daily/weekly
  2752. :type 'integer)
  2753. (defcustom org-scheduled-delay-days 0
  2754. "Number of days before a scheduled item becomes active.
  2755. This variable governs the display in sparse trees and in the agenda.
  2756. The default value (i.e. 0) means: don't delay scheduled item.
  2757. When negative, it means use this number (the absolute value of it)
  2758. even if a scheduled item has a different individual delay time
  2759. specified.
  2760. Custom commands can set this variable in the options section."
  2761. :group 'org-time
  2762. :group 'org-agenda-daily/weekly
  2763. :version "24.4"
  2764. :package-version '(Org . "8.0")
  2765. :type 'integer)
  2766. (defcustom org-read-date-prefer-future t
  2767. "Non-nil means assume future for incomplete date input from user.
  2768. This affects the following situations:
  2769. 1. The user gives a month but not a year.
  2770. For example, if it is April and you enter \"feb 2\", this will be read
  2771. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2772. 2. The user gives a day, but no month.
  2773. For example, if today is the 15th, and you enter \"3\", Org will read
  2774. this as the third of *next* month. However, if you enter \"17\",
  2775. it will be considered as *this* month.
  2776. If you set this variable to the symbol `time', then also the following
  2777. will work:
  2778. 3. If the user gives a time.
  2779. If the time is before now, it will be interpreted as tomorrow.
  2780. Currently none of this works for ISO week specifications.
  2781. When this option is nil, the current day, month and year will always be
  2782. used as defaults.
  2783. See also `org-agenda-jump-prefer-future'."
  2784. :group 'org-time
  2785. :type '(choice
  2786. (const :tag "Never" nil)
  2787. (const :tag "Check month and day" t)
  2788. (const :tag "Check month, day, and time" time)))
  2789. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2790. "Should the agenda jump command prefer the future for incomplete dates?
  2791. The default is to do the same as configured in `org-read-date-prefer-future'.
  2792. But you can also set a deviating value here.
  2793. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2794. :group 'org-agenda
  2795. :group 'org-time
  2796. :version "24.1"
  2797. :type '(choice
  2798. (const :tag "Use org-read-date-prefer-future"
  2799. org-read-date-prefer-future)
  2800. (const :tag "Never" nil)
  2801. (const :tag "Always" t)))
  2802. (defcustom org-read-date-force-compatible-dates t
  2803. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2804. Depending on the system Emacs is running on, certain dates cannot
  2805. be represented with the type used internally to represent time.
  2806. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2807. correctly. Some systems allow for earlier dates, some for later,
  2808. some for both. One way to find out it to insert any date into an
  2809. Org buffer, putting the cursor on the year and hitting S-up and
  2810. S-down to test the range.
  2811. When this variable is set to t, the date/time prompt will not let
  2812. you specify dates outside the 1970-2037 range, so it is certain that
  2813. these dates will work in whatever version of Emacs you are
  2814. running, and also that you can move a file from one Emacs implementation
  2815. to another. WHenever Org is forcing the year for you, it will display
  2816. a message and beep.
  2817. When this variable is nil, Org will check if the date is
  2818. representable in the specific Emacs implementation you are using.
  2819. If not, it will force a year, usually the current year, and beep
  2820. to remind you. Currently this setting is not recommended because
  2821. the likelihood that you will open your Org files in an Emacs that
  2822. has limited date range is not negligible.
  2823. A workaround for this problem is to use diary sexp dates for time
  2824. stamps outside of this range."
  2825. :group 'org-time
  2826. :version "24.1"
  2827. :type 'boolean)
  2828. (defcustom org-read-date-display-live t
  2829. "Non-nil means display current interpretation of date prompt live.
  2830. This display will be in an overlay, in the minibuffer."
  2831. :group 'org-time
  2832. :type 'boolean)
  2833. (defcustom org-read-date-popup-calendar t
  2834. "Non-nil means pop up a calendar when prompting for a date.
  2835. In the calendar, the date can be selected with mouse-1. However, the
  2836. minibuffer will also be active, and you can simply enter the date as well.
  2837. When nil, only the minibuffer will be available."
  2838. :group 'org-time
  2839. :type 'boolean)
  2840. (defvaralias 'org-popup-calendar-for-date-prompt
  2841. 'org-read-date-popup-calendar)
  2842. (defcustom org-extend-today-until 0
  2843. "The hour when your day really ends. Must be an integer.
  2844. This has influence for the following applications:
  2845. - When switching the agenda to \"today\". It it is still earlier than
  2846. the time given here, the day recognized as TODAY is actually yesterday.
  2847. - When a date is read from the user and it is still before the time given
  2848. here, the current date and time will be assumed to be yesterday, 23:59.
  2849. Also, timestamps inserted in capture templates follow this rule.
  2850. IMPORTANT: This is a feature whose implementation is and likely will
  2851. remain incomplete. Really, it is only here because past midnight seems to
  2852. be the favorite working time of John Wiegley :-)"
  2853. :group 'org-time
  2854. :type 'integer)
  2855. (defcustom org-use-effective-time nil
  2856. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2857. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2858. \"effective time\" of any timestamps between midnight and 8am will be
  2859. 23:59 of the previous day."
  2860. :group 'org-time
  2861. :version "24.1"
  2862. :type 'boolean)
  2863. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2864. "When non-nil, use the last clock out time for `org-todo'.
  2865. Note that this option has precedence over the combined use of
  2866. `org-use-effective-time' and `org-extend-today-until'."
  2867. :group 'org-time
  2868. :version "24.4"
  2869. :package-version '(Org . "8.0")
  2870. :type 'boolean)
  2871. (defcustom org-edit-timestamp-down-means-later nil
  2872. "Non-nil means S-down will increase the time in a time stamp.
  2873. When nil, S-up will increase."
  2874. :group 'org-time
  2875. :type 'boolean)
  2876. (defcustom org-calendar-follow-timestamp-change t
  2877. "Non-nil means make the calendar window follow timestamp changes.
  2878. When a timestamp is modified and the calendar window is visible, it will be
  2879. moved to the new date."
  2880. :group 'org-time
  2881. :type 'boolean)
  2882. (defgroup org-tags nil
  2883. "Options concerning tags in Org mode."
  2884. :tag "Org Tags"
  2885. :group 'org)
  2886. (defcustom org-tag-alist nil
  2887. "Default tags available in Org files.
  2888. The value of this variable is an alist. Associations either:
  2889. (TAG)
  2890. (TAG . SELECT)
  2891. (SPECIAL)
  2892. where TAG is a tag as a string, SELECT is character, used to
  2893. select that tag through the fast tag selection interface, and
  2894. SPECIAL is one of the following keywords: `:startgroup',
  2895. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2896. `:newline'. These keywords are used to define a hierarchy of
  2897. tags. See manual for details.
  2898. When this variable is nil, Org mode bases tag input on what is
  2899. already in the buffer. The value can be overridden locally by
  2900. using a TAGS keyword, e.g.,
  2901. #+TAGS: tag1 tag2
  2902. See also `org-tag-persistent-alist' to sidestep this behavior."
  2903. :group 'org-tags
  2904. :type '(repeat
  2905. (choice
  2906. (cons :tag "Tag with key"
  2907. (string :tag "Tag name")
  2908. (character :tag "Access char"))
  2909. (list :tag "Tag" (string :tag "Tag name"))
  2910. (const :tag "Start radio group" (:startgroup))
  2911. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2912. (const :tag "Group tags delimiter" (:grouptags))
  2913. (const :tag "End radio group" (:endgroup))
  2914. (const :tag "End tag group, non distinct" (:endgrouptag))
  2915. (const :tag "New line" (:newline)))))
  2916. (defcustom org-tag-persistent-alist nil
  2917. "Tags always available in Org files.
  2918. The value of this variable is an alist. Associations either:
  2919. (TAG)
  2920. (TAG . SELECT)
  2921. (SPECIAL)
  2922. where TAG is a tag as a string, SELECT is a character, used to
  2923. select that tag through the fast tag selection interface, and
  2924. SPECIAL is one of the following keywords: `:startgroup',
  2925. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2926. `:newline'. These keywords are used to define a hierarchy of
  2927. tags. See manual for details.
  2928. Unlike to `org-tag-alist', tags defined in this variable do not
  2929. depend on a local TAGS keyword. Instead, to disable these tags
  2930. on a per-file basis, insert anywhere in the file:
  2931. #+STARTUP: noptag"
  2932. :group 'org-tags
  2933. :type '(repeat
  2934. (choice
  2935. (cons :tag "Tag with key"
  2936. (string :tag "Tag name")
  2937. (character :tag "Access char"))
  2938. (list :tag "Tag" (string :tag "Tag name"))
  2939. (const :tag "Start radio group" (:startgroup))
  2940. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2941. (const :tag "Group tags delimiter" (:grouptags))
  2942. (const :tag "End radio group" (:endgroup))
  2943. (const :tag "End tag group, non distinct" (:endgrouptag))
  2944. (const :tag "New line" (:newline)))))
  2945. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2946. "If non-nil, always offer completion for all tags of all agenda files.
  2947. Instead of customizing this variable directly, you might want to
  2948. set it locally for capture buffers, because there no list of
  2949. tags in that file can be created dynamically (there are none).
  2950. (add-hook \\='org-capture-mode-hook
  2951. (lambda ()
  2952. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2953. :group 'org-tags
  2954. :version "24.1"
  2955. :type 'boolean)
  2956. (defvar org-file-tags nil
  2957. "List of tags that can be inherited by all entries in the file.
  2958. The tags will be inherited if the variable `org-use-tag-inheritance'
  2959. says they should be.
  2960. This variable is populated from #+FILETAGS lines.")
  2961. (defcustom org-use-fast-tag-selection 'auto
  2962. "Non-nil means use fast tag selection scheme.
  2963. This is a special interface to select and deselect tags with single keys.
  2964. When nil, fast selection is never used.
  2965. When the symbol `auto', fast selection is used if and only if selection
  2966. characters for tags have been configured, either through the variable
  2967. `org-tag-alist' or through a #+TAGS line in the buffer.
  2968. When t, fast selection is always used and selection keys are assigned
  2969. automatically if necessary."
  2970. :group 'org-tags
  2971. :type '(choice
  2972. (const :tag "Always" t)
  2973. (const :tag "Never" nil)
  2974. (const :tag "When selection characters are configured" auto)))
  2975. (defcustom org-fast-tag-selection-single-key nil
  2976. "Non-nil means fast tag selection exits after first change.
  2977. When nil, you have to press RET to exit it.
  2978. During fast tag selection, you can toggle this flag with `C-c'.
  2979. This variable can also have the value `expert'. In this case, the window
  2980. displaying the tags menu is not even shown, until you press C-c again."
  2981. :group 'org-tags
  2982. :type '(choice
  2983. (const :tag "No" nil)
  2984. (const :tag "Yes" t)
  2985. (const :tag "Expert" expert)))
  2986. (defvar org-fast-tag-selection-include-todo nil
  2987. "Non-nil means fast tags selection interface will also offer TODO states.
  2988. This is an undocumented feature, you should not rely on it.")
  2989. (defcustom org-tags-column -77
  2990. "The column to which tags should be indented in a headline.
  2991. If this number is positive, it specifies the column. If it is negative,
  2992. it means that the tags should be flushright to that column. For example,
  2993. -80 works well for a normal 80 character screen.
  2994. When 0, place tags directly after headline text, with only one space in
  2995. between."
  2996. :group 'org-tags
  2997. :type 'integer)
  2998. (defcustom org-auto-align-tags t
  2999. "Non-nil keeps tags aligned when modifying headlines.
  3000. Some operations (i.e. demoting) change the length of a headline and
  3001. therefore shift the tags around. With this option turned on, after
  3002. each such operation the tags are again aligned to `org-tags-column'."
  3003. :group 'org-tags
  3004. :type 'boolean)
  3005. (defcustom org-use-tag-inheritance t
  3006. "Non-nil means tags in levels apply also for sublevels.
  3007. When nil, only the tags directly given in a specific line apply there.
  3008. This may also be a list of tags that should be inherited, or a regexp that
  3009. matches tags that should be inherited. Additional control is possible
  3010. with the variable `org-tags-exclude-from-inheritance' which gives an
  3011. explicit list of tags to be excluded from inheritance, even if the value of
  3012. `org-use-tag-inheritance' would select it for inheritance.
  3013. If this option is t, a match early-on in a tree can lead to a large
  3014. number of matches in the subtree when constructing the agenda or creating
  3015. a sparse tree. If you only want to see the first match in a tree during
  3016. a search, check out the variable `org-tags-match-list-sublevels'."
  3017. :group 'org-tags
  3018. :type '(choice
  3019. (const :tag "Not" nil)
  3020. (const :tag "Always" t)
  3021. (repeat :tag "Specific tags" (string :tag "Tag"))
  3022. (regexp :tag "Tags matched by regexp")))
  3023. (defcustom org-tags-exclude-from-inheritance nil
  3024. "List of tags that should never be inherited.
  3025. This is a way to exclude a few tags from inheritance. For way to do
  3026. the opposite, to actively allow inheritance for selected tags,
  3027. see the variable `org-use-tag-inheritance'."
  3028. :group 'org-tags
  3029. :type '(repeat (string :tag "Tag")))
  3030. (defun org-tag-inherit-p (tag)
  3031. "Check if TAG is one that should be inherited."
  3032. (cond
  3033. ((member tag org-tags-exclude-from-inheritance) nil)
  3034. ((eq org-use-tag-inheritance t) t)
  3035. ((not org-use-tag-inheritance) nil)
  3036. ((stringp org-use-tag-inheritance)
  3037. (string-match org-use-tag-inheritance tag))
  3038. ((listp org-use-tag-inheritance)
  3039. (member tag org-use-tag-inheritance))
  3040. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3041. (defcustom org-tags-match-list-sublevels t
  3042. "Non-nil means list also sublevels of headlines matching a search.
  3043. This variable applies to tags/property searches, and also to stuck
  3044. projects because this search is based on a tags match as well.
  3045. When set to the symbol `indented', sublevels are indented with
  3046. leading dots.
  3047. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3048. the sublevels of a headline matching a tag search often also match
  3049. the same search. Listing all of them can create very long lists.
  3050. Setting this variable to nil causes subtrees of a match to be skipped.
  3051. This variable is semi-obsolete and probably should always be true. It
  3052. is better to limit inheritance to certain tags using the variables
  3053. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3054. :group 'org-tags
  3055. :type '(choice
  3056. (const :tag "No, don't list them" nil)
  3057. (const :tag "Yes, do list them" t)
  3058. (const :tag "List them, indented with leading dots" indented)))
  3059. (defcustom org-tags-sort-function nil
  3060. "When set, tags are sorted using this function as a comparator."
  3061. :group 'org-tags
  3062. :type '(choice
  3063. (const :tag "No sorting" nil)
  3064. (const :tag "Alphabetical" org-string-collate-lessp)
  3065. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3066. (function :tag "Custom function" nil)))
  3067. (defvar org-tags-history nil
  3068. "History of minibuffer reads for tags.")
  3069. (defvar org-last-tags-completion-table nil
  3070. "The last used completion table for tags.")
  3071. (defvar org-after-tags-change-hook nil
  3072. "Hook that is run after the tags in a line have changed.")
  3073. (defgroup org-properties nil
  3074. "Options concerning properties in Org mode."
  3075. :tag "Org Properties"
  3076. :group 'org)
  3077. (defcustom org-property-format "%-10s %s"
  3078. "How property key/value pairs should be formatted by `indent-line'.
  3079. When `indent-line' hits a property definition, it will format the line
  3080. according to this format, mainly to make sure that the values are
  3081. lined-up with respect to each other."
  3082. :group 'org-properties
  3083. :type 'string)
  3084. (defcustom org-properties-postprocess-alist nil
  3085. "Alist of properties and functions to adjust inserted values.
  3086. Elements of this alist must be of the form
  3087. ([string] [function])
  3088. where [string] must be a property name and [function] must be a
  3089. lambda expression: this lambda expression must take one argument,
  3090. the value to adjust, and return the new value as a string.
  3091. For example, this element will allow the property \"Remaining\"
  3092. to be updated wrt the relation between the \"Effort\" property
  3093. and the clock summary:
  3094. ((\"Remaining\" (lambda(value)
  3095. (let ((clocksum (org-clock-sum-current-item))
  3096. (effort (org-duration-to-minutes
  3097. (org-entry-get (point) \"Effort\"))))
  3098. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3099. :group 'org-properties
  3100. :version "24.1"
  3101. :type '(alist :key-type (string :tag "Property")
  3102. :value-type (function :tag "Function")))
  3103. (defcustom org-use-property-inheritance nil
  3104. "Non-nil means properties apply also for sublevels.
  3105. This setting is chiefly used during property searches. Turning it on can
  3106. cause significant overhead when doing a search, which is why it is not
  3107. on by default.
  3108. When nil, only the properties directly given in the current entry count.
  3109. When t, every property is inherited. The value may also be a list of
  3110. properties that should have inheritance, or a regular expression matching
  3111. properties that should be inherited.
  3112. However, note that some special properties use inheritance under special
  3113. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3114. and the properties ending in \"_ALL\" when they are used as descriptor
  3115. for valid values of a property.
  3116. Note for programmers:
  3117. When querying an entry with `org-entry-get', you can control if inheritance
  3118. should be used. By default, `org-entry-get' looks only at the local
  3119. properties. You can request inheritance by setting the inherit argument
  3120. to t (to force inheritance) or to `selective' (to respect the setting
  3121. in this variable)."
  3122. :group 'org-properties
  3123. :type '(choice
  3124. (const :tag "Not" nil)
  3125. (const :tag "Always" t)
  3126. (repeat :tag "Specific properties" (string :tag "Property"))
  3127. (regexp :tag "Properties matched by regexp")))
  3128. (defun org-property-inherit-p (property)
  3129. "Return a non-nil value if PROPERTY should be inherited."
  3130. (cond
  3131. ((eq org-use-property-inheritance t) t)
  3132. ((not org-use-property-inheritance) nil)
  3133. ((stringp org-use-property-inheritance)
  3134. (string-match org-use-property-inheritance property))
  3135. ((listp org-use-property-inheritance)
  3136. (member-ignore-case property org-use-property-inheritance))
  3137. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3138. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3139. "The default column format, if no other format has been defined.
  3140. This variable can be set on the per-file basis by inserting a line
  3141. #+COLUMNS: %25ITEM ....."
  3142. :group 'org-properties
  3143. :type 'string)
  3144. (defcustom org-columns-ellipses ".."
  3145. "The ellipses to be used when a field in column view is truncated.
  3146. When this is the empty string, as many characters as possible are shown,
  3147. but then there will be no visual indication that the field has been truncated.
  3148. When this is a string of length N, the last N characters of a truncated
  3149. field are replaced by this string. If the column is narrower than the
  3150. ellipses string, only part of the ellipses string will be shown."
  3151. :group 'org-properties
  3152. :type 'string)
  3153. (defconst org-global-properties-fixed
  3154. '(("VISIBILITY_ALL" . "folded children content all")
  3155. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3156. "List of property/value pairs that can be inherited by any entry.
  3157. These are fixed values, for the preset properties. The user variable
  3158. that can be used to add to this list is `org-global-properties'.
  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. If the value represents
  3161. multiple items like an \"_ALL\" property, separate the items by
  3162. spaces.")
  3163. (defcustom org-global-properties nil
  3164. "List of property/value pairs that can be inherited by any entry.
  3165. This list will be combined with the constant `org-global-properties-fixed'.
  3166. The entries in this list are cons cells where the car is a property
  3167. name and cdr is a string with the value.
  3168. You can set buffer-local values for the same purpose in the variable
  3169. `org-file-properties' this by adding lines like
  3170. #+PROPERTY: NAME VALUE"
  3171. :group 'org-properties
  3172. :type '(repeat
  3173. (cons (string :tag "Property")
  3174. (string :tag "Value"))))
  3175. (defvar-local org-file-properties nil
  3176. "List of property/value pairs that can be inherited by any entry.
  3177. Valid for the current buffer.
  3178. This variable is populated from #+PROPERTY lines.")
  3179. (defgroup org-agenda nil
  3180. "Options concerning agenda views in Org mode."
  3181. :tag "Org Agenda"
  3182. :group 'org)
  3183. (defvar-local org-category nil
  3184. "Variable used by Org files to set a category for agenda display.
  3185. Such files should use a file variable to set it, for example
  3186. # -*- mode: org; org-category: \"ELisp\"
  3187. or contain a special line
  3188. #+CATEGORY: ELisp
  3189. If the file does not specify a category, then file's base name
  3190. is used instead.")
  3191. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3192. (defcustom org-agenda-files nil
  3193. "The files to be used for agenda display.
  3194. If an entry is a directory, all files in that directory that are matched
  3195. by `org-agenda-file-regexp' will be part of the file list.
  3196. If the value of the variable is not a list but a single file name, then
  3197. the list of agenda files is actually stored and maintained in that file,
  3198. one agenda file per line. In this file paths can be given relative to
  3199. `org-directory'. Tilde expansion and environment variable substitution
  3200. are also made.
  3201. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3202. and removed with `\\[org-remove-file]'."
  3203. :group 'org-agenda
  3204. :type '(choice
  3205. (repeat :tag "List of files and directories" file)
  3206. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3207. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3208. "Regular expression to match files for `org-agenda-files'.
  3209. If any element in the list in that variable contains a directory instead
  3210. of a normal file, all files in that directory that are matched by this
  3211. regular expression will be included."
  3212. :group 'org-agenda
  3213. :type 'regexp)
  3214. (defcustom org-agenda-text-search-extra-files nil
  3215. "List of extra files to be searched by text search commands.
  3216. These files will be searched in addition to the agenda files by the
  3217. commands `org-search-view' (`\\[org-agenda] s') \
  3218. and `org-occur-in-agenda-files'.
  3219. Note that these files will only be searched for text search commands,
  3220. not for the other agenda views like todo lists, tag searches or the weekly
  3221. agenda. This variable is intended to list notes and possibly archive files
  3222. that should also be searched by these two commands.
  3223. In fact, if the first element in the list is the symbol `agenda-archives',
  3224. then all archive files of all agenda files will be added to the search
  3225. scope."
  3226. :group 'org-agenda
  3227. :type '(set :greedy t
  3228. (const :tag "Agenda Archives" agenda-archives)
  3229. (repeat :inline t (file))))
  3230. (defvaralias 'org-agenda-multi-occur-extra-files
  3231. 'org-agenda-text-search-extra-files)
  3232. (defcustom org-agenda-skip-unavailable-files nil
  3233. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3234. A nil value means to remove them, after a query, from the list."
  3235. :group 'org-agenda
  3236. :type 'boolean)
  3237. (defcustom org-agenda-diary-file 'diary-file
  3238. "File to which to add new entries with the `i' key in agenda and calendar.
  3239. When this is the symbol `diary-file', the functionality in the Emacs
  3240. calendar will be used to add entries to the `diary-file'. But when this
  3241. points to a file, `org-agenda-diary-entry' will be used instead."
  3242. :group 'org-agenda
  3243. :type '(choice
  3244. (const :tag "The standard Emacs diary file" diary-file)
  3245. (file :tag "Special Org file diary entries")))
  3246. (defgroup org-latex nil
  3247. "Options for embedding LaTeX code into Org mode."
  3248. :tag "Org LaTeX"
  3249. :group 'org)
  3250. (defcustom org-format-latex-options
  3251. '(:foreground default :background default :scale 1.0
  3252. :html-foreground "Black" :html-background "Transparent"
  3253. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3254. "Options for creating images from LaTeX fragments.
  3255. This is a property list with the following properties:
  3256. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3257. `default' means use the foreground of the default face.
  3258. `auto' means use the foreground from the text face.
  3259. :background the background color, or \"Transparent\".
  3260. `default' means use the background of the default face.
  3261. `auto' means use the background from the text face.
  3262. :scale a scaling factor for the size of the images, to get more pixels
  3263. :html-foreground, :html-background, :html-scale
  3264. the same numbers for HTML export.
  3265. :matchers a list indicating which matchers should be used to
  3266. find LaTeX fragments. Valid members of this list are:
  3267. \"begin\" find environments
  3268. \"$1\" find single characters surrounded by $.$
  3269. \"$\" find math expressions surrounded by $...$
  3270. \"$$\" find math expressions surrounded by $$....$$
  3271. \"\\(\" find math expressions surrounded by \\(...\\)
  3272. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3273. :group 'org-latex
  3274. :type 'plist)
  3275. (defcustom org-format-latex-signal-error t
  3276. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3277. When nil, just push out a message."
  3278. :group 'org-latex
  3279. :version "24.1"
  3280. :type 'boolean)
  3281. (defcustom org-latex-to-mathml-jar-file nil
  3282. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3283. Use this to specify additional executable file say a jar file.
  3284. When using MathToWeb as the converter, specify the full-path to
  3285. your mathtoweb.jar file."
  3286. :group 'org-latex
  3287. :version "24.1"
  3288. :type '(choice
  3289. (const :tag "None" nil)
  3290. (file :tag "JAR file" :must-match t)))
  3291. (defcustom org-latex-to-mathml-convert-command nil
  3292. "Command to convert LaTeX fragments to MathML.
  3293. Replace format-specifiers in the command as noted below and use
  3294. `shell-command' to convert LaTeX to MathML.
  3295. %j: Executable file in fully expanded form as specified by
  3296. `org-latex-to-mathml-jar-file'.
  3297. %I: Input LaTeX file in fully expanded form.
  3298. %i: The latex fragment to be converted.
  3299. %o: Output MathML file.
  3300. This command is used by `org-create-math-formula'.
  3301. When using MathToWeb as the converter, set this option to
  3302. \"java -jar %j -unicode -force -df %o %I\".
  3303. When using LaTeXML set this option to
  3304. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3305. :group 'org-latex
  3306. :version "24.1"
  3307. :type '(choice
  3308. (const :tag "None" nil)
  3309. (string :tag "\nShell command")))
  3310. (defcustom org-preview-latex-default-process 'dvipng
  3311. "The default process to convert LaTeX fragments to image files.
  3312. All available processes and theirs documents can be found in
  3313. `org-preview-latex-process-alist', which see."
  3314. :group 'org-latex
  3315. :version "26.1"
  3316. :package-version '(Org . "9.0")
  3317. :type 'symbol)
  3318. (defcustom org-preview-latex-process-alist
  3319. '((dvipng
  3320. :programs ("latex" "dvipng")
  3321. :description "dvi > png"
  3322. :message "you need to install the programs: latex and dvipng."
  3323. :image-input-type "dvi"
  3324. :image-output-type "png"
  3325. :image-size-adjust (1.0 . 1.0)
  3326. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3327. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3328. (dvisvgm
  3329. :programs ("latex" "dvisvgm")
  3330. :description "dvi > svg"
  3331. :message "you need to install the programs: latex and dvisvgm."
  3332. :use-xcolor t
  3333. :image-input-type "dvi"
  3334. :image-output-type "svg"
  3335. :image-size-adjust (1.7 . 1.5)
  3336. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3337. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3338. (imagemagick
  3339. :programs ("latex" "convert")
  3340. :description "pdf > png"
  3341. :message "you need to install the programs: latex and imagemagick."
  3342. :use-xcolor t
  3343. :image-input-type "pdf"
  3344. :image-output-type "png"
  3345. :image-size-adjust (1.0 . 1.0)
  3346. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3347. :image-converter
  3348. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3349. "Definitions of external processes for LaTeX previewing.
  3350. Org mode can use some external commands to generate TeX snippet's images for
  3351. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3352. `org-create-formula-image' how to call them.
  3353. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3354. PROPERTIES accepts the following attributes:
  3355. :programs list of strings, required programs.
  3356. :description string, describe the process.
  3357. :message string, message it when required programs cannot be found.
  3358. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3359. :image-output-type string, output file type of image converter (e.g., \"png\").
  3360. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3361. deal with background and foreground color of image.
  3362. Otherwise, dvipng style background and foreground color
  3363. format are generated. You may then refer to them in
  3364. command options with \"%F\" and \"%B\".
  3365. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3366. image size showed in buffer and the cdr element is for
  3367. HTML file. This option is only useful for process
  3368. developers, users should use variable
  3369. `org-format-latex-options' instead.
  3370. :post-clean list of strings, files matched are to be cleaned up once
  3371. the image is generated. When nil, the files with \".dvi\",
  3372. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3373. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3374. be cleaned up.
  3375. :latex-header list of strings, the LaTeX header of the snippet file.
  3376. When nil, the fallback value is used instead, which is
  3377. controlled by `org-format-latex-header',
  3378. `org-latex-default-packages-alist' and
  3379. `org-latex-packages-alist', which see.
  3380. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3381. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3382. replaced with values defined below.
  3383. :image-converter list of image converter commands strings. Each of them is
  3384. given to the shell and supports any of the following
  3385. place-holders defined below.
  3386. Place-holders used by `:image-converter' and `:latex-compiler':
  3387. %f input file name
  3388. %b base name of input file
  3389. %o base directory of input file
  3390. %O absolute output file name
  3391. Place-holders only used by `:image-converter':
  3392. %F foreground of image
  3393. %B background of image
  3394. %D dpi, which is used to adjust image size by some processing commands.
  3395. %S the image size scale ratio, which is used to adjust image size by some
  3396. processing commands."
  3397. :group 'org-latex
  3398. :version "26.1"
  3399. :package-version '(Org . "9.0")
  3400. :type '(alist :tag "LaTeX to image backends"
  3401. :value-type (plist)))
  3402. (defcustom org-preview-latex-image-directory "ltximg/"
  3403. "Path to store latex preview images.
  3404. A relative path here creates many directories relative to the
  3405. processed Org files paths. An absolute path puts all preview
  3406. images at the same place."
  3407. :group 'org-latex
  3408. :version "26.1"
  3409. :package-version '(Org . "9.0")
  3410. :type 'string)
  3411. (defun org-format-latex-mathml-available-p ()
  3412. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3413. (save-match-data
  3414. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3415. org-latex-to-mathml-convert-command)
  3416. (let ((executable (car (split-string
  3417. org-latex-to-mathml-convert-command))))
  3418. (when (executable-find executable)
  3419. (if (string-match
  3420. "%j" org-latex-to-mathml-convert-command)
  3421. (file-readable-p org-latex-to-mathml-jar-file)
  3422. t))))))
  3423. (defcustom org-format-latex-header "\\documentclass{article}
  3424. \\usepackage[usenames]{color}
  3425. \[PACKAGES]
  3426. \[DEFAULT-PACKAGES]
  3427. \\pagestyle{empty} % do not remove
  3428. % The settings below are copied from fullpage.sty
  3429. \\setlength{\\textwidth}{\\paperwidth}
  3430. \\addtolength{\\textwidth}{-3cm}
  3431. \\setlength{\\oddsidemargin}{1.5cm}
  3432. \\addtolength{\\oddsidemargin}{-2.54cm}
  3433. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3434. \\setlength{\\textheight}{\\paperheight}
  3435. \\addtolength{\\textheight}{-\\headheight}
  3436. \\addtolength{\\textheight}{-\\headsep}
  3437. \\addtolength{\\textheight}{-\\footskip}
  3438. \\addtolength{\\textheight}{-3cm}
  3439. \\setlength{\\topmargin}{1.5cm}
  3440. \\addtolength{\\topmargin}{-2.54cm}"
  3441. "The document header used for processing LaTeX fragments.
  3442. It is imperative that this header make sure that no page number
  3443. appears on the page. The package defined in the variables
  3444. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3445. will either replace the placeholder \"[PACKAGES]\" in this
  3446. header, or they will be appended."
  3447. :group 'org-latex
  3448. :type 'string)
  3449. (defun org-set-packages-alist (var val)
  3450. "Set the packages alist and make sure it has 3 elements per entry."
  3451. (set var (mapcar (lambda (x)
  3452. (if (and (consp x) (= (length x) 2))
  3453. (list (car x) (nth 1 x) t)
  3454. x))
  3455. val)))
  3456. (defun org-get-packages-alist (var)
  3457. "Get the packages alist and make sure it has 3 elements per entry."
  3458. (mapcar (lambda (x)
  3459. (if (and (consp x) (= (length x) 2))
  3460. (list (car x) (nth 1 x) t)
  3461. x))
  3462. (default-value var)))
  3463. (defcustom org-latex-default-packages-alist
  3464. '(("AUTO" "inputenc" t ("pdflatex"))
  3465. ("T1" "fontenc" t ("pdflatex"))
  3466. ("" "graphicx" t)
  3467. ("" "grffile" t)
  3468. ("" "longtable" nil)
  3469. ("" "wrapfig" nil)
  3470. ("" "rotating" nil)
  3471. ("normalem" "ulem" t)
  3472. ("" "amsmath" t)
  3473. ("" "textcomp" t)
  3474. ("" "amssymb" t)
  3475. ("" "capt-of" nil)
  3476. ("" "hyperref" nil))
  3477. "Alist of default packages to be inserted in the header.
  3478. Change this only if one of the packages here causes an
  3479. incompatibility with another package you are using.
  3480. The packages in this list are needed by one part or another of
  3481. Org mode to function properly:
  3482. - inputenc, fontenc: for basic font and character selection
  3483. - graphicx: for including images
  3484. - grffile: allow periods and spaces in graphics file names
  3485. - longtable: For multipage tables
  3486. - wrapfig: for figure placement
  3487. - rotating: for sideways figures and tables
  3488. - ulem: for underline and strike-through
  3489. - amsmath: for subscript and superscript and math environments
  3490. - textcomp, amssymb: for various symbols used
  3491. for interpreting the entities in `org-entities'. You can skip
  3492. some of these packages if you don't use any of their symbols.
  3493. - capt-of: for captions outside of floats
  3494. - hyperref: for cross references
  3495. Therefore you should not modify this variable unless you know
  3496. what you are doing. The one reason to change it anyway is that
  3497. you might be loading some other package that conflicts with one
  3498. of the default packages. Each element is either a cell or
  3499. a string.
  3500. A cell is of the format
  3501. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3502. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3503. when compiling LaTeX snippets into images for inclusion into
  3504. non-LaTeX output. COMPILERS is a list of compilers that should
  3505. include the package, see `org-latex-compiler'. If the document
  3506. compiler is not in the list, and the list is non-nil, the package
  3507. will not be inserted in the final document.
  3508. A string will be inserted as-is in the header of the document."
  3509. :group 'org-latex
  3510. :group 'org-export-latex
  3511. :set 'org-set-packages-alist
  3512. :get 'org-get-packages-alist
  3513. :version "26.1"
  3514. :package-version '(Org . "8.3")
  3515. :type '(repeat
  3516. (choice
  3517. (list :tag "options/package pair"
  3518. (string :tag "options")
  3519. (string :tag "package")
  3520. (boolean :tag "Snippet")
  3521. (choice
  3522. (const :tag "For all compilers" nil)
  3523. (repeat :tag "Allowed compiler" string)))
  3524. (string :tag "A line of LaTeX"))))
  3525. (defcustom org-latex-packages-alist nil
  3526. "Alist of packages to be inserted in every LaTeX header.
  3527. These will be inserted after `org-latex-default-packages-alist'.
  3528. Each element is either a cell or a string.
  3529. A cell is of the format:
  3530. (\"options\" \"package\" SNIPPET-FLAG)
  3531. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3532. needed when turning LaTeX snippets into images for inclusion into
  3533. non-LaTeX output.
  3534. A string will be inserted as-is in the header of the document.
  3535. Make sure that you only list packages here which:
  3536. - you want in every file;
  3537. - do not conflict with the setup in `org-format-latex-header';
  3538. - do not conflict with the default packages in
  3539. `org-latex-default-packages-alist'."
  3540. :group 'org-latex
  3541. :group 'org-export-latex
  3542. :set 'org-set-packages-alist
  3543. :get 'org-get-packages-alist
  3544. :type '(repeat
  3545. (choice
  3546. (list :tag "options/package pair"
  3547. (string :tag "options")
  3548. (string :tag "package")
  3549. (boolean :tag "Snippet"))
  3550. (string :tag "A line of LaTeX"))))
  3551. (defgroup org-appearance nil
  3552. "Settings for Org mode appearance."
  3553. :tag "Org Appearance"
  3554. :group 'org)
  3555. (defcustom org-level-color-stars-only nil
  3556. "Non-nil means fontify only the stars in each headline.
  3557. When nil, the entire headline is fontified.
  3558. Changing it requires restart of `font-lock-mode' to become effective
  3559. also in regions already fontified."
  3560. :group 'org-appearance
  3561. :type 'boolean)
  3562. (defcustom org-hide-leading-stars nil
  3563. "Non-nil means hide the first N-1 stars in a headline.
  3564. This works by using the face `org-hide' for these stars. This
  3565. face is white for a light background, and black for a dark
  3566. background. You may have to customize the face `org-hide' to
  3567. make this work.
  3568. Changing it requires restart of `font-lock-mode' to become effective
  3569. also in regions already fontified.
  3570. You may also set this on a per-file basis by adding one of the following
  3571. lines to the buffer:
  3572. #+STARTUP: hidestars
  3573. #+STARTUP: showstars"
  3574. :group 'org-appearance
  3575. :type 'boolean)
  3576. (defcustom org-hidden-keywords nil
  3577. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3578. For example, a value \\='(title) for this list makes the document's title
  3579. appear in the buffer without the initial \"#+TITLE:\" part."
  3580. :group 'org-appearance
  3581. :version "24.1"
  3582. :type '(set (const :tag "#+AUTHOR" author)
  3583. (const :tag "#+DATE" date)
  3584. (const :tag "#+EMAIL" email)
  3585. (const :tag "#+TITLE" title)))
  3586. (defcustom org-custom-properties nil
  3587. "List of properties (as strings) with a special meaning.
  3588. The default use of these custom properties is to let the user
  3589. hide them with `org-toggle-custom-properties-visibility'."
  3590. :group 'org-properties
  3591. :group 'org-appearance
  3592. :version "24.3"
  3593. :type '(repeat (string :tag "Property Name")))
  3594. (defcustom org-fontify-done-headline nil
  3595. "Non-nil means change the face of a headline if it is marked DONE.
  3596. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3597. When this is non-nil, the headline after the keyword is set to the
  3598. `org-headline-done' as an additional indication."
  3599. :group 'org-appearance
  3600. :type 'boolean)
  3601. (defcustom org-fontify-emphasized-text t
  3602. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3603. Changing this variable requires a restart of Emacs to take effect."
  3604. :group 'org-appearance
  3605. :type 'boolean)
  3606. (defcustom org-fontify-whole-heading-line nil
  3607. "Non-nil means fontify the whole line for headings.
  3608. This is useful when setting a background color for the
  3609. org-level-* faces."
  3610. :group 'org-appearance
  3611. :type 'boolean)
  3612. (defcustom org-highlight-latex-and-related nil
  3613. "Non-nil means highlight LaTeX related syntax in the buffer.
  3614. When non nil, the value should be a list containing any of the
  3615. following symbols:
  3616. `latex' Highlight LaTeX snippets and environments.
  3617. `script' Highlight subscript and superscript.
  3618. `entities' Highlight entities."
  3619. :group 'org-appearance
  3620. :version "24.4"
  3621. :package-version '(Org . "8.0")
  3622. :type '(choice
  3623. (const :tag "No highlighting" nil)
  3624. (set :greedy t :tag "Highlight"
  3625. (const :tag "LaTeX snippets and environments" latex)
  3626. (const :tag "Subscript and superscript" script)
  3627. (const :tag "Entities" entities))))
  3628. (defcustom org-hide-emphasis-markers nil
  3629. "Non-nil mean font-lock should hide the emphasis marker characters."
  3630. :group 'org-appearance
  3631. :type 'boolean)
  3632. (defcustom org-hide-macro-markers nil
  3633. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3634. :group 'org-appearance
  3635. :type 'boolean)
  3636. (defcustom org-pretty-entities nil
  3637. "Non-nil means show entities as UTF8 characters.
  3638. When nil, the \\name form remains in the buffer."
  3639. :group 'org-appearance
  3640. :version "24.1"
  3641. :type 'boolean)
  3642. (defcustom org-pretty-entities-include-sub-superscripts t
  3643. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3644. :group 'org-appearance
  3645. :version "24.1"
  3646. :type 'boolean)
  3647. (defvar org-emph-re nil
  3648. "Regular expression for matching emphasis.
  3649. After a match, the match groups contain these elements:
  3650. 0 The match of the full regular expression, including the characters
  3651. before and after the proper match
  3652. 1 The character before the proper match, or empty at beginning of line
  3653. 2 The proper match, including the leading and trailing markers
  3654. 3 The leading marker like * or /, indicating the type of highlighting
  3655. 4 The text between the emphasis markers, not including the markers
  3656. 5 The character after the match, empty at the end of a line")
  3657. (defvar org-verbatim-re nil
  3658. "Regular expression for matching verbatim text.")
  3659. (defvar org-emphasis-regexp-components) ; defined just below
  3660. (defvar org-emphasis-alist) ; defined just below
  3661. (defun org-set-emph-re (var val)
  3662. "Set variable and compute the emphasis regular expression."
  3663. (set var val)
  3664. (when (and (boundp 'org-emphasis-alist)
  3665. (boundp 'org-emphasis-regexp-components)
  3666. org-emphasis-alist org-emphasis-regexp-components)
  3667. (pcase-let*
  3668. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3669. (body (if (<= nl 0) body
  3670. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3671. (template
  3672. (format (concat "\\([%s]\\|^\\)" ;before markers
  3673. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3674. "\\([%s]\\|$\\)") ;after markers
  3675. pre border border body border post)))
  3676. (setq org-emph-re (format template "*/_+"))
  3677. (setq org-verbatim-re (format template "=~")))))
  3678. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3679. ;; set this option proved cumbersome. See this message/thread:
  3680. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3681. (defvar org-emphasis-regexp-components
  3682. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3683. "Components used to build the regular expression for emphasis.
  3684. This is a list with five entries. Terminology: In an emphasis string
  3685. like \" *strong word* \", we call the initial space PREMATCH, the final
  3686. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3687. and \"trong wor\" is the body. The different components in this variable
  3688. specify what is allowed/forbidden in each part:
  3689. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3690. post Chars allowed as postmatch. End of line will be allowed too.
  3691. border The chars *forbidden* as border characters.
  3692. body-regexp A regexp like \".\" to match a body character. Don't use
  3693. non-shy groups here, and don't allow newline here.
  3694. newline The maximum number of newlines allowed in an emphasis exp.
  3695. You need to reload Org or to restart Emacs after setting this.")
  3696. (defcustom org-emphasis-alist
  3697. '(("*" bold)
  3698. ("/" italic)
  3699. ("_" underline)
  3700. ("=" org-verbatim verbatim)
  3701. ("~" org-code verbatim)
  3702. ("+" (:strike-through t)))
  3703. "Alist of characters and faces to emphasize text.
  3704. Text starting and ending with a special character will be emphasized,
  3705. for example *bold*, _underlined_ and /italic/. This variable sets the
  3706. marker characters and the face to be used by font-lock for highlighting
  3707. in Org buffers.
  3708. You need to reload Org or to restart Emacs after customizing this."
  3709. :group 'org-appearance
  3710. :set 'org-set-emph-re
  3711. :version "24.4"
  3712. :package-version '(Org . "8.0")
  3713. :type '(repeat
  3714. (list
  3715. (string :tag "Marker character")
  3716. (choice
  3717. (face :tag "Font-lock-face")
  3718. (plist :tag "Face property list"))
  3719. (option (const verbatim)))))
  3720. (defvar org-protecting-blocks '("src" "example" "export")
  3721. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3722. This is needed for font-lock setup.")
  3723. ;;; Functions and variables from their packages
  3724. ;; Declared here to avoid compiler warnings
  3725. (defvar mark-active)
  3726. ;; Various packages
  3727. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3728. (declare-function calendar-forward-day "cal-move" (arg))
  3729. (declare-function calendar-goto-date "cal-move" (date))
  3730. (declare-function calendar-goto-today "cal-move" ())
  3731. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3732. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3733. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3734. (declare-function cdlatex-tab "ext:cdlatex" ())
  3735. (declare-function dired-get-filename
  3736. "dired"
  3737. (&optional localp no-error-if-not-filep))
  3738. (declare-function iswitchb-read-buffer
  3739. "iswitchb"
  3740. (prompt &optional
  3741. default require-match _predicate start matches-set))
  3742. (declare-function org-agenda-change-all-lines
  3743. "org-agenda"
  3744. (newhead hdmarker &optional fixface just-this))
  3745. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3746. "org-agenda"
  3747. (&optional end))
  3748. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3749. (declare-function org-agenda-format-item
  3750. "org-agenda"
  3751. (extra txt &optional level category tags dotime
  3752. remove-re habitp))
  3753. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3754. (declare-function org-agenda-save-markers-for-cut-and-paste
  3755. "org-agenda"
  3756. (beg end))
  3757. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3758. (declare-function org-agenda-skip "org-agenda" ())
  3759. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3760. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3761. (declare-function org-indent-mode "org-indent" (&optional arg))
  3762. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3763. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3764. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3765. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3766. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3767. (declare-function parse-time-string "parse-time" (string))
  3768. (defvar align-mode-rules-list)
  3769. (defvar calc-embedded-close-formula)
  3770. (defvar calc-embedded-open-formula)
  3771. (defvar calc-embedded-open-mode)
  3772. (defvar font-lock-unfontify-region-function)
  3773. (defvar iswitchb-temp-buflist)
  3774. (defvar org-agenda-tags-todo-honor-ignore-options)
  3775. (defvar remember-data-file)
  3776. (defvar texmathp-why)
  3777. ;;;###autoload
  3778. (defun turn-on-orgtbl ()
  3779. "Unconditionally turn on `orgtbl-mode'."
  3780. (require 'org-table)
  3781. (orgtbl-mode 1))
  3782. (defun org-at-table-p (&optional table-type)
  3783. "Non-nil if the cursor is inside an Org table.
  3784. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3785. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3786. (or (not (derived-mode-p 'org-mode))
  3787. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3788. (and e (or table-type
  3789. (eq 'org (org-element-property :type e))))))))
  3790. (defun org-at-table.el-p ()
  3791. "Non-nil when point is at a table.el table."
  3792. (and (org-match-line "[ \t]*[|+]")
  3793. (let ((element (org-element-at-point)))
  3794. (and (eq (org-element-type element) 'table)
  3795. (eq (org-element-property :type element) 'table.el)))))
  3796. (defun org-at-table-hline-p ()
  3797. "Non-nil when point is inside a hline in a table.
  3798. Assume point is already in a table."
  3799. (org-match-line org-table-hline-regexp))
  3800. (defun org-table-map-tables (function &optional quietly)
  3801. "Apply FUNCTION to the start of all tables in the buffer."
  3802. (org-with-wide-buffer
  3803. (goto-char (point-min))
  3804. (while (re-search-forward org-table-any-line-regexp nil t)
  3805. (unless quietly
  3806. (message "Mapping tables: %d%%"
  3807. (floor (* 100.0 (point)) (buffer-size))))
  3808. (beginning-of-line 1)
  3809. (when (and (looking-at org-table-line-regexp)
  3810. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3811. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3812. (save-excursion (funcall function))
  3813. (or (looking-at org-table-line-regexp)
  3814. (forward-char 1)))
  3815. (re-search-forward org-table-any-border-regexp nil 1)))
  3816. (unless quietly (message "Mapping tables: done")))
  3817. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3818. (declare-function org-clock-update-mode-line "org-clock" ())
  3819. (declare-function org-resolve-clocks "org-clock"
  3820. (&optional also-non-dangling-p prompt last-valid))
  3821. (defun org-at-TBLFM-p (&optional pos)
  3822. "Non-nil when point (or POS) is in #+TBLFM line."
  3823. (save-excursion
  3824. (goto-char (or pos (point)))
  3825. (beginning-of-line)
  3826. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3827. (eq (org-element-type (org-element-at-point)) 'table))))
  3828. (defvar org-clock-start-time)
  3829. (defvar org-clock-marker (make-marker)
  3830. "Marker recording the last clock-in.")
  3831. (defvar org-clock-hd-marker (make-marker)
  3832. "Marker recording the last clock-in, but the headline position.")
  3833. (defvar org-clock-heading ""
  3834. "The heading of the current clock entry.")
  3835. (defun org-clock-is-active ()
  3836. "Return the buffer where the clock is currently running.
  3837. Return nil if no clock is running."
  3838. (marker-buffer org-clock-marker))
  3839. (defun org-check-running-clock ()
  3840. "Check if the current buffer contains the running clock.
  3841. If yes, offer to stop it and to save the buffer with the changes."
  3842. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3843. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3844. (buffer-name))))
  3845. (org-clock-out)
  3846. (when (y-or-n-p "Save changed buffer?")
  3847. (save-buffer))))
  3848. (defun org-clocktable-try-shift (dir n)
  3849. "Check if this line starts a clock table, if yes, shift the time block."
  3850. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3851. (org-clocktable-shift dir n)))
  3852. ;;;###autoload
  3853. (defun org-clock-persistence-insinuate ()
  3854. "Set up hooks for clock persistence."
  3855. (require 'org-clock)
  3856. (add-hook 'org-mode-hook 'org-clock-load)
  3857. (add-hook 'kill-emacs-hook 'org-clock-save))
  3858. (defgroup org-archive nil
  3859. "Options concerning archiving in Org mode."
  3860. :tag "Org Archive"
  3861. :group 'org-structure)
  3862. (defcustom org-archive-location "%s_archive::"
  3863. "The location where subtrees should be archived.
  3864. The value of this variable is a string, consisting of two parts,
  3865. separated by a double-colon. The first part is a filename and
  3866. the second part is a headline.
  3867. When the filename is omitted, archiving happens in the same file.
  3868. %s in the filename will be replaced by the current file
  3869. name (without the directory part). Archiving to a different file
  3870. is useful to keep archived entries from contributing to the
  3871. Org Agenda.
  3872. The archived entries will be filed as subtrees of the specified
  3873. headline. When the headline is omitted, the subtrees are simply
  3874. filed away at the end of the file, as top-level entries. Also in
  3875. the heading you can use %s to represent the file name, this can be
  3876. useful when using the same archive for a number of different files.
  3877. Here are a few examples:
  3878. \"%s_archive::\"
  3879. If the current file is Projects.org, archive in file
  3880. Projects.org_archive, as top-level trees. This is the default.
  3881. \"::* Archived Tasks\"
  3882. Archive in the current file, under the top-level headline
  3883. \"* Archived Tasks\".
  3884. \"~/org/archive.org::\"
  3885. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3886. \"~/org/archive.org::* From %s\"
  3887. Archive in file ~/org/archive.org (absolute path), under headlines
  3888. \"From FILENAME\" where file name is the current file name.
  3889. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3890. The \"datetree/\" string is special, signifying to archive
  3891. items to the datetree. Items are placed in either the CLOSED
  3892. date of the item, or the current date if there is no CLOSED date.
  3893. The heading will be a subentry to the current date. There doesn't
  3894. need to be a heading, but there always needs to be a slash after
  3895. datetree. For example, to store archived items directly in the
  3896. datetree, use \"~/org/datetree.org::datetree/\".
  3897. \"basement::** Finished Tasks\"
  3898. Archive in file ./basement (relative path), as level 3 trees
  3899. below the level 2 heading \"** Finished Tasks\".
  3900. You may set this option on a per-file basis by adding to the buffer a
  3901. line like
  3902. #+ARCHIVE: basement::** Finished Tasks
  3903. You may also define it locally for a subtree by setting an ARCHIVE property
  3904. in the entry. If such a property is found in an entry, or anywhere up
  3905. the hierarchy, it will be used."
  3906. :group 'org-archive
  3907. :type 'string)
  3908. (defcustom org-agenda-skip-archived-trees t
  3909. "Non-nil means the agenda will skip any items located in archived trees.
  3910. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3911. variable is no longer recommended, you should leave it at the value t.
  3912. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3913. :group 'org-archive
  3914. :group 'org-agenda-skip
  3915. :type 'boolean)
  3916. (defcustom org-columns-skip-archived-trees t
  3917. "Non-nil means ignore archived trees when creating column view."
  3918. :group 'org-archive
  3919. :group 'org-properties
  3920. :type 'boolean)
  3921. (defcustom org-cycle-open-archived-trees nil
  3922. "Non-nil means `org-cycle' will open archived trees.
  3923. An archived tree is a tree marked with the tag ARCHIVE.
  3924. When nil, archived trees will stay folded. You can still open them with
  3925. normal outline commands like `show-all', but not with the cycling commands."
  3926. :group 'org-archive
  3927. :group 'org-cycle
  3928. :type 'boolean)
  3929. (defcustom org-sparse-tree-open-archived-trees nil
  3930. "Non-nil means sparse tree construction shows matches in archived trees.
  3931. When nil, matches in these trees are highlighted, but the trees are kept in
  3932. collapsed state."
  3933. :group 'org-archive
  3934. :group 'org-sparse-trees
  3935. :type 'boolean)
  3936. (defcustom org-sparse-tree-default-date-type nil
  3937. "The default date type when building a sparse tree.
  3938. When this is nil, a date is a scheduled or a deadline timestamp.
  3939. Otherwise, these types are allowed:
  3940. all: all timestamps
  3941. active: only active timestamps (<...>)
  3942. inactive: only inactive timestamps ([...])
  3943. scheduled: only scheduled timestamps
  3944. deadline: only deadline timestamps"
  3945. :type '(choice (const :tag "Scheduled or deadline" nil)
  3946. (const :tag "All timestamps" all)
  3947. (const :tag "Only active timestamps" active)
  3948. (const :tag "Only inactive timestamps" inactive)
  3949. (const :tag "Only scheduled timestamps" scheduled)
  3950. (const :tag "Only deadline timestamps" deadline)
  3951. (const :tag "Only closed timestamps" closed))
  3952. :version "26.1"
  3953. :package-version '(Org . "8.3")
  3954. :group 'org-sparse-trees)
  3955. (defun org-cycle-hide-archived-subtrees (state)
  3956. "Re-hide all archived subtrees after a visibility state change.
  3957. STATE should be one of the symbols listed in the docstring of
  3958. `org-cycle-hook'."
  3959. (when (and (not org-cycle-open-archived-trees)
  3960. (not (memq state '(overview folded))))
  3961. (save-excursion
  3962. (let* ((globalp (memq state '(contents all)))
  3963. (beg (if globalp (point-min) (point)))
  3964. (end (if globalp (point-max) (org-end-of-subtree t))))
  3965. (org-hide-archived-subtrees beg end)
  3966. (goto-char beg)
  3967. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3968. (message "%s" (substitute-command-keys
  3969. "Subtree is archived and stays closed. Use \
  3970. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3971. (defun org-force-cycle-archived ()
  3972. "Cycle subtree even if it is archived."
  3973. (interactive)
  3974. (setq this-command 'org-cycle)
  3975. (let ((org-cycle-open-archived-trees t))
  3976. (call-interactively 'org-cycle)))
  3977. (defun org-hide-archived-subtrees (beg end)
  3978. "Re-hide all archived subtrees after a visibility state change."
  3979. (org-with-wide-buffer
  3980. (let ((case-fold-search nil)
  3981. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3982. (goto-char beg)
  3983. ;; Include headline point is currently on.
  3984. (beginning-of-line)
  3985. (while (and (< (point) end) (re-search-forward re end t))
  3986. (when (member org-archive-tag (org-get-tags nil t))
  3987. (org-flag-subtree t)
  3988. (org-end-of-subtree t))))))
  3989. (defun org-flag-subtree (flag)
  3990. (save-excursion
  3991. (org-back-to-heading t)
  3992. (org-flag-region (line-end-position)
  3993. (progn (org-end-of-subtree t) (point))
  3994. flag
  3995. 'outline)))
  3996. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3997. ;; Declare Column View Code
  3998. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3999. (declare-function org-columns-compute "org-colview" (property))
  4000. ;; Declare ID code
  4001. (declare-function org-id-store-link "org-id")
  4002. (declare-function org-id-locations-load "org-id")
  4003. (declare-function org-id-locations-save "org-id")
  4004. (defvar org-id-track-globally)
  4005. ;;; Variables for pre-computed regular expressions, all buffer local
  4006. (defvar-local org-todo-regexp nil
  4007. "Matches any of the TODO state keywords.
  4008. Since TODO keywords are case-sensitive, `case-fold-search' is
  4009. expected to be bound to nil when matching against this regexp.")
  4010. (defvar-local org-not-done-regexp nil
  4011. "Matches any of the TODO state keywords except the last one.
  4012. Since TODO keywords are case-sensitive, `case-fold-search' is
  4013. expected to be bound to nil when matching against this regexp.")
  4014. (defvar-local org-not-done-heading-regexp nil
  4015. "Matches a TODO headline that is not done.
  4016. Since TODO keywords are case-sensitive, `case-fold-search' is
  4017. expected to be bound to nil when matching against this regexp.")
  4018. (defvar-local org-todo-line-regexp nil
  4019. "Matches a headline and puts TODO state into group 2 if present.
  4020. Since TODO keywords are case-sensitive, `case-fold-search' is
  4021. expected to be bound to nil when matching against this regexp.")
  4022. (defvar-local org-complex-heading-regexp nil
  4023. "Matches a headline and puts everything into groups:
  4024. group 1: Stars
  4025. group 2: The TODO keyword, maybe
  4026. group 3: Priority cookie
  4027. group 4: True headline
  4028. group 5: Tags
  4029. Since TODO keywords are case-sensitive, `case-fold-search' is
  4030. expected to be bound to nil when matching against this regexp.")
  4031. (defvar-local org-complex-heading-regexp-format nil
  4032. "Printf format to make regexp to match an exact headline.
  4033. This regexp will match the headline of any node which has the
  4034. exact headline text that is put into the format, but may have any
  4035. TODO state, priority and tags.")
  4036. (defvar-local org-todo-line-tags-regexp nil
  4037. "Matches a headline and puts TODO state into group 2 if present.
  4038. Also put tags into group 4 if tags are present.")
  4039. (defconst org-plain-time-of-day-regexp
  4040. (concat
  4041. "\\(\\<[012]?[0-9]"
  4042. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4043. "\\(--?"
  4044. "\\(\\<[012]?[0-9]"
  4045. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4046. "\\)?")
  4047. "Regular expression to match a plain time or time range.
  4048. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4049. groups carry important information:
  4050. 0 the full match
  4051. 1 the first time, range or not
  4052. 8 the second time, if it is a range.")
  4053. (defconst org-plain-time-extension-regexp
  4054. (concat
  4055. "\\(\\<[012]?[0-9]"
  4056. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4057. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4058. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4059. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4060. groups carry important information:
  4061. 0 the full match
  4062. 7 hours of duration
  4063. 9 minutes of duration")
  4064. (defconst org-stamp-time-of-day-regexp
  4065. (concat
  4066. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4067. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4068. "\\(--?"
  4069. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4070. "Regular expression to match a timestamp time or time range.
  4071. After a match, the following groups carry important information:
  4072. 0 the full match
  4073. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4074. 2 the first time, range or not
  4075. 4 the second time, if it is a range.")
  4076. (defconst org-startup-options
  4077. '(("fold" org-startup-folded t)
  4078. ("overview" org-startup-folded t)
  4079. ("nofold" org-startup-folded nil)
  4080. ("showall" org-startup-folded nil)
  4081. ("showeverything" org-startup-folded showeverything)
  4082. ("content" org-startup-folded content)
  4083. ("indent" org-startup-indented t)
  4084. ("noindent" org-startup-indented nil)
  4085. ("hidestars" org-hide-leading-stars t)
  4086. ("showstars" org-hide-leading-stars nil)
  4087. ("odd" org-odd-levels-only t)
  4088. ("oddeven" org-odd-levels-only nil)
  4089. ("align" org-startup-align-all-tables t)
  4090. ("noalign" org-startup-align-all-tables nil)
  4091. ("shrink" org-startup-shrink-all-tables t)
  4092. ("inlineimages" org-startup-with-inline-images t)
  4093. ("noinlineimages" org-startup-with-inline-images nil)
  4094. ("latexpreview" org-startup-with-latex-preview t)
  4095. ("nolatexpreview" org-startup-with-latex-preview nil)
  4096. ("customtime" org-display-custom-times t)
  4097. ("logdone" org-log-done time)
  4098. ("lognotedone" org-log-done note)
  4099. ("nologdone" org-log-done nil)
  4100. ("lognoteclock-out" org-log-note-clock-out t)
  4101. ("nolognoteclock-out" org-log-note-clock-out nil)
  4102. ("logrepeat" org-log-repeat state)
  4103. ("lognoterepeat" org-log-repeat note)
  4104. ("logdrawer" org-log-into-drawer t)
  4105. ("nologdrawer" org-log-into-drawer nil)
  4106. ("logstatesreversed" org-log-states-order-reversed t)
  4107. ("nologstatesreversed" org-log-states-order-reversed nil)
  4108. ("nologrepeat" org-log-repeat nil)
  4109. ("logreschedule" org-log-reschedule time)
  4110. ("lognotereschedule" org-log-reschedule note)
  4111. ("nologreschedule" org-log-reschedule nil)
  4112. ("logredeadline" org-log-redeadline time)
  4113. ("lognoteredeadline" org-log-redeadline note)
  4114. ("nologredeadline" org-log-redeadline nil)
  4115. ("logrefile" org-log-refile time)
  4116. ("lognoterefile" org-log-refile note)
  4117. ("nologrefile" org-log-refile nil)
  4118. ("fninline" org-footnote-define-inline t)
  4119. ("nofninline" org-footnote-define-inline nil)
  4120. ("fnlocal" org-footnote-section nil)
  4121. ("fnauto" org-footnote-auto-label t)
  4122. ("fnprompt" org-footnote-auto-label nil)
  4123. ("fnconfirm" org-footnote-auto-label confirm)
  4124. ("fnplain" org-footnote-auto-label plain)
  4125. ("fnadjust" org-footnote-auto-adjust t)
  4126. ("nofnadjust" org-footnote-auto-adjust nil)
  4127. ("constcgs" constants-unit-system cgs)
  4128. ("constSI" constants-unit-system SI)
  4129. ("noptag" org-tag-persistent-alist nil)
  4130. ("hideblocks" org-hide-block-startup t)
  4131. ("nohideblocks" org-hide-block-startup nil)
  4132. ("beamer" org-startup-with-beamer-mode t)
  4133. ("entitiespretty" org-pretty-entities t)
  4134. ("entitiesplain" org-pretty-entities nil))
  4135. "Variable associated with STARTUP options for Org.
  4136. Each element is a list of three items: the startup options (as written
  4137. in the #+STARTUP line), the corresponding variable, and the value to set
  4138. this variable to if the option is found. An optional forth element PUSH
  4139. means to push this value onto the list in the variable.")
  4140. (defcustom org-group-tags t
  4141. "When non-nil (the default), use group tags.
  4142. This can be turned on/off through `org-toggle-tags-groups'."
  4143. :group 'org-tags
  4144. :group 'org-startup
  4145. :type 'boolean)
  4146. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4147. (defun org-toggle-tags-groups ()
  4148. "Toggle support for group tags.
  4149. Support for group tags is controlled by the option
  4150. `org-group-tags', which is non-nil by default."
  4151. (interactive)
  4152. (setq org-group-tags (not org-group-tags))
  4153. (cond ((and (derived-mode-p 'org-agenda-mode)
  4154. org-group-tags)
  4155. (org-agenda-redo))
  4156. ((derived-mode-p 'org-mode)
  4157. (let ((org-inhibit-startup t)) (org-mode))))
  4158. (message "Groups tags support has been turned %s"
  4159. (if org-group-tags "on" "off")))
  4160. (defun org-tag-add-to-alist (alist1 alist2)
  4161. "Append ALIST1 elements to ALIST2 if they are not there yet."
  4162. (cond
  4163. ((null alist2) alist1)
  4164. ((null alist1) alist2)
  4165. (t (let ((alist2-cars (mapcar (lambda (x) (car-safe x)) alist2))
  4166. to-add)
  4167. (dolist (i alist1)
  4168. (unless (member (car-safe i) alist2-cars)
  4169. (push i to-add)))
  4170. (append to-add alist2)))))
  4171. (defun org-set-regexps-and-options (&optional tags-only)
  4172. "Precompute regular expressions used in the current buffer.
  4173. When optional argument TAGS-ONLY is non-nil, only compute tags
  4174. related expressions."
  4175. (when (derived-mode-p 'org-mode)
  4176. (let ((alist (org--setup-collect-keywords
  4177. (org-make-options-regexp
  4178. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4179. (and (not tags-only)
  4180. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4181. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4182. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4183. ;; Startup options. Get this early since it does change
  4184. ;; behavior for other options (e.g., tags).
  4185. (let ((startup (cdr (assq 'startup alist))))
  4186. (dolist (option startup)
  4187. (let ((entry (assoc-string option org-startup-options t)))
  4188. (when entry
  4189. (let ((var (nth 1 entry))
  4190. (val (nth 2 entry)))
  4191. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4192. (unless (listp (symbol-value var))
  4193. (set (make-local-variable var) nil))
  4194. (add-to-list var val)))))))
  4195. (setq-local org-file-tags
  4196. (mapcar #'org-add-prop-inherited
  4197. (cdr (assq 'filetags alist))))
  4198. (setq org-current-tag-alist
  4199. (org-tag-add-to-alist
  4200. org-tag-persistent-alist
  4201. (let ((tags (cdr (assq 'tags alist))))
  4202. (if tags (org-tag-string-to-alist tags)
  4203. org-tag-alist))))
  4204. (setq org-tag-groups-alist
  4205. (org-tag-alist-to-groups org-current-tag-alist))
  4206. (unless tags-only
  4207. ;; File properties.
  4208. (setq-local org-file-properties (cdr (assq 'property alist)))
  4209. ;; Archive location.
  4210. (let ((archive (cdr (assq 'archive alist))))
  4211. (when archive (setq-local org-archive-location archive)))
  4212. ;; Category.
  4213. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4214. (when cat
  4215. (setq-local org-category (intern cat))
  4216. (setq-local org-file-properties
  4217. (org--update-property-plist
  4218. "CATEGORY" cat org-file-properties))))
  4219. ;; Columns.
  4220. (let ((column (cdr (assq 'columns alist))))
  4221. (when column (setq-local org-columns-default-format column)))
  4222. ;; Constants.
  4223. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4224. ;; Link abbreviations.
  4225. (let ((links (cdr (assq 'link alist))))
  4226. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4227. ;; Priorities.
  4228. (let ((priorities (cdr (assq 'priorities alist))))
  4229. (when priorities
  4230. (setq-local org-highest-priority (nth 0 priorities))
  4231. (setq-local org-lowest-priority (nth 1 priorities))
  4232. (setq-local org-default-priority (nth 2 priorities))))
  4233. ;; Scripts.
  4234. (let ((scripts (assq 'scripts alist)))
  4235. (when scripts
  4236. (setq-local org-use-sub-superscripts (cdr scripts))))
  4237. ;; TODO keywords.
  4238. (setq-local org-todo-kwd-alist nil)
  4239. (setq-local org-todo-key-alist nil)
  4240. (setq-local org-todo-key-trigger nil)
  4241. (setq-local org-todo-keywords-1 nil)
  4242. (setq-local org-done-keywords nil)
  4243. (setq-local org-todo-heads nil)
  4244. (setq-local org-todo-sets nil)
  4245. (setq-local org-todo-log-states nil)
  4246. (let ((todo-sequences
  4247. (or (nreverse (cdr (assq 'todo alist)))
  4248. (let ((d (default-value 'org-todo-keywords)))
  4249. (if (not (stringp (car d))) d
  4250. ;; XXX: Backward compatibility code.
  4251. (list (cons org-todo-interpretation d)))))))
  4252. (dolist (sequence todo-sequences)
  4253. (let* ((sequence (or (run-hook-with-args-until-success
  4254. 'org-todo-setup-filter-hook sequence)
  4255. sequence))
  4256. (sequence-type (car sequence))
  4257. (keywords (cdr sequence))
  4258. (sep (member "|" keywords))
  4259. names alist)
  4260. (dolist (k (remove "|" keywords))
  4261. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4262. k)
  4263. (error "Invalid TODO keyword %s" k))
  4264. (let ((name (match-string 1 k))
  4265. (key (match-string 2 k))
  4266. (log (org-extract-log-state-settings k)))
  4267. (push name names)
  4268. (push (cons name (and key (string-to-char key))) alist)
  4269. (when log (push log org-todo-log-states))))
  4270. (let* ((names (nreverse names))
  4271. (done (if sep (org-remove-keyword-keys (cdr sep))
  4272. (last names)))
  4273. (head (car names))
  4274. (tail (list sequence-type head (car done) (org-last done))))
  4275. (add-to-list 'org-todo-heads head 'append)
  4276. (push names org-todo-sets)
  4277. (setq org-done-keywords (append org-done-keywords done nil))
  4278. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4279. (setq org-todo-key-alist
  4280. (append org-todo-key-alist
  4281. (and alist
  4282. (append '((:startgroup))
  4283. (nreverse alist)
  4284. '((:endgroup))))))
  4285. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4286. (setq org-todo-sets (nreverse org-todo-sets)
  4287. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4288. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4289. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4290. ;; Compute the regular expressions and other local variables.
  4291. ;; Using `org-outline-regexp-bol' would complicate them much,
  4292. ;; because of the fixed white space at the end of that string.
  4293. (unless org-done-keywords
  4294. (setq org-done-keywords
  4295. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4296. (setq org-not-done-keywords
  4297. (org-delete-all org-done-keywords
  4298. (copy-sequence org-todo-keywords-1))
  4299. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4300. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4301. org-not-done-heading-regexp
  4302. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4303. org-todo-line-regexp
  4304. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4305. org-complex-heading-regexp
  4306. (concat "^\\(\\*+\\)"
  4307. "\\(?: +" org-todo-regexp "\\)?"
  4308. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4309. "\\(?: +\\(.*?\\)\\)??"
  4310. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4311. "[ \t]*$")
  4312. org-complex-heading-regexp-format
  4313. (concat "^\\(\\*+\\)"
  4314. "\\(?: +" org-todo-regexp "\\)?"
  4315. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4316. "\\(?: +"
  4317. ;; Stats cookies can be stuck to body.
  4318. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4319. "\\(%s\\)"
  4320. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4321. "\\)"
  4322. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4323. "[ \t]*$")
  4324. org-todo-line-tags-regexp
  4325. (concat "^\\(\\*+\\)"
  4326. "\\(?: +" org-todo-regexp "\\)?"
  4327. "\\(?: +\\(.*?\\)\\)??"
  4328. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4329. "[ \t]*$"))
  4330. (org-compute-latex-and-related-regexp)))))
  4331. (defun org--setup-collect-keywords (regexp &optional files alist)
  4332. "Return setup keywords values as an alist.
  4333. REGEXP matches a subset of setup keywords. FILES is a list of
  4334. file names already visited. It is used to avoid circular setup
  4335. files. ALIST, when non-nil, is the alist computed so far.
  4336. Return value contains the following keys: `archive', `category',
  4337. `columns', `constants', `filetags', `link', `priorities',
  4338. `property', `scripts', `startup', `tags' and `todo'."
  4339. (org-with-wide-buffer
  4340. (goto-char (point-min))
  4341. (let ((case-fold-search t))
  4342. (while (re-search-forward regexp nil t)
  4343. (let ((element (org-element-at-point)))
  4344. (when (eq (org-element-type element) 'keyword)
  4345. (let ((key (org-element-property :key element))
  4346. (value (org-element-property :value element)))
  4347. (cond
  4348. ((equal key "ARCHIVE")
  4349. (when (org-string-nw-p value)
  4350. (push (cons 'archive value) alist)))
  4351. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4352. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4353. ((equal key "CONSTANTS")
  4354. (let* ((constants (assq 'constants alist))
  4355. (store (cdr constants)))
  4356. (dolist (pair (split-string value))
  4357. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4358. pair)
  4359. (let* ((name (match-string 1 pair))
  4360. (value (match-string 2 pair))
  4361. (old (assoc name store)))
  4362. (if old (setcdr old value)
  4363. (push (cons name value) store)))))
  4364. (if constants (setcdr constants store)
  4365. (push (cons 'constants store) alist))))
  4366. ((equal key "FILETAGS")
  4367. (when (org-string-nw-p value)
  4368. (let ((old (assq 'filetags alist))
  4369. (new (apply #'nconc
  4370. (mapcar (lambda (x) (org-split-string x ":"))
  4371. (split-string value)))))
  4372. (if old (setcdr old (append new (cdr old)))
  4373. (push (cons 'filetags new) alist)))))
  4374. ((equal key "LINK")
  4375. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4376. (let ((links (assq 'link alist))
  4377. (pair (cons (match-string-no-properties 1 value)
  4378. (match-string-no-properties 2 value))))
  4379. (if links (push pair (cdr links))
  4380. (push (list 'link pair) alist)))))
  4381. ((equal key "OPTIONS")
  4382. (when (and (org-string-nw-p value)
  4383. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4384. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4385. ((equal key "PRIORITIES")
  4386. (push (cons 'priorities
  4387. (let ((prio (split-string value)))
  4388. (if (< (length prio) 3) '(?A ?C ?B)
  4389. (mapcar #'string-to-char prio))))
  4390. alist))
  4391. ((equal key "PROPERTY")
  4392. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4393. (let* ((property (assq 'property alist))
  4394. (value (org--update-property-plist
  4395. (match-string-no-properties 1 value)
  4396. (match-string-no-properties 2 value)
  4397. (cdr property))))
  4398. (if property (setcdr property value)
  4399. (push (cons 'property value) alist)))))
  4400. ((equal key "STARTUP")
  4401. (let ((startup (assq 'startup alist)))
  4402. (if startup
  4403. (setcdr startup
  4404. (append (cdr startup) (split-string value)))
  4405. (push (cons 'startup (split-string value)) alist))))
  4406. ((equal key "TAGS")
  4407. (let ((tag-cell (assq 'tags alist)))
  4408. (if tag-cell
  4409. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4410. (push (cons 'tags value) alist))))
  4411. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4412. (let ((todo (assq 'todo alist))
  4413. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4414. (split-string value))))
  4415. (if todo (push value (cdr todo))
  4416. (push (list 'todo value) alist))))
  4417. ((equal key "SETUPFILE")
  4418. (unless buffer-read-only ; Do not check in Gnus messages.
  4419. (let ((f (and (org-string-nw-p value)
  4420. (expand-file-name
  4421. (org-unbracket-string "\"" "\"" value)))))
  4422. (when (and f (file-readable-p f) (not (member f files)))
  4423. (with-temp-buffer
  4424. (setq default-directory (file-name-directory f))
  4425. (insert-file-contents f)
  4426. (setq alist
  4427. ;; Fake Org mode to benefit from cache
  4428. ;; without recurring needlessly.
  4429. (let ((major-mode 'org-mode))
  4430. (org--setup-collect-keywords
  4431. regexp (cons f files) alist)))))))))))))))
  4432. alist)
  4433. (defun org-tag-string-to-alist (s)
  4434. "Return tag alist associated to string S.
  4435. S is a value for TAGS keyword or produced with
  4436. `org-tag-alist-to-string'. Return value is an alist suitable for
  4437. `org-tag-alist' or `org-tag-persistent-alist'."
  4438. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4439. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4440. "\\|{.+?}\\)" ; regular expression
  4441. "\\(?:(\\(.\\))\\)?\\'"))
  4442. alist group-flag)
  4443. (dolist (tokens lines (cdr (nreverse alist)))
  4444. (push '(:newline) alist)
  4445. (while tokens
  4446. (let ((token (pop tokens)))
  4447. (pcase token
  4448. ("{"
  4449. (push '(:startgroup) alist)
  4450. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4451. ("}"
  4452. (push '(:endgroup) alist)
  4453. (setq group-flag nil))
  4454. ("["
  4455. (push '(:startgrouptag) alist)
  4456. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4457. ("]"
  4458. (push '(:endgrouptag) alist)
  4459. (setq group-flag nil))
  4460. (":"
  4461. (push '(:grouptags) alist))
  4462. ((guard (string-match tag-re token))
  4463. (let ((tag (match-string 1 token))
  4464. (key (and (match-beginning 2)
  4465. (string-to-char (match-string 2 token)))))
  4466. ;; Push all tags in groups, no matter if they already
  4467. ;; appear somewhere else in the list.
  4468. (when (or group-flag (not (assoc tag alist)))
  4469. (push (cons tag key) alist))))))))))
  4470. (defun org-tag-alist-to-string (alist &optional skip-key)
  4471. "Return tag string associated to ALIST.
  4472. ALIST is an alist, as defined in `org-tag-alist' or
  4473. `org-tag-persistent-alist', or produced with
  4474. `org-tag-string-to-alist'.
  4475. Return value is a string suitable as a value for \"TAGS\"
  4476. keyword.
  4477. When optional argument SKIP-KEY is non-nil, skip selection keys
  4478. next to tags."
  4479. (mapconcat (lambda (token)
  4480. (pcase token
  4481. (`(:startgroup) "{")
  4482. (`(:endgroup) "}")
  4483. (`(:startgrouptag) "[")
  4484. (`(:endgrouptag) "]")
  4485. (`(:grouptags) ":")
  4486. (`(:newline) "\\n")
  4487. ((and
  4488. (guard (not skip-key))
  4489. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4490. (format "%s(%c)" tag key))
  4491. (`(,(and tag (pred stringp)) . ,_) tag)
  4492. (_ (user-error "Invalid tag token: %S" token))))
  4493. alist
  4494. " "))
  4495. (defun org-tag-alist-to-groups (alist)
  4496. "Return group alist from tag ALIST.
  4497. ALIST is an alist, as defined in `org-tag-alist' or
  4498. `org-tag-persistent-alist', or produced with
  4499. `org-tag-string-to-alist'. Return value is an alist following
  4500. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4501. a string, summarizing TAGS, as a list of strings."
  4502. (let (groups group-status current-group)
  4503. (dolist (token alist (nreverse groups))
  4504. (pcase token
  4505. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4506. (`(,(or :endgroup :endgrouptag))
  4507. (when (eq group-status 'append)
  4508. (push (nreverse current-group) groups))
  4509. (setq group-status nil current-group nil))
  4510. (`(:grouptags) (setq group-status 'append))
  4511. ((and `(,tag . ,_) (guard group-status))
  4512. (if (eq group-status 'append) (push tag current-group)
  4513. (setq current-group (list tag))))
  4514. (_ nil)))))
  4515. (defvar org--file-cache (make-hash-table :test #'equal)
  4516. "Hash table to store contents of files referenced via a URL.
  4517. This is the cache of file URLs read using `org-file-contents'.")
  4518. (defun org-reset-file-cache ()
  4519. "Reset the cache of files downloaded by `org-file-contents'."
  4520. (clrhash org--file-cache))
  4521. (defun org-file-url-p (file)
  4522. "Non-nil if FILE is a URL."
  4523. (require 'ffap)
  4524. (string-match-p ffap-url-regexp file))
  4525. (defun org-file-contents (file &optional noerror nocache)
  4526. "Return the contents of FILE, as a string.
  4527. FILE can be a file name or URL.
  4528. If FILE is a URL, download the contents. If the URL contents are
  4529. already cached in the `org--file-cache' hash table, the download step
  4530. is skipped.
  4531. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4532. from file or URL.
  4533. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4534. is available. This option applies only if FILE is a URL."
  4535. (let* ((is-url (org-file-url-p file))
  4536. (cache (and is-url
  4537. (not nocache)
  4538. (gethash file org--file-cache))))
  4539. (cond
  4540. (cache)
  4541. (is-url
  4542. (with-current-buffer (url-retrieve-synchronously file)
  4543. (goto-char (point-min))
  4544. ;; Move point to after the url-retrieve header.
  4545. (search-forward "\n\n" nil :move)
  4546. ;; Search for the success code only in the url-retrieve header.
  4547. (if (save-excursion
  4548. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4549. ;; Update the cache `org--file-cache' and return contents.
  4550. (puthash file
  4551. (buffer-substring-no-properties (point) (point-max))
  4552. org--file-cache)
  4553. (funcall (if noerror #'message #'user-error)
  4554. "Unable to fetch file from %S"
  4555. file))))
  4556. (t
  4557. (with-temp-buffer
  4558. (condition-case nil
  4559. (progn
  4560. (insert-file-contents file)
  4561. (buffer-string))
  4562. (file-error
  4563. (funcall (if noerror #'message #'user-error)
  4564. "Unable to read file %S"
  4565. file))))))))
  4566. (defun org-extract-log-state-settings (x)
  4567. "Extract the log state setting from a TODO keyword string.
  4568. This will extract info from a string like \"WAIT(w@/!)\"."
  4569. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4570. (let ((kw (match-string 1 x))
  4571. (log1 (and (match-end 3) (match-string 3 x)))
  4572. (log2 (and (match-end 4) (match-string 4 x))))
  4573. (and (or log1 log2)
  4574. (list kw
  4575. (and log1 (if (equal log1 "!") 'time 'note))
  4576. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4577. (defun org-remove-keyword-keys (list)
  4578. "Remove a pair of parenthesis at the end of each string in LIST."
  4579. (mapcar (lambda (x)
  4580. (if (string-match "(.*)$" x)
  4581. (substring x 0 (match-beginning 0))
  4582. x))
  4583. list))
  4584. (defun org-assign-fast-keys (alist)
  4585. "Assign fast keys to a keyword-key alist.
  4586. Respect keys that are already there."
  4587. (let (new e (alt ?0))
  4588. (while (setq e (pop alist))
  4589. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4590. (cdr e)) ;; Key already assigned.
  4591. (push e new)
  4592. (let ((clist (string-to-list (downcase (car e))))
  4593. (used (append new alist)))
  4594. (when (= (car clist) ?@)
  4595. (pop clist))
  4596. (while (and clist (rassoc (car clist) used))
  4597. (pop clist))
  4598. (unless clist
  4599. (while (rassoc alt used)
  4600. (cl-incf alt)))
  4601. (push (cons (car e) (or (car clist) alt)) new))))
  4602. (nreverse new)))
  4603. ;;; Some variables used in various places
  4604. (defvar org-window-configuration nil
  4605. "Used in various places to store a window configuration.")
  4606. (defvar org-selected-window nil
  4607. "Used in various places to store a window configuration.")
  4608. (defvar org-finish-function nil
  4609. "Function to be called when `C-c C-c' is used.
  4610. This is for getting out of special buffers like capture.")
  4611. (defvar org-last-state)
  4612. ;; Defined somewhere in this file, but used before definition.
  4613. (defvar org-entities) ;; defined in org-entities.el
  4614. (defvar org-struct-menu)
  4615. (defvar org-org-menu)
  4616. (defvar org-tbl-menu)
  4617. ;;;; Define the Org mode
  4618. ;; We use a before-change function to check if a table might need
  4619. ;; an update.
  4620. (defvar org-table-may-need-update t
  4621. "Indicates that a table might need an update.
  4622. This variable is set by `org-before-change-function'.
  4623. `org-table-align' sets it back to nil.")
  4624. (defun org-before-change-function (_beg _end)
  4625. "Every change indicates that a table might need an update."
  4626. (setq org-table-may-need-update t))
  4627. (defvar org-mode-map)
  4628. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4629. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4630. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4631. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4632. (defvar org-table-buffer-is-an nil)
  4633. (defvar bidi-paragraph-direction)
  4634. (defvar buffer-face-mode-face)
  4635. (require 'outline)
  4636. ;; Other stuff we need.
  4637. (require 'time-date)
  4638. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4639. (require 'easymenu)
  4640. (autoload 'easy-menu-add "easymenu")
  4641. (require 'overlay)
  4642. ;; (require 'org-macs) moved higher up in the file before it is first used
  4643. (require 'org-entities)
  4644. ;; (require 'org-compat) moved higher up in the file before it is first used
  4645. (require 'org-faces)
  4646. (require 'org-list)
  4647. (require 'org-pcomplete)
  4648. (require 'org-src)
  4649. (require 'org-footnote)
  4650. (require 'org-macro)
  4651. ;; babel
  4652. (require 'ob)
  4653. ;;;###autoload
  4654. (define-derived-mode org-mode outline-mode "Org"
  4655. "Outline-based notes management and organizer, alias
  4656. \"Carsten's outline-mode for keeping track of everything.\"
  4657. Org mode develops organizational tasks around a NOTES file which
  4658. contains information about projects as plain text. Org mode is
  4659. implemented on top of Outline mode, which is ideal to keep the content
  4660. of large files well structured. It supports ToDo items, deadlines and
  4661. time stamps, which magically appear in the diary listing of the Emacs
  4662. calendar. Tables are easily created with a built-in table editor.
  4663. Plain text URL-like links connect to websites, emails (VM), Usenet
  4664. messages (Gnus), BBDB entries, and any files related to the project.
  4665. For printing and sharing of notes, an Org file (or a part of it)
  4666. can be exported as a structured ASCII or HTML file.
  4667. The following commands are available:
  4668. \\{org-mode-map}"
  4669. ;; Get rid of Outline menus, they are not needed
  4670. ;; Need to do this here because define-derived-mode sets up
  4671. ;; the keymap so late. Still, it is a waste to call this each time
  4672. ;; we switch another buffer into Org mode.
  4673. (define-key org-mode-map [menu-bar headings] 'undefined)
  4674. (define-key org-mode-map [menu-bar hide] 'undefined)
  4675. (define-key org-mode-map [menu-bar show] 'undefined)
  4676. (org-load-modules-maybe)
  4677. (org-install-agenda-files-menu)
  4678. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4679. (add-to-invisibility-spec '(org-hide-block . t))
  4680. (add-to-invisibility-spec '(org-hide-drawer . t))
  4681. (setq-local outline-regexp org-outline-regexp)
  4682. (setq-local outline-level 'org-outline-level)
  4683. (setq bidi-paragraph-direction 'left-to-right)
  4684. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4685. (unless org-display-table
  4686. (setq org-display-table (make-display-table)))
  4687. (set-display-table-slot
  4688. org-display-table 4
  4689. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4690. org-ellipsis)))
  4691. (setq buffer-display-table org-display-table))
  4692. (org-set-regexps-and-options)
  4693. (org-set-font-lock-defaults)
  4694. (when (and org-tag-faces (not org-tags-special-faces-re))
  4695. ;; tag faces set outside customize.... force initialization.
  4696. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4697. ;; Calc embedded
  4698. (setq-local calc-embedded-open-mode "# ")
  4699. ;; Modify a few syntax entries
  4700. (modify-syntax-entry ?@ "w")
  4701. (modify-syntax-entry ?\" "\"")
  4702. (modify-syntax-entry ?\\ "_")
  4703. (modify-syntax-entry ?~ "_")
  4704. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4705. ;; Activate before-change-function
  4706. (setq-local org-table-may-need-update t)
  4707. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4708. ;; Check for running clock before killing a buffer
  4709. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4710. ;; Initialize macros templates.
  4711. (org-macro-initialize-templates)
  4712. ;; Initialize radio targets.
  4713. (org-update-radio-target-regexp)
  4714. ;; Indentation.
  4715. (setq-local indent-line-function 'org-indent-line)
  4716. (setq-local indent-region-function 'org-indent-region)
  4717. ;; Filling and auto-filling.
  4718. (org-setup-filling)
  4719. ;; Comments.
  4720. (org-setup-comments-handling)
  4721. ;; Initialize cache.
  4722. (org-element-cache-reset)
  4723. ;; Beginning/end of defun
  4724. (setq-local beginning-of-defun-function 'org-backward-element)
  4725. (setq-local end-of-defun-function
  4726. (lambda ()
  4727. (if (not (org-at-heading-p))
  4728. (org-forward-element)
  4729. (org-forward-element)
  4730. (forward-char -1))))
  4731. ;; Next error for sparse trees
  4732. (setq-local next-error-function 'org-occur-next-match)
  4733. ;; Make sure dependence stuff works reliably, even for users who set it
  4734. ;; too late :-(
  4735. (if org-enforce-todo-dependencies
  4736. (add-hook 'org-blocker-hook
  4737. 'org-block-todo-from-children-or-siblings-or-parent)
  4738. (remove-hook 'org-blocker-hook
  4739. 'org-block-todo-from-children-or-siblings-or-parent))
  4740. (if org-enforce-todo-checkbox-dependencies
  4741. (add-hook 'org-blocker-hook
  4742. 'org-block-todo-from-checkboxes)
  4743. (remove-hook 'org-blocker-hook
  4744. 'org-block-todo-from-checkboxes))
  4745. ;; Align options lines
  4746. (setq-local
  4747. align-mode-rules-list
  4748. '((org-in-buffer-settings
  4749. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4750. (modes . '(org-mode)))))
  4751. ;; Imenu
  4752. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4753. ;; Make isearch reveal context
  4754. (setq-local outline-isearch-open-invisible-function
  4755. (lambda (&rest _) (org-show-context 'isearch)))
  4756. ;; Setup the pcomplete hooks
  4757. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4758. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4759. (setq-local pcomplete-default-completion-function 'ignore)
  4760. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4761. (setq-local pcomplete-termination-string "")
  4762. (setq-local buffer-face-mode-face 'org-default)
  4763. ;; If empty file that did not turn on Org mode automatically, make
  4764. ;; it to.
  4765. (when (and org-insert-mode-line-in-empty-file
  4766. (called-interactively-p 'any)
  4767. (= (point-min) (point-max)))
  4768. (insert "# -*- mode: org -*-\n\n"))
  4769. (unless org-inhibit-startup
  4770. (org-unmodified
  4771. (when org-startup-with-beamer-mode (org-beamer-mode))
  4772. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4773. (org-table-map-tables
  4774. (cond ((and org-startup-align-all-tables
  4775. org-startup-shrink-all-tables)
  4776. (lambda () (org-table-align) (org-table-shrink)))
  4777. (org-startup-align-all-tables #'org-table-align)
  4778. (t #'org-table-shrink))
  4779. t))
  4780. (when org-startup-with-inline-images (org-display-inline-images))
  4781. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4782. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4783. (when org-startup-truncated (setq truncate-lines t))
  4784. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4785. (org-refresh-effort-properties)))
  4786. ;; Try to set `org-hide' face correctly.
  4787. (let ((foreground (org-find-invisible-foreground)))
  4788. (when foreground
  4789. (set-face-foreground 'org-hide foreground))))
  4790. ;; Update `customize-package-emacs-version-alist'
  4791. (add-to-list 'customize-package-emacs-version-alist
  4792. '(Org ("8.0" . "24.4")
  4793. ("8.1" . "24.4")
  4794. ("8.2" . "24.4")
  4795. ("8.2.7" . "24.4")
  4796. ("8.3" . "26.1")
  4797. ("9.0" . "26.1")
  4798. ("9.1" . "26.1")
  4799. ("9.2" . "27.1")))
  4800. (defvar org-mode-transpose-word-syntax-table
  4801. (let ((st (make-syntax-table text-mode-syntax-table)))
  4802. (dolist (c org-emphasis-alist st)
  4803. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4804. (when (fboundp 'abbrev-table-put)
  4805. (abbrev-table-put org-mode-abbrev-table
  4806. :parents (list text-mode-abbrev-table)))
  4807. (defun org-find-invisible-foreground ()
  4808. (let ((candidates (remove
  4809. "unspecified-bg"
  4810. (nconc
  4811. (list (face-background 'default)
  4812. (face-background 'org-default))
  4813. (mapcar
  4814. (lambda (alist)
  4815. (when (boundp alist)
  4816. (cdr (assq 'background-color (symbol-value alist)))))
  4817. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4818. (list (face-foreground 'org-hide))))))
  4819. (car (remove nil candidates))))
  4820. (defun org-current-time (&optional rounding-minutes past)
  4821. "Current time, possibly rounded to ROUNDING-MINUTES.
  4822. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4823. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4824. the rounding returns a past time."
  4825. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4826. (car org-time-stamp-rounding-minutes)))
  4827. (time (decode-time)) res)
  4828. (if (< r 1)
  4829. (current-time)
  4830. (setq res
  4831. (apply 'encode-time
  4832. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4833. (nthcdr 2 time))))
  4834. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4835. (seconds-to-time (- (float-time res) (* r 60)))
  4836. res))))
  4837. (defun org-today ()
  4838. "Return today date, considering `org-extend-today-until'."
  4839. (time-to-days
  4840. (time-subtract (current-time)
  4841. (list 0 (* 3600 org-extend-today-until) 0))))
  4842. ;;;; Font-Lock stuff, including the activators
  4843. (defvar org-mouse-map (make-sparse-keymap))
  4844. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4845. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4846. (when org-mouse-1-follows-link
  4847. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4848. (when org-tab-follows-link
  4849. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4850. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4851. (require 'font-lock)
  4852. (defconst org-non-link-chars "]\t\n\r<>")
  4853. (defvar org-link-types-re nil
  4854. "Matches a link that has a url-like prefix like \"http:\"")
  4855. (defvar org-link-re-with-space nil
  4856. "Matches a link with spaces, optional angular brackets around it.")
  4857. (defvar org-link-re-with-space2 nil
  4858. "Matches a link with spaces, optional angular brackets around it.")
  4859. (defvar org-link-re-with-space3 nil
  4860. "Matches a link with spaces, only for internal part in bracket links.")
  4861. (defvar org-angle-link-re nil
  4862. "Matches link with angular brackets, spaces are allowed.")
  4863. (defvar org-plain-link-re nil
  4864. "Matches plain link, without spaces.")
  4865. (defvar org-bracket-link-regexp nil
  4866. "Matches a link in double brackets.")
  4867. (defvar org-bracket-link-analytic-regexp nil
  4868. "Regular expression used to analyze links.
  4869. Here is what the match groups contain after a match:
  4870. 1: http:
  4871. 2: http
  4872. 3: path
  4873. 4: [desc]
  4874. 5: desc")
  4875. (defvar org-bracket-link-analytic-regexp++ nil
  4876. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4877. (defvar org-any-link-re nil
  4878. "Regular expression matching any link.")
  4879. (defconst org-match-sexp-depth 3
  4880. "Number of stacked braces for sub/superscript matching.")
  4881. (defun org-create-multibrace-regexp (left right n)
  4882. "Create a regular expression which will match a balanced sexp.
  4883. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4884. as single character strings.
  4885. The regexp returned will match the entire expression including the
  4886. delimiters. It will also define a single group which contains the
  4887. match except for the outermost delimiters. The maximum depth of
  4888. stacked delimiters is N. Escaping delimiters is not possible."
  4889. (let* ((nothing (concat "[^" left right "]*?"))
  4890. (or "\\|")
  4891. (re nothing)
  4892. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4893. (while (> n 1)
  4894. (setq n (1- n)
  4895. re (concat re or next)
  4896. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4897. (concat left "\\(" re "\\)" right)))
  4898. (defconst org-match-substring-regexp
  4899. (concat
  4900. "\\(\\S-\\)\\([_^]\\)\\("
  4901. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4902. "\\|"
  4903. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4904. "\\|"
  4905. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4906. "The regular expression matching a sub- or superscript.")
  4907. (defconst org-match-substring-with-braces-regexp
  4908. (concat
  4909. "\\(\\S-\\)\\([_^]\\)"
  4910. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4911. "The regular expression matching a sub- or superscript, forcing braces.")
  4912. (defun org-make-link-regexps ()
  4913. "Update the link regular expressions.
  4914. This should be called after the variable `org-link-parameters' has changed."
  4915. (let ((types-re (regexp-opt (org-link-types) t)))
  4916. (setq org-link-types-re
  4917. (concat "\\`" types-re ":")
  4918. org-link-re-with-space
  4919. (concat "<?" types-re ":"
  4920. "\\([^" org-non-link-chars " ]"
  4921. "[^" org-non-link-chars "]*"
  4922. "[^" org-non-link-chars " ]\\)>?")
  4923. org-link-re-with-space2
  4924. (concat "<?" types-re ":"
  4925. "\\([^" org-non-link-chars " ]"
  4926. "[^\t\n\r]*"
  4927. "[^" org-non-link-chars " ]\\)>?")
  4928. org-link-re-with-space3
  4929. (concat "<?" types-re ":"
  4930. "\\([^" org-non-link-chars " ]"
  4931. "[^\t\n\r]*\\)")
  4932. org-angle-link-re
  4933. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4934. types-re)
  4935. org-plain-link-re
  4936. (concat
  4937. "\\<" types-re ":"
  4938. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4939. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4940. org-bracket-link-regexp
  4941. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4942. org-bracket-link-analytic-regexp
  4943. (concat
  4944. "\\[\\["
  4945. "\\(" types-re ":\\)?"
  4946. "\\([^]]+\\)"
  4947. "\\]"
  4948. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4949. "\\]")
  4950. org-bracket-link-analytic-regexp++
  4951. (concat
  4952. "\\[\\["
  4953. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4954. "\\([^]]+\\)"
  4955. "\\]"
  4956. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4957. "\\]")
  4958. org-any-link-re
  4959. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4960. org-angle-link-re "\\)\\|\\("
  4961. org-plain-link-re "\\)"))))
  4962. (org-make-link-regexps)
  4963. (defvar org-emph-face nil)
  4964. (defun org-do-emphasis-faces (limit)
  4965. "Run through the buffer and emphasize strings."
  4966. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4967. (car org-emphasis-regexp-components))))
  4968. (catch :exit
  4969. (while (re-search-forward quick-re limit t)
  4970. (let* ((marker (match-string 2))
  4971. (verbatim? (member marker '("~" "="))))
  4972. (when (save-excursion
  4973. (goto-char (match-beginning 0))
  4974. (and
  4975. ;; Do not match table hlines.
  4976. (not (and (equal marker "+")
  4977. (org-match-line
  4978. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4979. ;; Do not match headline stars. Do not consider
  4980. ;; stars of a headline as closing marker for bold
  4981. ;; markup either.
  4982. (not (and (equal marker "*")
  4983. (save-excursion
  4984. (forward-char)
  4985. (skip-chars-backward "*")
  4986. (looking-at-p org-outline-regexp-bol))))
  4987. ;; Match full emphasis markup regexp.
  4988. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4989. ;; Do not span over paragraph boundaries.
  4990. (not (string-match-p org-element-paragraph-separate
  4991. (match-string 2)))
  4992. ;; Do not span over cells in table rows.
  4993. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4994. (string-match-p "|" (match-string 4))))))
  4995. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4996. (font-lock-prepend-text-property
  4997. (match-beginning 2) (match-end 2) 'face face)
  4998. (when verbatim?
  4999. (org-remove-flyspell-overlays-in
  5000. (match-beginning 0) (match-end 0)))
  5001. (add-text-properties (match-beginning 2) (match-end 2)
  5002. '(font-lock-multiline t org-emphasis t))
  5003. (when org-hide-emphasis-markers
  5004. (add-text-properties (match-end 4) (match-beginning 5)
  5005. '(invisible org-link))
  5006. (add-text-properties (match-beginning 3) (match-end 3)
  5007. '(invisible org-link)))
  5008. (throw :exit t))))))))
  5009. (defun org-emphasize (&optional char)
  5010. "Insert or change an emphasis, i.e. a font like bold or italic.
  5011. If there is an active region, change that region to a new emphasis.
  5012. If there is no region, just insert the marker characters and position
  5013. the cursor between them.
  5014. CHAR should be the marker character. If it is a space, it means to
  5015. remove the emphasis of the selected region.
  5016. If CHAR is not given (for example in an interactive call) it will be
  5017. prompted for."
  5018. (interactive)
  5019. (let ((erc org-emphasis-regexp-components)
  5020. (string "") beg end move s)
  5021. (if (org-region-active-p)
  5022. (setq beg (region-beginning)
  5023. end (region-end)
  5024. string (buffer-substring beg end))
  5025. (setq move t))
  5026. (unless char
  5027. (message "Emphasis marker or tag: [%s]"
  5028. (mapconcat #'car org-emphasis-alist ""))
  5029. (setq char (read-char-exclusive)))
  5030. (if (equal char ?\s)
  5031. (setq s ""
  5032. move nil)
  5033. (unless (assoc (char-to-string char) org-emphasis-alist)
  5034. (user-error "No such emphasis marker: \"%c\"" char))
  5035. (setq s (char-to-string char)))
  5036. (while (and (> (length string) 1)
  5037. (equal (substring string 0 1) (substring string -1))
  5038. (assoc (substring string 0 1) org-emphasis-alist))
  5039. (setq string (substring string 1 -1)))
  5040. (setq string (concat s string s))
  5041. (when beg (delete-region beg end))
  5042. (unless (or (bolp)
  5043. (string-match (concat "[" (nth 0 erc) "\n]")
  5044. (char-to-string (char-before (point)))))
  5045. (insert " "))
  5046. (unless (or (eobp)
  5047. (string-match (concat "[" (nth 1 erc) "\n]")
  5048. (char-to-string (char-after (point)))))
  5049. (insert " ") (backward-char 1))
  5050. (insert string)
  5051. (and move (backward-char 1))))
  5052. (defconst org-nonsticky-props
  5053. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5054. (defsubst org-rear-nonsticky-at (pos)
  5055. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5056. (defun org-activate-links (limit)
  5057. "Add link properties to links.
  5058. This includes angle, plain, and bracket links."
  5059. (catch :exit
  5060. (while (re-search-forward org-any-link-re limit t)
  5061. (let* ((start (match-beginning 0))
  5062. (end (match-end 0))
  5063. (style (cond ((eq ?< (char-after start)) 'angle)
  5064. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5065. (t 'plain))))
  5066. (when (and (memq style org-highlight-links)
  5067. ;; Do not confuse plain links with tags.
  5068. (not (and (eq style 'plain)
  5069. (let ((face (get-text-property
  5070. (max (1- start) (point-min)) 'face)))
  5071. (if (consp face) (memq 'org-tag face)
  5072. (eq 'org-tag face))))))
  5073. (let* ((link-object (save-excursion
  5074. (goto-char start)
  5075. (save-match-data (org-element-link-parser))))
  5076. (link (org-element-property :raw-link link-object))
  5077. (type (org-element-property :type link-object))
  5078. (path (org-element-property :path link-object))
  5079. (properties ;for link's visible part
  5080. (list
  5081. 'face (pcase (org-link-get-parameter type :face)
  5082. ((and (pred functionp) face) (funcall face path))
  5083. ((and (pred facep) face) face)
  5084. ((and (pred consp) face) face) ;anonymous
  5085. (_ 'org-link))
  5086. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5087. 'highlight)
  5088. 'keymap (or (org-link-get-parameter type :keymap)
  5089. org-mouse-map)
  5090. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5091. ((and (pred stringp) echo) echo)
  5092. ((and (pred functionp) echo) echo)
  5093. (_ (concat "LINK: " link)))
  5094. 'htmlize-link (pcase (org-link-get-parameter type
  5095. :htmlize-link)
  5096. ((and (pred functionp) f) (funcall f))
  5097. (_ `(:uri ,link)))
  5098. 'font-lock-multiline t)))
  5099. (org-remove-flyspell-overlays-in start end)
  5100. (org-rear-nonsticky-at end)
  5101. (if (not (eq 'bracket style))
  5102. (add-text-properties start end properties)
  5103. ;; Handle invisible parts in bracket links.
  5104. (remove-text-properties start end '(invisible nil))
  5105. (let ((hidden
  5106. (append `(invisible
  5107. ,(or (org-link-get-parameter type :display)
  5108. 'org-link))
  5109. properties))
  5110. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5111. (visible-end (or (match-end 4) (match-end 2))))
  5112. (add-text-properties start visible-start hidden)
  5113. (add-text-properties visible-start visible-end properties)
  5114. (add-text-properties visible-end end hidden)
  5115. (org-rear-nonsticky-at visible-start)
  5116. (org-rear-nonsticky-at visible-end)))
  5117. (let ((f (org-link-get-parameter type :activate-func)))
  5118. (when (functionp f)
  5119. (funcall f start end path (eq style 'bracket))))
  5120. (throw :exit t))))) ;signal success
  5121. nil))
  5122. (defun org-activate-code (limit)
  5123. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5124. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5125. (remove-text-properties (match-beginning 0) (match-end 0)
  5126. '(display t invisible t intangible t))
  5127. t))
  5128. (defcustom org-src-fontify-natively t
  5129. "When non-nil, fontify code in code blocks.
  5130. See also the `org-block' face."
  5131. :type 'boolean
  5132. :version "26.1"
  5133. :package-version '(Org . "8.3")
  5134. :group 'org-appearance
  5135. :group 'org-babel)
  5136. (defcustom org-allow-promoting-top-level-subtree nil
  5137. "When non-nil, allow promoting a top level subtree.
  5138. The leading star of the top level headline will be replaced
  5139. by a #."
  5140. :type 'boolean
  5141. :version "24.1"
  5142. :group 'org-appearance)
  5143. (defun org-fontify-meta-lines-and-blocks (limit)
  5144. (condition-case nil
  5145. (org-fontify-meta-lines-and-blocks-1 limit)
  5146. (error (message "Org mode fontification error in %S at %d"
  5147. (current-buffer)
  5148. (line-number-at-pos)))))
  5149. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5150. "Fontify #+ lines and blocks."
  5151. (let ((case-fold-search t))
  5152. (when (re-search-forward
  5153. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5154. limit t)
  5155. (let ((beg (match-beginning 0))
  5156. (block-start (match-end 0))
  5157. (block-end nil)
  5158. (lang (match-string 7))
  5159. (beg1 (line-beginning-position 2))
  5160. (dc1 (downcase (match-string 2)))
  5161. (dc3 (downcase (match-string 3)))
  5162. end end1 quoting block-type)
  5163. (cond
  5164. ((and (match-end 4) (equal dc3 "+begin"))
  5165. ;; Truly a block
  5166. (setq block-type (downcase (match-string 5))
  5167. quoting (member block-type org-protecting-blocks))
  5168. (when (re-search-forward
  5169. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5170. nil t) ;; on purpose, we look further than LIMIT
  5171. (setq end (min (point-max) (match-end 0))
  5172. end1 (min (point-max) (1- (match-beginning 0))))
  5173. (setq block-end (match-beginning 0))
  5174. (when quoting
  5175. (org-remove-flyspell-overlays-in beg1 end1)
  5176. (remove-text-properties beg end
  5177. '(display t invisible t intangible t)))
  5178. (add-text-properties
  5179. beg end '(font-lock-fontified t font-lock-multiline t))
  5180. (add-text-properties beg beg1 '(face org-meta-line))
  5181. (org-remove-flyspell-overlays-in beg beg1)
  5182. (add-text-properties ; For end_src
  5183. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5184. (org-remove-flyspell-overlays-in end1 end)
  5185. (cond
  5186. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5187. (org-src-font-lock-fontify-block lang block-start block-end)
  5188. (add-text-properties beg1 block-end '(src-block t)))
  5189. (quoting
  5190. (add-text-properties beg1 (min (point-max) (1+ end1))
  5191. (list 'face
  5192. (list :inherit
  5193. (let ((face-name
  5194. (intern (format "org-block-%s" lang))))
  5195. (append (and (facep face-name) (list face-name))
  5196. '(org-block))))))) ; end of source block
  5197. ((not org-fontify-quote-and-verse-blocks))
  5198. ((string= block-type "quote")
  5199. (add-face-text-property
  5200. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5201. ((string= block-type "verse")
  5202. (add-face-text-property
  5203. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5204. (add-text-properties beg beg1 '(face org-block-begin-line))
  5205. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5206. '(face org-block-end-line))
  5207. t))
  5208. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5209. (org-remove-flyspell-overlays-in
  5210. (match-beginning 0)
  5211. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5212. (add-text-properties
  5213. beg (match-end 3)
  5214. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5215. '(font-lock-fontified t invisible t)
  5216. '(font-lock-fontified t face org-document-info-keyword)))
  5217. (add-text-properties
  5218. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5219. (if (string-equal dc1 "+title:")
  5220. '(font-lock-fontified t face org-document-title)
  5221. '(font-lock-fontified t face org-document-info))))
  5222. ((string-prefix-p "+caption" dc1)
  5223. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5224. (remove-text-properties (match-beginning 0) (match-end 0)
  5225. '(display t invisible t intangible t))
  5226. ;; Handle short captions.
  5227. (save-excursion
  5228. (beginning-of-line)
  5229. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5230. (add-text-properties (line-beginning-position) (match-end 1)
  5231. '(font-lock-fontified t face org-meta-line))
  5232. (add-text-properties (match-end 0) (line-end-position)
  5233. '(font-lock-fontified t face org-block))
  5234. t)
  5235. ((member dc3 '(" " ""))
  5236. (org-remove-flyspell-overlays-in beg (match-end 0))
  5237. (add-text-properties
  5238. beg (match-end 0)
  5239. '(font-lock-fontified t face font-lock-comment-face)))
  5240. (t ;; just any other in-buffer setting, but not indented
  5241. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5242. (remove-text-properties (match-beginning 0) (match-end 0)
  5243. '(display t invisible t intangible t))
  5244. (add-text-properties beg (match-end 0)
  5245. '(font-lock-fontified t face org-meta-line))
  5246. t))))))
  5247. (defun org-fontify-drawers (limit)
  5248. "Fontify drawers."
  5249. (when (re-search-forward org-drawer-regexp limit t)
  5250. (add-text-properties
  5251. (match-beginning 0) (match-end 0)
  5252. '(font-lock-fontified t face org-special-keyword))
  5253. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5254. t))
  5255. (defun org-fontify-macros (limit)
  5256. "Fontify macros."
  5257. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5258. (let ((begin (match-beginning 0))
  5259. (opening-end (match-beginning 1)))
  5260. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5261. (match-string 1))
  5262. (let ((end (match-end 1))
  5263. (closing-start (match-beginning 1)))
  5264. (add-text-properties
  5265. begin end
  5266. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5267. (org-remove-flyspell-overlays-in begin end)
  5268. (when org-hide-macro-markers
  5269. (add-text-properties begin opening-end '(invisible t))
  5270. (add-text-properties closing-start end '(invisible t)))
  5271. t)))))
  5272. (defun org-activate-footnote-links (limit)
  5273. "Add text properties for footnotes."
  5274. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5275. (when fn
  5276. (let* ((beg (nth 1 fn))
  5277. (end (nth 2 fn))
  5278. (label (car fn))
  5279. (referencep (/= (line-beginning-position) beg)))
  5280. (when (and referencep (nth 3 fn))
  5281. (save-excursion
  5282. (goto-char beg)
  5283. (search-forward (or label "fn:"))
  5284. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5285. (add-text-properties beg end
  5286. (list 'mouse-face 'highlight
  5287. 'keymap org-mouse-map
  5288. 'help-echo
  5289. (if referencep "Footnote reference"
  5290. "Footnote definition")
  5291. 'font-lock-fontified t
  5292. 'font-lock-multiline t
  5293. 'face 'org-footnote))))))
  5294. (defun org-activate-dates (limit)
  5295. "Add text properties for dates."
  5296. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5297. (not (equal (char-before (match-beginning 0)) 91)))
  5298. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5299. (add-text-properties (match-beginning 0) (match-end 0)
  5300. (list 'mouse-face 'highlight
  5301. 'keymap org-mouse-map))
  5302. (org-rear-nonsticky-at (match-end 0))
  5303. (when org-display-custom-times
  5304. ;; If it's a date range, activate custom time for second date.
  5305. (when (match-end 3)
  5306. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5307. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5308. t))
  5309. (defvar-local org-target-link-regexp nil
  5310. "Regular expression matching radio targets in plain text.")
  5311. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5312. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5313. border border border))
  5314. "Regular expression matching a link target.")
  5315. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5316. "Regular expression matching a radio target.")
  5317. (defconst org-any-target-regexp
  5318. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5319. "Regular expression matching any target.")
  5320. (defun org-activate-target-links (limit)
  5321. "Add text properties for target matches."
  5322. (when org-target-link-regexp
  5323. (let ((case-fold-search t))
  5324. (when (re-search-forward org-target-link-regexp limit t)
  5325. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5326. (add-text-properties (match-beginning 1) (match-end 1)
  5327. (list 'mouse-face 'highlight
  5328. 'keymap org-mouse-map
  5329. 'help-echo "Radio target link"
  5330. 'org-linked-text t))
  5331. (org-rear-nonsticky-at (match-end 1))
  5332. t))))
  5333. (defun org-update-radio-target-regexp ()
  5334. "Find all radio targets in this file and update the regular expression.
  5335. Also refresh fontification if needed."
  5336. (interactive)
  5337. (let ((old-regexp org-target-link-regexp)
  5338. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5339. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5340. (targets
  5341. (org-with-wide-buffer
  5342. (goto-char (point-min))
  5343. (let (rtn)
  5344. (while (re-search-forward org-radio-target-regexp nil t)
  5345. ;; Make sure point is really within the object.
  5346. (backward-char)
  5347. (let ((obj (org-element-context)))
  5348. (when (eq (org-element-type obj) 'radio-target)
  5349. (cl-pushnew (org-element-property :value obj) rtn
  5350. :test #'equal))))
  5351. rtn))))
  5352. (setq org-target-link-regexp
  5353. (and targets
  5354. (concat before-re
  5355. (mapconcat
  5356. (lambda (x)
  5357. (replace-regexp-in-string
  5358. " +" "\\s-+" (regexp-quote x) t t))
  5359. targets
  5360. "\\|")
  5361. after-re)))
  5362. (unless (equal old-regexp org-target-link-regexp)
  5363. ;; Clean-up cache.
  5364. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5365. ((not org-target-link-regexp) old-regexp)
  5366. (t
  5367. (concat before-re
  5368. (mapconcat
  5369. (lambda (re)
  5370. (substring re (length before-re)
  5371. (- (length after-re))))
  5372. (list old-regexp org-target-link-regexp)
  5373. "\\|")
  5374. after-re)))))
  5375. (org-with-wide-buffer
  5376. (goto-char (point-min))
  5377. (while (re-search-forward regexp nil t)
  5378. (org-element-cache-refresh (match-beginning 1)))))
  5379. ;; Re fontify buffer.
  5380. (when (memq 'radio org-highlight-links)
  5381. (org-restart-font-lock)))))
  5382. (defvar org-latex-and-related-regexp nil
  5383. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5384. (defun org-compute-latex-and-related-regexp ()
  5385. "Compute regular expression for LaTeX, entities and sub/superscript.
  5386. Result depends on variable `org-highlight-latex-and-related'."
  5387. (setq-local
  5388. org-latex-and-related-regexp
  5389. (let* ((re-sub
  5390. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5391. ((eq org-use-sub-superscripts '{})
  5392. (list org-match-substring-with-braces-regexp))
  5393. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5394. (re-latex
  5395. (when (memq 'latex org-highlight-latex-and-related)
  5396. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5397. (delq nil
  5398. (mapcar (lambda (x)
  5399. (and (member (car x) matchers) (nth 1 x)))
  5400. org-latex-regexps)))))
  5401. (re-entities
  5402. (when (memq 'entities org-highlight-latex-and-related)
  5403. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5404. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5405. (defun org-do-latex-and-related (limit)
  5406. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5407. LIMIT bounds the search for syntax to highlight. Stop at first
  5408. highlighted object, if any. Return t if some highlighting was
  5409. done, nil otherwise."
  5410. (when (org-string-nw-p org-latex-and-related-regexp)
  5411. (catch 'found
  5412. (while (re-search-forward org-latex-and-related-regexp limit t)
  5413. (unless
  5414. (cl-some
  5415. (lambda (f)
  5416. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5417. (save-excursion
  5418. (goto-char (1+ (match-beginning 0)))
  5419. (face-at-point nil t)))
  5420. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5421. '(?_ ?^))
  5422. 1
  5423. 0)))
  5424. (font-lock-prepend-text-property
  5425. (+ offset (match-beginning 0)) (match-end 0)
  5426. 'face 'org-latex-and-related)
  5427. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5428. '(font-lock-multiline t)))
  5429. (throw 'found t)))
  5430. nil)))
  5431. (defun org-restart-font-lock ()
  5432. "Restart `font-lock-mode', to force refontification."
  5433. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5434. (font-lock-mode -1)
  5435. (font-lock-mode 1)))
  5436. (defun org-activate-tags (limit)
  5437. (when (re-search-forward
  5438. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5439. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5440. (add-text-properties (match-beginning 1) (match-end 1)
  5441. (list 'mouse-face 'highlight
  5442. 'keymap org-mouse-map))
  5443. (org-rear-nonsticky-at (match-end 1))
  5444. t))
  5445. (defun org-outline-level ()
  5446. "Compute the outline level of the heading at point.
  5447. If this is called at a normal headline, the level is the number
  5448. of stars. Use `org-reduced-level' to remove the effect of
  5449. `org-odd-levels'. Unlike to `org-current-level', this function
  5450. takes into consideration inlinetasks."
  5451. (org-with-wide-buffer
  5452. (end-of-line)
  5453. (if (re-search-backward org-outline-regexp-bol nil t)
  5454. (1- (- (match-end 0) (match-beginning 0)))
  5455. 0)))
  5456. (defvar org-font-lock-keywords nil)
  5457. (defsubst org-re-property (property &optional literal allow-null value)
  5458. "Return a regexp matching a PROPERTY line.
  5459. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5460. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5461. non-nil, match properties even without a value.
  5462. Match group 3 is set to the value when it exists. If there is no
  5463. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5464. With optional argument VALUE, match only property lines with
  5465. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5466. unless LITERAL is non-nil."
  5467. (concat
  5468. "^\\(?4:[ \t]*\\)"
  5469. (format "\\(?1::\\(?2:%s\\):\\)"
  5470. (if literal property (regexp-quote property)))
  5471. (cond (value
  5472. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5473. (if literal value (regexp-quote value))))
  5474. (allow-null
  5475. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5476. (t
  5477. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5478. (defconst org-property-re
  5479. (org-re-property "\\S-+" 'literal t)
  5480. "Regular expression matching a property line.
  5481. There are four matching groups:
  5482. 1: :PROPKEY: including the leading and trailing colon,
  5483. 2: PROPKEY without the leading and trailing colon,
  5484. 3: PROPVAL without leading or trailing spaces,
  5485. 4: the indentation of the current line,
  5486. 5: trailing whitespace.")
  5487. (defvar org-font-lock-hook nil
  5488. "Functions to be called for special font lock stuff.")
  5489. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5490. (defvar org-font-lock-set-keywords-hook nil
  5491. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5492. This is called after `org-font-lock-extra-keywords' is defined, but before
  5493. it is installed to be used by font lock. This can be useful if something
  5494. needs to be inserted at a specific position in the font-lock sequence.")
  5495. (defun org-font-lock-hook (limit)
  5496. "Run `org-font-lock-hook' within LIMIT."
  5497. (run-hook-with-args 'org-font-lock-hook limit))
  5498. (defun org-set-font-lock-defaults ()
  5499. "Set font lock defaults for the current buffer."
  5500. (let* ((em org-fontify-emphasized-text)
  5501. (lk org-highlight-links)
  5502. (org-font-lock-extra-keywords
  5503. (list
  5504. ;; Call the hook
  5505. '(org-font-lock-hook)
  5506. ;; Headlines
  5507. `(,(if org-fontify-whole-heading-line
  5508. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5509. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5510. (1 (org-get-level-face 1))
  5511. (2 (org-get-level-face 2))
  5512. (3 (org-get-level-face 3)))
  5513. ;; Table lines
  5514. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5515. (1 'org-table t))
  5516. ;; Table internals
  5517. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5518. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5519. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5520. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5521. ;; Drawers
  5522. '(org-fontify-drawers)
  5523. ;; Properties
  5524. (list org-property-re
  5525. '(1 'org-special-keyword t)
  5526. '(3 'org-property-value t))
  5527. ;; Link related fontification.
  5528. '(org-activate-links)
  5529. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5530. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5531. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5532. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5533. ;; Targets.
  5534. (list org-any-target-regexp '(0 'org-target t))
  5535. ;; Diary sexps.
  5536. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5537. ;; Macro
  5538. '(org-fontify-macros)
  5539. ;; TODO keyword
  5540. (list (format org-heading-keyword-regexp-format
  5541. org-todo-regexp)
  5542. '(2 (org-get-todo-face 2) t))
  5543. ;; DONE
  5544. (if org-fontify-done-headline
  5545. (list (format org-heading-keyword-regexp-format
  5546. (concat
  5547. "\\(?:"
  5548. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5549. "\\)"))
  5550. '(2 'org-headline-done t))
  5551. nil)
  5552. ;; Priorities
  5553. '(org-font-lock-add-priority-faces)
  5554. ;; Tags
  5555. '(org-font-lock-add-tag-faces)
  5556. ;; Tags groups
  5557. (when (and org-group-tags org-tag-groups-alist)
  5558. (list (concat org-outline-regexp-bol ".+\\(:"
  5559. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5560. ":\\).*$")
  5561. '(1 'org-tag-group prepend)))
  5562. ;; Special keywords
  5563. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5564. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5565. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5566. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5567. ;; Emphasis
  5568. (when em '(org-do-emphasis-faces))
  5569. ;; Checkboxes
  5570. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5571. 1 'org-checkbox prepend)
  5572. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5573. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5574. (0 (org-get-checkbox-statistics-face) t)))
  5575. ;; Description list items
  5576. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5577. 1 'org-list-dt prepend)
  5578. ;; ARCHIVEd headings
  5579. (list (concat
  5580. org-outline-regexp-bol
  5581. "\\(.*:" org-archive-tag ":.*\\)")
  5582. '(1 'org-archived prepend))
  5583. ;; Specials
  5584. '(org-do-latex-and-related)
  5585. '(org-fontify-entities)
  5586. '(org-raise-scripts)
  5587. ;; Code
  5588. '(org-activate-code (1 'org-code t))
  5589. ;; COMMENT
  5590. (list (format
  5591. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5592. org-todo-regexp
  5593. org-comment-string)
  5594. '(9 'org-special-keyword t))
  5595. ;; Blocks and meta lines
  5596. '(org-fontify-meta-lines-and-blocks))))
  5597. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5598. (run-hooks 'org-font-lock-set-keywords-hook)
  5599. ;; Now set the full font-lock-keywords
  5600. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5601. (setq-local font-lock-defaults
  5602. '(org-font-lock-keywords t nil nil backward-paragraph))
  5603. (kill-local-variable 'font-lock-keywords)
  5604. nil))
  5605. (defun org-toggle-pretty-entities ()
  5606. "Toggle the composition display of entities as UTF8 characters."
  5607. (interactive)
  5608. (setq-local org-pretty-entities (not org-pretty-entities))
  5609. (org-restart-font-lock)
  5610. (if org-pretty-entities
  5611. (message "Entities are now displayed as UTF8 characters")
  5612. (save-restriction
  5613. (widen)
  5614. (decompose-region (point-min) (point-max))
  5615. (message "Entities are now displayed as plain text"))))
  5616. (defvar-local org-custom-properties-overlays nil
  5617. "List of overlays used for custom properties.")
  5618. (defun org-toggle-custom-properties-visibility ()
  5619. "Display or hide properties in `org-custom-properties'."
  5620. (interactive)
  5621. (if org-custom-properties-overlays
  5622. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5623. (setq org-custom-properties-overlays nil))
  5624. (when org-custom-properties
  5625. (org-with-wide-buffer
  5626. (goto-char (point-min))
  5627. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5628. (while (re-search-forward regexp nil t)
  5629. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5630. (when (and end (< (point) end))
  5631. ;; Hide first custom property in current drawer.
  5632. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5633. (overlay-put o 'invisible t)
  5634. (overlay-put o 'org-custom-property t)
  5635. (push o org-custom-properties-overlays))
  5636. ;; Hide additional custom properties in the same drawer.
  5637. (while (re-search-forward regexp end t)
  5638. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5639. (overlay-put o 'invisible t)
  5640. (overlay-put o 'org-custom-property t)
  5641. (push o org-custom-properties-overlays)))))
  5642. ;; Each entry is limited to a single property drawer.
  5643. (outline-next-heading)))))))
  5644. (defun org-fontify-entities (limit)
  5645. "Find an entity to fontify."
  5646. (let (ee)
  5647. (when org-pretty-entities
  5648. (catch 'match
  5649. ;; "\_ "-family is left out on purpose. Only the first one,
  5650. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5651. ;; confusing when adding a second white space character.
  5652. (while (re-search-forward
  5653. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5654. limit t)
  5655. (when (and (not (org-at-comment-p))
  5656. (setq ee (org-entity-get (match-string 1)))
  5657. (= (length (nth 6 ee)) 1))
  5658. (let* ((end (if (equal (match-string 2) "{}")
  5659. (match-end 2)
  5660. (match-end 1))))
  5661. (add-text-properties
  5662. (match-beginning 0) end
  5663. (list 'font-lock-fontified t))
  5664. (compose-region (match-beginning 0) end
  5665. (nth 6 ee) nil)
  5666. (backward-char 1)
  5667. (throw 'match t))))
  5668. nil))))
  5669. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5670. "Fontify string S like in Org mode."
  5671. (with-temp-buffer
  5672. (insert s)
  5673. (let ((org-odd-levels-only odd-levels))
  5674. (org-mode)
  5675. (org-font-lock-ensure)
  5676. (buffer-string))))
  5677. (defvar org-m nil)
  5678. (defvar org-l nil)
  5679. (defvar org-f nil)
  5680. (defun org-get-level-face (n)
  5681. "Get the right face for match N in font-lock matching of headlines."
  5682. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5683. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5684. (if org-cycle-level-faces
  5685. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5686. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5687. (cond
  5688. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5689. ((eq n 2) org-f)
  5690. (t (unless org-level-color-stars-only org-f))))
  5691. (defun org-face-from-face-or-color (context inherit face-or-color)
  5692. "Create a face list that inherits INHERIT, but sets the foreground color.
  5693. When FACE-OR-COLOR is not a string, just return it."
  5694. (if (stringp face-or-color)
  5695. (list :inherit inherit
  5696. (cdr (assoc context org-faces-easy-properties))
  5697. face-or-color)
  5698. face-or-color))
  5699. (defun org-get-todo-face (kwd)
  5700. "Get the right face for a TODO keyword KWD.
  5701. If KWD is a number, get the corresponding match group."
  5702. (when (numberp kwd) (setq kwd (match-string kwd)))
  5703. (or (org-face-from-face-or-color
  5704. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5705. (and (member kwd org-done-keywords) 'org-done)
  5706. 'org-todo))
  5707. (defun org-get-priority-face (priority)
  5708. "Get the right face for PRIORITY.
  5709. PRIORITY is a character."
  5710. (or (org-face-from-face-or-color
  5711. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5712. 'org-priority))
  5713. (defun org-get-tag-face (tag)
  5714. "Get the right face for TAG.
  5715. If TAG is a number, get the corresponding match group."
  5716. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5717. (or (org-face-from-face-or-color
  5718. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5719. 'org-tag)))
  5720. (defun org-font-lock-add-priority-faces (limit)
  5721. "Add the special priority faces."
  5722. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5723. (add-text-properties
  5724. (match-beginning 1) (match-end 1)
  5725. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5726. 'font-lock-fontified t))))
  5727. (defun org-font-lock-add-tag-faces (limit)
  5728. "Add the special tag faces."
  5729. (when (and org-tag-faces org-tags-special-faces-re)
  5730. (while (re-search-forward org-tags-special-faces-re limit t)
  5731. (add-text-properties (match-beginning 1) (match-end 1)
  5732. (list 'face (org-get-tag-face 1)
  5733. 'font-lock-fontified t))
  5734. (backward-char 1))))
  5735. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5736. "Remove fontification and activation overlays from links."
  5737. (font-lock-default-unfontify-region beg end)
  5738. (let* ((buffer-undo-list t)
  5739. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5740. (inhibit-modification-hooks t)
  5741. deactivate-mark buffer-file-name buffer-file-truename)
  5742. (decompose-region beg end)
  5743. (remove-text-properties beg end
  5744. '(mouse-face t keymap t org-linked-text t
  5745. invisible t intangible t
  5746. org-emphasis t))
  5747. (org-remove-font-lock-display-properties beg end)))
  5748. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5749. ((raise 0.3) (height 0.7))
  5750. ((raise -0.5))
  5751. ((raise 0.5)))
  5752. "Display properties for showing superscripts and subscripts.")
  5753. (defun org-remove-font-lock-display-properties (beg end)
  5754. "Remove specific display properties that have been added by font lock.
  5755. The will remove the raise properties that are used to show superscripts
  5756. and subscripts."
  5757. (let (next prop)
  5758. (while (< beg end)
  5759. (setq next (next-single-property-change beg 'display nil end)
  5760. prop (get-text-property beg 'display))
  5761. (when (member prop org-script-display)
  5762. (put-text-property beg next 'display nil))
  5763. (setq beg next))))
  5764. (defun org-raise-scripts (limit)
  5765. "Add raise properties to sub/superscripts."
  5766. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5767. (re-search-forward
  5768. (if (eq org-use-sub-superscripts t)
  5769. org-match-substring-regexp
  5770. org-match-substring-with-braces-regexp)
  5771. limit t))
  5772. (let* ((pos (point)) table-p comment-p
  5773. (mpos (match-beginning 3))
  5774. (emph-p (get-text-property mpos 'org-emphasis))
  5775. (link-p (get-text-property mpos 'mouse-face))
  5776. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5777. (goto-char (point-at-bol))
  5778. (setq table-p (looking-at-p org-table-dataline-regexp)
  5779. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5780. (goto-char pos)
  5781. ;; Handle a_b^c
  5782. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5783. (unless (or comment-p emph-p link-p keyw-p)
  5784. (put-text-property (match-beginning 3) (match-end 0)
  5785. 'display
  5786. (if (equal (char-after (match-beginning 2)) ?^)
  5787. (nth (if table-p 3 1) org-script-display)
  5788. (nth (if table-p 2 0) org-script-display)))
  5789. (add-text-properties (match-beginning 2) (match-end 2)
  5790. (list 'invisible t))
  5791. (when (and (eq (char-after (match-beginning 3)) ?{)
  5792. (eq (char-before (match-end 3)) ?}))
  5793. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5794. (list 'invisible t))
  5795. (add-text-properties (1- (match-end 3)) (match-end 3)
  5796. (list 'invisible t))))
  5797. t)))
  5798. (defun org-remove-empty-overlays-at (pos)
  5799. "Remove outline overlays that do not contain non-white stuff."
  5800. (dolist (o (overlays-at pos))
  5801. (and (eq 'outline (overlay-get o 'invisible))
  5802. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5803. (overlay-end o))))
  5804. (delete-overlay o))))
  5805. (defun org-show-empty-lines-in-parent ()
  5806. "Move to the parent and re-show empty lines before visible headlines."
  5807. (save-excursion
  5808. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5809. (org-cycle-show-empty-lines context))))
  5810. (defun org-files-list ()
  5811. "Return `org-agenda-files' list, plus all open Org files.
  5812. This is useful for operations that need to scan all of a user's
  5813. open and agenda-wise Org files."
  5814. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5815. (dolist (buf (buffer-list))
  5816. (with-current-buffer buf
  5817. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5818. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5819. :test #'equal))))
  5820. files))
  5821. (defsubst org-entry-beginning-position ()
  5822. "Return the beginning position of the current entry."
  5823. (save-excursion (org-back-to-heading t) (point)))
  5824. (defsubst org-entry-end-position ()
  5825. "Return the end position of the current entry."
  5826. (save-excursion (outline-next-heading) (point)))
  5827. (defun org-subtree-end-visible-p ()
  5828. "Is the end of the current subtree visible?"
  5829. (pos-visible-in-window-p
  5830. (save-excursion (org-end-of-subtree t) (point))))
  5831. (defun org-first-headline-recenter ()
  5832. "Move cursor to the first headline and recenter the headline."
  5833. (let ((window (get-buffer-window)))
  5834. (when window
  5835. (goto-char (point-min))
  5836. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5837. (set-window-start window (line-beginning-position))))))
  5838. ;;; Visibility (headlines, blocks, drawers)
  5839. ;;;; Headlines visibility
  5840. (defun org-show-entry ()
  5841. "Show the body directly following this heading.
  5842. Show the heading too, if it is currently invisible."
  5843. (interactive)
  5844. (save-excursion
  5845. (ignore-errors
  5846. (org-back-to-heading t)
  5847. (org-flag-region
  5848. (line-end-position 0)
  5849. (save-excursion
  5850. (if (re-search-forward
  5851. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5852. (match-beginning 1)
  5853. (point-max)))
  5854. nil
  5855. 'outline))))
  5856. (defun org-show-children (&optional level)
  5857. "Show all direct subheadings of this heading.
  5858. Prefix arg LEVEL is how many levels below the current level
  5859. should be shown. Default is enough to cause the following
  5860. heading to appear."
  5861. (interactive "p")
  5862. (save-excursion
  5863. (org-back-to-heading t)
  5864. (let* ((current-level (funcall outline-level))
  5865. (max-level (org-get-valid-level
  5866. current-level
  5867. (if level (prefix-numeric-value level) 1)))
  5868. (end (save-excursion (org-end-of-subtree t t)))
  5869. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5870. (past-first-child nil)
  5871. ;; Make sure to skip inlinetasks.
  5872. (re (format regexp-fmt
  5873. current-level
  5874. (cond
  5875. ((not (featurep 'org-inlinetask)) "")
  5876. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5877. 3))
  5878. (t (1- org-inlinetask-min-level))))))
  5879. ;; Display parent heading.
  5880. (org-flag-heading nil)
  5881. (forward-line)
  5882. ;; Display children. First child may be deeper than expected
  5883. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5884. ;; MAX-LEVEL accordingly.
  5885. (while (re-search-forward re end t)
  5886. (unless past-first-child
  5887. (setq re (format regexp-fmt
  5888. current-level
  5889. (max (funcall outline-level) max-level)))
  5890. (setq past-first-child t))
  5891. (org-flag-heading nil)))))
  5892. (defun org-show-subtree ()
  5893. "Show everything after this heading at deeper levels."
  5894. (interactive)
  5895. (org-flag-region
  5896. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5897. ;;;; Blocks visibility
  5898. (defun org-hide-block-toggle-maybe ()
  5899. "Toggle visibility of block at point.
  5900. Unlike to `org-hide-block-toggle', this function does not throw
  5901. an error. Return a non-nil value when toggling is successful."
  5902. (interactive)
  5903. (ignore-errors (org-hide-block-toggle)))
  5904. (defun org-hide-block-toggle (&optional force)
  5905. "Toggle the visibility of the current block.
  5906. When optional argument FORCE is `off', make block visible. If it
  5907. is non-nil, hide it unconditionally. Throw an error when not at
  5908. a block. Return a non-nil value when toggling is successful."
  5909. (interactive)
  5910. (let ((element (org-element-at-point)))
  5911. (unless (memq (org-element-type element)
  5912. '(center-block comment-block dynamic-block example-block
  5913. export-block quote-block special-block
  5914. src-block verse-block))
  5915. (user-error "Not at a block"))
  5916. (let* ((post (org-element-property :post-affiliated element))
  5917. (start (save-excursion
  5918. (goto-char post)
  5919. (line-end-position)))
  5920. (end (save-excursion
  5921. (goto-char (org-element-property :end element))
  5922. (skip-chars-backward " \t\n")
  5923. (line-end-position))))
  5924. ;; Do nothing when not before or at the block opening line or at
  5925. ;; the block closing line.
  5926. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5927. (cond ((eq force 'off)
  5928. (org-flag-region start end nil 'org-hide-block))
  5929. (force
  5930. (org-flag-region start end t 'org-hide-block))
  5931. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5932. (org-flag-region start end nil 'org-hide-block))
  5933. (t
  5934. (org-flag-region start end t 'org-hide-block)))
  5935. ;; When the block is hidden away, make sure point is left in
  5936. ;; a visible part of the buffer.
  5937. (when (invisible-p (max (1- (point)) (point-min)))
  5938. (goto-char post))
  5939. ;; Signal success.
  5940. t))))
  5941. (defun org-hide-block-toggle-all ()
  5942. "Toggle the visibility of all blocks in the current buffer."
  5943. (org-block-map 'org-hide-block-toggle))
  5944. (defun org-hide-block-all ()
  5945. "Fold all blocks in the current buffer."
  5946. (interactive)
  5947. (org-show-all '(blocks))
  5948. (org-block-map 'org-hide-block-toggle-maybe))
  5949. ;;;; Drawers visibility
  5950. (defun org-cycle-hide-drawers (state &optional exceptions)
  5951. "Re-hide all drawers after a visibility state change.
  5952. STATE should be one of the symbols listed in the docstring of
  5953. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5954. a list of strings specifying which drawers should not be hidden."
  5955. (when (and (derived-mode-p 'org-mode)
  5956. (not (memq state '(overview folded contents))))
  5957. (save-excursion
  5958. (let* ((globalp (eq state 'all))
  5959. (beg (if globalp (point-min) (point)))
  5960. (end (if globalp (point-max)
  5961. (if (eq state 'children)
  5962. (save-excursion (outline-next-heading) (point))
  5963. (org-end-of-subtree t)))))
  5964. (goto-char beg)
  5965. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5966. (unless (member-ignore-case (match-string 1) exceptions)
  5967. (let ((drawer (org-element-at-point)))
  5968. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5969. (org-flag-drawer t drawer)
  5970. ;; Make sure to skip drawer entirely or we might flag
  5971. ;; it another time when matching its ending line with
  5972. ;; `org-drawer-regexp'.
  5973. (goto-char (org-element-property :end drawer))))))))))
  5974. (defun org-flag-drawer (flag &optional element)
  5975. "When FLAG is non-nil, hide the drawer we are at.
  5976. Otherwise make it visible. When optional argument ELEMENT is
  5977. a parsed drawer, as returned by `org-element-at-point', hide or
  5978. show that drawer instead."
  5979. (let ((drawer (or element
  5980. (and (save-excursion
  5981. (beginning-of-line)
  5982. (looking-at-p org-drawer-regexp))
  5983. (org-element-at-point)))))
  5984. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5985. (let ((post (org-element-property :post-affiliated drawer)))
  5986. (org-flag-region
  5987. (save-excursion (goto-char post) (line-end-position))
  5988. (save-excursion (goto-char (org-element-property :end drawer))
  5989. (skip-chars-backward " \t\n")
  5990. (line-end-position))
  5991. flag 'org-hide-drawer)
  5992. ;; When the drawer is hidden away, make sure point lies in
  5993. ;; a visible part of the buffer.
  5994. (when (invisible-p (max (1- (point)) (point-min)))
  5995. (goto-char post))))))
  5996. ;;;; Visibility cycling
  5997. (defvar-local org-cycle-global-status nil)
  5998. (put 'org-cycle-global-status 'org-state t)
  5999. (defvar-local org-cycle-subtree-status nil)
  6000. (put 'org-cycle-subtree-status 'org-state t)
  6001. (defun org-show-all (&optional types)
  6002. "Show all contents in the visible part of the buffer.
  6003. By default, the function expands headings, blocks and drawers.
  6004. When optional argument TYPE is a list of symbols among `blocks',
  6005. `drawers' and `headings', to only expand one specific type."
  6006. (dolist (type (or types '(blocks drawers headings)))
  6007. (org-flag-region (point-min) (point-max) nil
  6008. (pcase type
  6009. (`blocks 'org-hide-block)
  6010. (`drawers 'org-hide-drawer)
  6011. (`headings 'outline)
  6012. (_ (error "Invalid type: %S" type))))))
  6013. ;;;###autoload
  6014. (defun org-cycle (&optional arg)
  6015. "TAB-action and visibility cycling for Org mode.
  6016. This is the command invoked in Org mode by the `TAB' key. Its main
  6017. purpose is outline visibility cycling, but it also invokes other actions
  6018. in special contexts.
  6019. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6020. the entire
  6021. buffer through 3 states (global cycling)
  6022. 1. OVERVIEW: Show only top-level headlines.
  6023. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6024. 3. SHOW ALL: Show everything.
  6025. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6026. switch to the startup visibility,
  6027. determined by the variable `org-startup-folded', and by any VISIBILITY
  6028. properties in the buffer.
  6029. With a `\\[universal-argument] \\[universal-argument] \
  6030. \\[universal-argument]' prefix argument, show the entire buffer, including
  6031. any drawers.
  6032. When inside a table, re-align the table and move to the next field.
  6033. When point is at the beginning of a headline, rotate the subtree started
  6034. by this line through 3 different states (local cycling)
  6035. 1. FOLDED: Only the main headline is shown.
  6036. 2. CHILDREN: The main headline and the direct children are shown.
  6037. From this state, you can move to one of the children
  6038. and zoom in further.
  6039. 3. SUBTREE: Show the entire subtree, including body text.
  6040. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6041. When point is at the beginning of an empty headline and the variable
  6042. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6043. of the headline by demoting and promoting it to likely levels. This
  6044. speeds up creation document structure by pressing `TAB' once or several
  6045. times right after creating a new headline.
  6046. When there is a numeric prefix, go up to a heading with level ARG, do
  6047. a `show-subtree' and return to the previous cursor position. If ARG
  6048. is negative, go up that many levels.
  6049. When point is not at the beginning of a headline, execute the global
  6050. binding for `TAB', which is re-indenting the line. See the option
  6051. `org-cycle-emulate-tab' for details.
  6052. As a special case, if point is at the beginning of the buffer and there is
  6053. no headline in line 1, this function will act as if called with prefix arg
  6054. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6055. prefix arg, but only
  6056. if the variable `org-cycle-global-at-bob' is t."
  6057. (interactive "P")
  6058. (org-load-modules-maybe)
  6059. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6060. (and org-cycle-level-after-item/entry-creation
  6061. (or (org-cycle-level)
  6062. (org-cycle-item-indentation))))
  6063. (let* ((limit-level
  6064. (or org-cycle-max-level
  6065. (and (boundp 'org-inlinetask-min-level)
  6066. org-inlinetask-min-level
  6067. (1- org-inlinetask-min-level))))
  6068. (nstars (and limit-level
  6069. (if org-odd-levels-only
  6070. (and limit-level (1- (* limit-level 2)))
  6071. limit-level)))
  6072. (org-outline-regexp
  6073. (if (not (derived-mode-p 'org-mode))
  6074. outline-regexp
  6075. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6076. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6077. (not (looking-at org-outline-regexp))))
  6078. (org-cycle-hook
  6079. (if bob-special
  6080. (delq 'org-optimize-window-after-visibility-change
  6081. (copy-sequence org-cycle-hook))
  6082. org-cycle-hook))
  6083. (pos (point)))
  6084. (cond
  6085. ((equal arg '(16))
  6086. (setq last-command 'dummy)
  6087. (org-set-startup-visibility)
  6088. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6089. ((equal arg '(64))
  6090. (org-show-all)
  6091. (org-unlogged-message "Entire buffer visible, including drawers"))
  6092. ((equal arg '(4)) (org-cycle-internal-global))
  6093. ;; Try hiding block at point.
  6094. ((org-hide-block-toggle-maybe))
  6095. ;; Try cdlatex TAB completion
  6096. ((org-try-cdlatex-tab))
  6097. ;; Table: enter it or move to the next field.
  6098. ((org-at-table-p 'any)
  6099. (if (org-at-table.el-p)
  6100. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6101. Use `\\[org-edit-special]' to edit table.el tables"))
  6102. (if arg (org-table-edit-field t)
  6103. (org-table-justify-field-maybe)
  6104. (call-interactively 'org-table-next-field))))
  6105. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6106. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6107. (bob-special (org-cycle-internal-global))
  6108. ;; Drawers: delegate to `org-flag-drawer'.
  6109. ((save-excursion
  6110. (beginning-of-line 1)
  6111. (looking-at org-drawer-regexp))
  6112. (org-flag-drawer ; toggle block visibility
  6113. (not (get-char-property (match-end 0) 'invisible))))
  6114. ;; Show-subtree, ARG levels up from here.
  6115. ((integerp arg)
  6116. (save-excursion
  6117. (org-back-to-heading)
  6118. (outline-up-heading (if (< arg 0) (- arg)
  6119. (- (funcall outline-level) arg)))
  6120. (org-show-subtree)))
  6121. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6122. ((and (featurep 'org-inlinetask)
  6123. (org-inlinetask-at-task-p)
  6124. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6125. (org-inlinetask-toggle-visibility))
  6126. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6127. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6128. (save-excursion (move-beginning-of-line 1)
  6129. (looking-at org-outline-regexp)))
  6130. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6131. (org-cycle-internal-local))
  6132. ;; From there: TAB emulation and template completion.
  6133. (buffer-read-only (org-back-to-heading))
  6134. ((run-hook-with-args-until-success
  6135. 'org-tab-after-check-for-cycling-hook))
  6136. ((run-hook-with-args-until-success
  6137. 'org-tab-before-tab-emulation-hook))
  6138. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6139. (or (not (bolp))
  6140. (not (looking-at org-outline-regexp))))
  6141. (call-interactively (global-key-binding "\t")))
  6142. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6143. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6144. (or (and (eq org-cycle-emulate-tab 'white)
  6145. (= (match-end 0) (point-at-eol)))
  6146. (and (eq org-cycle-emulate-tab 'whitestart)
  6147. (>= (match-end 0) pos))))
  6148. t
  6149. (eq org-cycle-emulate-tab t))
  6150. (call-interactively (global-key-binding "\t")))
  6151. (t (save-excursion
  6152. (org-back-to-heading)
  6153. (org-cycle)))))))
  6154. (defun org-cycle-internal-global ()
  6155. "Do the global cycling action."
  6156. ;; Hack to avoid display of messages for .org attachments in Gnus
  6157. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6158. (cond
  6159. ((and (eq last-command this-command)
  6160. (eq org-cycle-global-status 'overview))
  6161. ;; We just created the overview - now do table of contents
  6162. ;; This can be slow in very large buffers, so indicate action
  6163. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6164. (unless ga (org-unlogged-message "CONTENTS..."))
  6165. (org-content)
  6166. (unless ga (org-unlogged-message "CONTENTS...done"))
  6167. (setq org-cycle-global-status 'contents)
  6168. (run-hook-with-args 'org-cycle-hook 'contents))
  6169. ((and (eq last-command this-command)
  6170. (eq org-cycle-global-status 'contents))
  6171. ;; We just showed the table of contents - now show everything
  6172. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6173. (org-show-all '(headings blocks))
  6174. (unless ga (org-unlogged-message "SHOW ALL"))
  6175. (setq org-cycle-global-status 'all)
  6176. (run-hook-with-args 'org-cycle-hook 'all))
  6177. (t
  6178. ;; Default action: go to overview
  6179. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6180. (org-overview)
  6181. (unless ga (org-unlogged-message "OVERVIEW"))
  6182. (setq org-cycle-global-status 'overview)
  6183. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6184. (defvar org-called-with-limited-levels nil
  6185. "Non-nil when `org-with-limited-levels' is currently active.")
  6186. (defun org-cycle-internal-local ()
  6187. "Do the local cycling action."
  6188. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6189. ;; First, determine end of headline (EOH), end of subtree or item
  6190. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6191. (save-excursion
  6192. (if (org-at-item-p)
  6193. (progn
  6194. (beginning-of-line)
  6195. (setq struct (org-list-struct))
  6196. (setq eoh (point-at-eol))
  6197. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6198. (setq has-children (org-list-has-child-p (point) struct)))
  6199. (org-back-to-heading)
  6200. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6201. (setq eos (save-excursion (org-end-of-subtree t t)
  6202. (when (bolp) (backward-char)) (point)))
  6203. (setq has-children
  6204. (or (save-excursion
  6205. (let ((level (funcall outline-level)))
  6206. (outline-next-heading)
  6207. (and (org-at-heading-p t)
  6208. (> (funcall outline-level) level))))
  6209. (save-excursion
  6210. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6211. ;; Determine end invisible part of buffer (EOL)
  6212. (beginning-of-line 2)
  6213. (while (and (not (eobp)) ;This is like `next-line'.
  6214. (get-char-property (1- (point)) 'invisible))
  6215. (goto-char (next-single-char-property-change (point) 'invisible))
  6216. (and (eolp) (beginning-of-line 2)))
  6217. (setq eol (point)))
  6218. ;; Find out what to do next and set `this-command'
  6219. (cond
  6220. ((= eos eoh)
  6221. ;; Nothing is hidden behind this heading
  6222. (unless (org-before-first-heading-p)
  6223. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6224. (org-unlogged-message "EMPTY ENTRY")
  6225. (setq org-cycle-subtree-status nil)
  6226. (save-excursion
  6227. (goto-char eos)
  6228. (outline-next-heading)
  6229. (when (org-invisible-p) (org-flag-heading nil))))
  6230. ((and (or (>= eol eos)
  6231. (not (string-match "\\S-" (buffer-substring eol eos))))
  6232. (or has-children
  6233. (not (setq children-skipped
  6234. org-cycle-skip-children-state-if-no-children))))
  6235. ;; Entire subtree is hidden in one line: children view
  6236. (unless (org-before-first-heading-p)
  6237. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6238. (if (org-at-item-p)
  6239. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6240. (org-show-entry)
  6241. (org-with-limited-levels (org-show-children))
  6242. (org-show-set-visibility 'canonical)
  6243. ;; Fold every list in subtree to top-level items.
  6244. (when (eq org-cycle-include-plain-lists 'integrate)
  6245. (save-excursion
  6246. (org-back-to-heading)
  6247. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6248. (beginning-of-line 1)
  6249. (let* ((struct (org-list-struct))
  6250. (prevs (org-list-prevs-alist struct))
  6251. (end (org-list-get-bottom-point struct)))
  6252. (dolist (e (org-list-get-all-items (point) struct prevs))
  6253. (org-list-set-item-visibility e struct 'folded))
  6254. (goto-char (if (< end eos) end eos)))))))
  6255. (org-unlogged-message "CHILDREN")
  6256. (save-excursion
  6257. (goto-char eos)
  6258. (outline-next-heading)
  6259. (when (org-invisible-p) (org-flag-heading nil)))
  6260. (setq org-cycle-subtree-status 'children)
  6261. (unless (org-before-first-heading-p)
  6262. (run-hook-with-args 'org-cycle-hook 'children)))
  6263. ((or children-skipped
  6264. (and (eq last-command this-command)
  6265. (eq org-cycle-subtree-status 'children)))
  6266. ;; We just showed the children, or no children are there,
  6267. ;; now show everything.
  6268. (unless (org-before-first-heading-p)
  6269. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6270. (org-flag-region eoh eos nil 'outline)
  6271. (org-unlogged-message
  6272. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6273. (setq org-cycle-subtree-status 'subtree)
  6274. (unless (org-before-first-heading-p)
  6275. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6276. (t
  6277. ;; Default action: hide the subtree.
  6278. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6279. (org-flag-region eoh eos t 'outline)
  6280. (org-unlogged-message "FOLDED")
  6281. (setq org-cycle-subtree-status 'folded)
  6282. (unless (org-before-first-heading-p)
  6283. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6284. ;;;###autoload
  6285. (defun org-global-cycle (&optional arg)
  6286. "Cycle the global visibility. For details see `org-cycle'.
  6287. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6288. With a numeric prefix, show all headlines up to that level."
  6289. (interactive "P")
  6290. (let ((org-cycle-include-plain-lists
  6291. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6292. (cond
  6293. ((integerp arg)
  6294. (org-show-all '(headings blocks))
  6295. (outline-hide-sublevels arg)
  6296. (setq org-cycle-global-status 'contents))
  6297. ((equal arg '(4))
  6298. (org-set-startup-visibility)
  6299. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6300. (t
  6301. (org-cycle '(4))))))
  6302. (defun org-set-startup-visibility ()
  6303. "Set the visibility required by startup options and properties."
  6304. (cond
  6305. ((eq org-startup-folded t)
  6306. (org-overview))
  6307. ((eq org-startup-folded 'content)
  6308. (org-content))
  6309. ((or (eq org-startup-folded 'showeverything)
  6310. (eq org-startup-folded nil))
  6311. (org-show-all)))
  6312. (unless (eq org-startup-folded 'showeverything)
  6313. (when org-hide-block-startup (org-hide-block-all))
  6314. (org-set-visibility-according-to-property)
  6315. (org-cycle-hide-archived-subtrees 'all)
  6316. (org-cycle-hide-drawers 'all)
  6317. (org-cycle-show-empty-lines t)))
  6318. (defun org-set-visibility-according-to-property ()
  6319. "Switch subtree visibilities according to :VISIBILITY: property."
  6320. (interactive)
  6321. (org-with-wide-buffer
  6322. (goto-char (point-min))
  6323. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6324. (if (not (org-at-property-p)) (outline-next-heading)
  6325. (let ((state (match-string 3)))
  6326. (save-excursion
  6327. (org-back-to-heading t)
  6328. (outline-hide-subtree)
  6329. (org-reveal)
  6330. (cond
  6331. ((equal state "folded")
  6332. (outline-hide-subtree))
  6333. ((equal state "children")
  6334. (org-show-hidden-entry)
  6335. (org-show-children))
  6336. ((equal state "content")
  6337. (save-excursion
  6338. (save-restriction
  6339. (org-narrow-to-subtree)
  6340. (org-content))))
  6341. ((member state '("all" "showall"))
  6342. (outline-show-subtree)))))))))
  6343. (defun org-overview ()
  6344. "Switch to overview mode, showing only top-level headlines.
  6345. This shows all headlines with a level equal or greater than the level
  6346. of the first headline in the buffer. This is important, because if the
  6347. first headline is not level one, then (hide-sublevels 1) gives confusing
  6348. results."
  6349. (interactive)
  6350. (save-excursion
  6351. (let ((level
  6352. (save-excursion
  6353. (goto-char (point-min))
  6354. (when (re-search-forward org-outline-regexp-bol nil t)
  6355. (goto-char (match-beginning 0))
  6356. (funcall outline-level)))))
  6357. (and level (outline-hide-sublevels level)))))
  6358. (defun org-content (&optional arg)
  6359. "Show all headlines in the buffer, like a table of contents.
  6360. With numerical argument N, show content up to level N."
  6361. (interactive "P")
  6362. (org-overview)
  6363. (save-excursion
  6364. ;; Visit all headings and show their offspring
  6365. (and (integerp arg) (org-overview))
  6366. (goto-char (point-max))
  6367. (catch 'exit
  6368. (while (and (progn (condition-case nil
  6369. (outline-previous-visible-heading 1)
  6370. (error (goto-char (point-min))))
  6371. t)
  6372. (looking-at org-outline-regexp))
  6373. (if (integerp arg)
  6374. (org-show-children (1- arg))
  6375. (outline-show-branches))
  6376. (when (bobp) (throw 'exit nil))))))
  6377. (defun org-optimize-window-after-visibility-change (state)
  6378. "Adjust the window after a change in outline visibility.
  6379. This function is the default value of the hook `org-cycle-hook'."
  6380. (when (get-buffer-window (current-buffer))
  6381. (cond
  6382. ((eq state 'content) nil)
  6383. ((eq state 'all) nil)
  6384. ((eq state 'folded) nil)
  6385. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6386. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6387. (defun org-clean-visibility-after-subtree-move ()
  6388. "Fix visibility issues after moving a subtree."
  6389. ;; First, find a reasonable region to look at:
  6390. ;; Start two siblings above, end three below
  6391. (let* ((beg (save-excursion
  6392. (and (org-get-last-sibling)
  6393. (org-get-last-sibling))
  6394. (point)))
  6395. (end (save-excursion
  6396. (and (org-get-next-sibling)
  6397. (org-get-next-sibling)
  6398. (org-get-next-sibling))
  6399. (if (org-at-heading-p)
  6400. (point-at-eol)
  6401. (point))))
  6402. (level (looking-at "\\*+"))
  6403. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6404. (save-excursion
  6405. (save-restriction
  6406. (narrow-to-region beg end)
  6407. (when re
  6408. ;; Properly fold already folded siblings
  6409. (goto-char (point-min))
  6410. (while (re-search-forward re nil t)
  6411. (when (and (not (org-invisible-p))
  6412. (org-invisible-p (line-end-position)))
  6413. (outline-hide-entry))))
  6414. (org-cycle-hide-drawers 'all)
  6415. (org-cycle-show-empty-lines 'overview)))))
  6416. (defun org-cycle-show-empty-lines (state)
  6417. "Show empty lines above all visible headlines.
  6418. The region to be covered depends on STATE when called through
  6419. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6420. entire buffer covered. Note that an empty line is only shown if there
  6421. are at least `org-cycle-separator-lines' empty lines before the headline."
  6422. (when (/= org-cycle-separator-lines 0)
  6423. (save-excursion
  6424. (let* ((n (abs org-cycle-separator-lines))
  6425. (re (cond
  6426. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6427. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6428. (t (let ((ns (number-to-string (- n 2))))
  6429. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6430. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6431. beg end)
  6432. (cond
  6433. ((memq state '(overview contents t))
  6434. (setq beg (point-min) end (point-max)))
  6435. ((memq state '(children folded))
  6436. (setq beg (point)
  6437. end (progn (org-end-of-subtree t t)
  6438. (line-beginning-position 2)))))
  6439. (when beg
  6440. (goto-char beg)
  6441. (while (re-search-forward re end t)
  6442. (unless (get-char-property (match-end 1) 'invisible)
  6443. (let ((e (match-end 1))
  6444. (b (if (>= org-cycle-separator-lines 0)
  6445. (match-beginning 1)
  6446. (save-excursion
  6447. (goto-char (match-beginning 0))
  6448. (skip-chars-backward " \t\n")
  6449. (line-end-position)))))
  6450. (org-flag-region b e nil 'outline))))))))
  6451. ;; Never hide empty lines at the end of the file.
  6452. (save-excursion
  6453. (goto-char (point-max))
  6454. (outline-previous-heading)
  6455. (outline-end-of-heading)
  6456. (when (and (looking-at "[ \t\n]+")
  6457. (= (match-end 0) (point-max)))
  6458. (org-flag-region (point) (match-end 0) nil 'outline))))
  6459. ;;;; Reveal point location
  6460. (defun org-show-context (&optional key)
  6461. "Make sure point and context are visible.
  6462. Optional argument KEY, when non-nil, is a symbol. See
  6463. `org-show-context-detail' for allowed values and how much is to
  6464. be shown."
  6465. (org-show-set-visibility
  6466. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6467. ((cdr (assq key org-show-context-detail)))
  6468. (t (cdr (assq 'default org-show-context-detail))))))
  6469. (defun org-show-set-visibility (detail)
  6470. "Set visibility around point according to DETAIL.
  6471. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6472. `tree', `canonical' or t. See `org-show-context-detail' for more
  6473. information."
  6474. ;; Show current heading and possibly its entry, following headline
  6475. ;; or all children.
  6476. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6477. (org-flag-heading nil)
  6478. (org-show-entry)
  6479. ;; If point is hidden within a drawer or a block, make sure to
  6480. ;; expose it.
  6481. (dolist (o (overlays-at (point)))
  6482. (when (memq (overlay-get o 'invisible)
  6483. '(org-hide-block org-hide-drawer outline))
  6484. (delete-overlay o)))
  6485. (unless (org-before-first-heading-p)
  6486. (org-with-limited-levels
  6487. (cl-case detail
  6488. ((tree canonical t) (org-show-children))
  6489. ((nil minimal ancestors))
  6490. (t (save-excursion
  6491. (outline-next-heading)
  6492. (org-flag-heading nil)))))))
  6493. ;; Show all siblings.
  6494. (when (eq detail 'lineage) (org-show-siblings))
  6495. ;; Show ancestors, possibly with their children.
  6496. (when (memq detail '(ancestors lineage tree canonical t))
  6497. (save-excursion
  6498. (while (org-up-heading-safe)
  6499. (org-flag-heading nil)
  6500. (when (memq detail '(canonical t)) (org-show-entry))
  6501. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6502. (defvar org-reveal-start-hook nil
  6503. "Hook run before revealing a location.")
  6504. (defun org-reveal (&optional siblings)
  6505. "Show current entry, hierarchy above it, and the following headline.
  6506. This can be used to show a consistent set of context around
  6507. locations exposed with `org-show-context'.
  6508. With optional argument SIBLINGS, on each level of the hierarchy all
  6509. siblings are shown. This repairs the tree structure to what it would
  6510. look like when opened with hierarchical calls to `org-cycle'.
  6511. With a \\[universal-argument] \\[universal-argument] prefix, \
  6512. go to the parent and show the entire tree."
  6513. (interactive "P")
  6514. (run-hooks 'org-reveal-start-hook)
  6515. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6516. ((equal siblings '(16))
  6517. (save-excursion
  6518. (when (org-up-heading-safe)
  6519. (org-show-subtree)
  6520. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6521. (t (org-show-set-visibility 'lineage))))
  6522. ;;; Indirect buffer display of subtrees
  6523. (defvar org-indirect-dedicated-frame nil
  6524. "This is the frame being used for indirect tree display.")
  6525. (defvar org-last-indirect-buffer nil)
  6526. (defun org-tree-to-indirect-buffer (&optional arg)
  6527. "Create indirect buffer and narrow it to current subtree.
  6528. With a numerical prefix ARG, go up to this level and then take that tree.
  6529. If ARG is negative, go up that many levels.
  6530. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6531. indirect buffer previously made with this command, to avoid proliferation of
  6532. indirect buffers. However, when you call the command with a \
  6533. `\\[universal-argument]' prefix, or
  6534. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6535. so that you can work with several indirect buffers at the same time. If
  6536. `org-indirect-buffer-display' is `dedicated-frame', the \
  6537. `\\[universal-argument]' prefix also
  6538. requests that a new frame be made for the new buffer, so that the dedicated
  6539. frame is not changed."
  6540. (interactive "P")
  6541. (let ((cbuf (current-buffer))
  6542. (cwin (selected-window))
  6543. (pos (point))
  6544. beg end level heading ibuf)
  6545. (save-excursion
  6546. (org-back-to-heading t)
  6547. (when (numberp arg)
  6548. (setq level (org-outline-level))
  6549. (when (< arg 0) (setq arg (+ level arg)))
  6550. (while (> (setq level (org-outline-level)) arg)
  6551. (org-up-heading-safe)))
  6552. (setq beg (point)
  6553. heading (org-get-heading 'no-tags))
  6554. (org-end-of-subtree t t)
  6555. (when (org-at-heading-p) (backward-char 1))
  6556. (setq end (point)))
  6557. (when (and (buffer-live-p org-last-indirect-buffer)
  6558. (not (eq org-indirect-buffer-display 'new-frame))
  6559. (not arg))
  6560. (kill-buffer org-last-indirect-buffer))
  6561. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6562. org-last-indirect-buffer ibuf)
  6563. (cond
  6564. ((or (eq org-indirect-buffer-display 'new-frame)
  6565. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6566. (select-frame (make-frame))
  6567. (delete-other-windows)
  6568. (pop-to-buffer-same-window ibuf)
  6569. (org-set-frame-title heading))
  6570. ((eq org-indirect-buffer-display 'dedicated-frame)
  6571. (raise-frame
  6572. (select-frame (or (and org-indirect-dedicated-frame
  6573. (frame-live-p org-indirect-dedicated-frame)
  6574. org-indirect-dedicated-frame)
  6575. (setq org-indirect-dedicated-frame (make-frame)))))
  6576. (delete-other-windows)
  6577. (pop-to-buffer-same-window ibuf)
  6578. (org-set-frame-title (concat "Indirect: " heading)))
  6579. ((eq org-indirect-buffer-display 'current-window)
  6580. (pop-to-buffer-same-window ibuf))
  6581. ((eq org-indirect-buffer-display 'other-window)
  6582. (pop-to-buffer ibuf))
  6583. (t (error "Invalid value")))
  6584. (narrow-to-region beg end)
  6585. (org-show-all '(headings blocks))
  6586. (goto-char pos)
  6587. (run-hook-with-args 'org-cycle-hook 'all)
  6588. (and (window-live-p cwin) (select-window cwin))))
  6589. (defun org-get-indirect-buffer (&optional buffer heading)
  6590. (setq buffer (or buffer (current-buffer)))
  6591. (let ((n 1) (base (buffer-name buffer)) bname)
  6592. (while (buffer-live-p
  6593. (get-buffer
  6594. (setq bname
  6595. (concat base "-"
  6596. (if heading (concat heading "-" (number-to-string n))
  6597. (number-to-string n))))))
  6598. (setq n (1+ n)))
  6599. (condition-case nil
  6600. (make-indirect-buffer buffer bname 'clone)
  6601. (error (make-indirect-buffer buffer bname)))))
  6602. (defun org-set-frame-title (title)
  6603. "Set the title of the current frame to the string TITLE."
  6604. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6605. ;;;; Structure editing
  6606. ;;; Inserting headlines
  6607. (defun org--line-empty-p (n)
  6608. "Is the Nth next line empty?
  6609. Counts the current line as N = 1 and the previous line as N = 0;
  6610. see `beginning-of-line'."
  6611. (save-excursion
  6612. (and (not (bobp))
  6613. (or (beginning-of-line n) t)
  6614. (save-match-data
  6615. (looking-at "[ \t]*$")))))
  6616. (defun org-previous-line-empty-p ()
  6617. "Is the previous line a blank line?
  6618. When NEXT is non-nil, check the next line instead."
  6619. (org--line-empty-p 0))
  6620. (defun org-next-line-empty-p ()
  6621. "Is the previous line a blank line?
  6622. When NEXT is non-nil, check the next line instead."
  6623. (org--line-empty-p 2))
  6624. (defun org--blank-before-heading-p (&optional parent)
  6625. "Non-nil when an empty line should precede a new heading here.
  6626. When optional argument PARENT is non-nil, consider parent
  6627. headline instead of current one."
  6628. (pcase (assq 'heading org-blank-before-new-entry)
  6629. (`(heading . auto)
  6630. (save-excursion
  6631. (org-with-limited-levels
  6632. (unless (and (org-before-first-heading-p)
  6633. (not (outline-next-heading)))
  6634. (org-back-to-heading t)
  6635. (when parent (org-up-heading-safe))
  6636. (cond ((not (bobp))
  6637. (org-previous-line-empty-p))
  6638. ((outline-next-heading)
  6639. (org-previous-line-empty-p))
  6640. ;; Ignore trailing spaces on last buffer line.
  6641. ((progn (skip-chars-backward " \t") (bolp))
  6642. (org-previous-line-empty-p))
  6643. (t nil))))))
  6644. (`(heading . ,value) value)
  6645. (_ nil)))
  6646. (defun org-insert-heading (&optional arg invisible-ok top)
  6647. "Insert a new heading or an item with the same depth at point.
  6648. If point is at the beginning of a heading, insert a new heading
  6649. or a new headline above the current one. When at the beginning
  6650. of a regular line of text, turn it into a heading.
  6651. If point is in the middle of a line, split it and create a new
  6652. headline with the text in the current line after point (see
  6653. `org-M-RET-may-split-line' on how to modify this behavior). As
  6654. a special case, on a headline, splitting can only happen on the
  6655. title itself. E.g., this excludes breaking stars or tags.
  6656. With a `\\[universal-argument]' prefix, set \
  6657. `org-insert-heading-respect-content' to
  6658. a non-nil value for the duration of the command. This forces the
  6659. insertion of a heading after the current subtree, independently
  6660. on the location of point.
  6661. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6662. insert the heading at the end of the tree
  6663. above the current heading. For example, if point is within a
  6664. 2nd-level heading, then it will insert a 2nd-level heading at
  6665. the end of the 1st-level parent subtree.
  6666. When INVISIBLE-OK is set, stop at invisible headlines when going
  6667. back. This is important for non-interactive uses of the
  6668. command.
  6669. When optional argument TOP is non-nil, insert a level 1 heading,
  6670. unconditionally."
  6671. (interactive "P")
  6672. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6673. (level (org-current-level))
  6674. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6675. (cond
  6676. ((or org-insert-heading-respect-content
  6677. (member arg '((4) (16)))
  6678. (and (not invisible-ok)
  6679. (invisible-p (max (1- (point)) (point-min)))))
  6680. ;; Position point at the location of insertion.
  6681. (if (not level) ;before first headline
  6682. (org-with-limited-levels (outline-next-heading))
  6683. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6684. ;; is nil.
  6685. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6686. (cond ((equal arg '(16))
  6687. (org-up-heading-safe)
  6688. (org-end-of-subtree t t))
  6689. (t
  6690. (org-end-of-subtree t t))))
  6691. (unless (bolp) (insert "\n")) ;ensure final newline
  6692. (unless (and blank? (org-previous-line-empty-p))
  6693. (org-N-empty-lines-before-current (if blank? 1 0)))
  6694. (insert stars " \n")
  6695. (forward-char -1))
  6696. ;; At a headline...
  6697. ((org-at-heading-p)
  6698. (cond ((bolp)
  6699. (when blank? (save-excursion (insert "\n")))
  6700. (save-excursion (insert stars " \n"))
  6701. (unless (and blank? (org-previous-line-empty-p))
  6702. (org-N-empty-lines-before-current (if blank? 1 0)))
  6703. (end-of-line))
  6704. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6705. (org-match-line org-complex-heading-regexp)
  6706. (org-pos-in-match-range (point) 4))
  6707. ;; Grab the text that should moved to the new headline.
  6708. ;; Preserve tags.
  6709. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6710. (if (looking-at "[ \t]*$") (replace-match "")
  6711. (org-set-tags nil t))
  6712. (end-of-line)
  6713. (when blank? (insert "\n"))
  6714. (insert "\n" stars " ")
  6715. (when (org-string-nw-p split) (insert split))
  6716. (when (eobp) (save-excursion (insert "\n")))))
  6717. (t
  6718. (end-of-line)
  6719. (when blank? (insert "\n"))
  6720. (insert "\n" stars " ")
  6721. (when (eobp) (save-excursion (insert "\n"))))))
  6722. ;; On regular text, turn line into a headline or split, if
  6723. ;; appropriate.
  6724. ((bolp)
  6725. (insert stars " ")
  6726. (unless (and blank? (org-previous-line-empty-p))
  6727. (org-N-empty-lines-before-current (if blank? 1 0))))
  6728. (t
  6729. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6730. (end-of-line))
  6731. (insert "\n" stars " ")
  6732. (unless (and blank? (org-previous-line-empty-p))
  6733. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6734. (run-hooks 'org-insert-heading-hook))
  6735. (defun org-N-empty-lines-before-current (n)
  6736. "Make the number of empty lines before current exactly N.
  6737. So this will delete or add empty lines."
  6738. (let ((column (current-column)))
  6739. (beginning-of-line)
  6740. (unless (bobp)
  6741. (let ((start (save-excursion
  6742. (skip-chars-backward " \r\t\n")
  6743. (line-end-position))))
  6744. (delete-region start (line-end-position 0))))
  6745. (insert (make-string n ?\n))
  6746. (move-to-column column)))
  6747. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6748. "Return the heading of the current entry, without the stars.
  6749. When NO-TAGS is non-nil, don't include tags.
  6750. When NO-TODO is non-nil, don't include TODO keywords.
  6751. When NO-PRIORITY is non-nil, don't include priority cookie.
  6752. When NO-COMMENT is non-nil, don't include COMMENT string."
  6753. (save-excursion
  6754. (org-back-to-heading t)
  6755. (let ((case-fold-search nil))
  6756. (looking-at org-complex-heading-regexp)
  6757. (let ((todo (and (not no-todo) (match-string 2)))
  6758. (priority (and (not no-priority) (match-string 3)))
  6759. (headline (pcase (match-string 4)
  6760. (`nil "")
  6761. ((and (guard no-comment) h)
  6762. (replace-regexp-in-string
  6763. (eval-when-compile
  6764. (format "\\`%s[ \t]+" org-comment-string))
  6765. "" h))
  6766. (h h)))
  6767. (tags (and (not no-tags) (match-string 5))))
  6768. (mapconcat #'identity
  6769. (delq nil (list todo priority headline tags))
  6770. " ")))))
  6771. (defun org-heading-components ()
  6772. "Return the components of the current heading.
  6773. This is a list with the following elements:
  6774. - the level as an integer
  6775. - the reduced level, different if `org-odd-levels-only' is set.
  6776. - the TODO keyword, or nil
  6777. - the priority character, like ?A, or nil if no priority is given
  6778. - the headline text itself, or the tags string if no headline text
  6779. - the tags string, or nil."
  6780. (save-excursion
  6781. (org-back-to-heading t)
  6782. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6783. (list (length (match-string 1))
  6784. (org-reduced-level (length (match-string 1)))
  6785. (match-string-no-properties 2)
  6786. (and (match-end 3) (aref (match-string 3) 2))
  6787. (match-string-no-properties 4)
  6788. (match-string-no-properties 5)))))
  6789. (defun org-get-entry ()
  6790. "Get the entry text, after heading, entire subtree."
  6791. (save-excursion
  6792. (org-back-to-heading t)
  6793. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6794. (defun org-edit-headline (&optional heading)
  6795. "Edit the current headline.
  6796. Set it to HEADING when provided."
  6797. (interactive)
  6798. (org-with-wide-buffer
  6799. (org-back-to-heading t)
  6800. (let ((case-fold-search nil))
  6801. (when (looking-at org-complex-heading-regexp)
  6802. (let* ((old (match-string-no-properties 4))
  6803. (new (save-match-data
  6804. (org-trim (or heading (read-string "Edit: " old))))))
  6805. (unless (equal old new)
  6806. (if old (replace-match new t t nil 4)
  6807. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6808. (insert " " new))
  6809. (org-set-tags nil t)
  6810. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6811. (defun org-insert-heading-after-current ()
  6812. "Insert a new heading with same level as current, after current subtree."
  6813. (interactive)
  6814. (org-back-to-heading)
  6815. (org-insert-heading)
  6816. (org-move-subtree-down)
  6817. (end-of-line 1))
  6818. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6819. "Insert heading with `org-insert-heading-respect-content' set to t."
  6820. (interactive)
  6821. (org-insert-heading '(4) invisible-ok))
  6822. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6823. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6824. (interactive)
  6825. (org-insert-todo-heading force-state '(4)))
  6826. (defun org-insert-todo-heading (arg &optional force-heading)
  6827. "Insert a new heading with the same level and TODO state as current heading.
  6828. If the heading has no TODO state, or if the state is DONE, use
  6829. the first state (TODO by default). Also with one prefix arg,
  6830. force first state. With two prefix args, force inserting at the
  6831. end of the parent subtree.
  6832. When called at a plain list item, insert a new item with an
  6833. unchecked check box."
  6834. (interactive "P")
  6835. (when (or force-heading (not (org-insert-item 'checkbox)))
  6836. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6837. force-heading))
  6838. (save-excursion
  6839. (org-forward-heading-same-level -1)
  6840. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6841. (let* ((new-mark-x
  6842. (if (or (equal arg '(4))
  6843. (not (match-beginning 2))
  6844. (member (match-string 2) org-done-keywords))
  6845. (car org-todo-keywords-1)
  6846. (match-string 2)))
  6847. (new-mark
  6848. (or
  6849. (run-hook-with-args-until-success
  6850. 'org-todo-get-default-hook new-mark-x nil)
  6851. new-mark-x)))
  6852. (beginning-of-line 1)
  6853. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6854. (if org-treat-insert-todo-heading-as-state-change
  6855. (org-todo new-mark)
  6856. (insert new-mark " "))))
  6857. (when org-provide-todo-statistics
  6858. (org-update-parent-todo-statistics))))
  6859. (defun org-insert-subheading (arg)
  6860. "Insert a new subheading and demote it.
  6861. Works for outline headings and for plain lists alike."
  6862. (interactive "P")
  6863. (org-insert-heading arg)
  6864. (cond
  6865. ((org-at-heading-p) (org-do-demote))
  6866. ((org-at-item-p) (org-indent-item))))
  6867. (defun org-insert-todo-subheading (arg)
  6868. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6869. Works for outline headings and for plain lists alike."
  6870. (interactive "P")
  6871. (org-insert-todo-heading arg)
  6872. (cond
  6873. ((org-at-heading-p) (org-do-demote))
  6874. ((org-at-item-p) (org-indent-item))))
  6875. ;;; Promotion and Demotion
  6876. (defvar org-after-demote-entry-hook nil
  6877. "Hook run after an entry has been demoted.
  6878. The cursor will be at the beginning of the entry.
  6879. When a subtree is being demoted, the hook will be called for each node.")
  6880. (defvar org-after-promote-entry-hook nil
  6881. "Hook run after an entry has been promoted.
  6882. The cursor will be at the beginning of the entry.
  6883. When a subtree is being promoted, the hook will be called for each node.")
  6884. (defun org-promote-subtree ()
  6885. "Promote the entire subtree.
  6886. See also `org-promote'."
  6887. (interactive)
  6888. (save-excursion
  6889. (org-with-limited-levels (org-map-tree 'org-promote)))
  6890. (org-fix-position-after-promote))
  6891. (defun org-demote-subtree ()
  6892. "Demote the entire subtree.
  6893. See `org-demote' and `org-promote'."
  6894. (interactive)
  6895. (save-excursion
  6896. (org-with-limited-levels (org-map-tree 'org-demote)))
  6897. (org-fix-position-after-promote))
  6898. (defun org-do-promote ()
  6899. "Promote the current heading higher up the tree.
  6900. If the region is active in `transient-mark-mode', promote all
  6901. headings in the region."
  6902. (interactive)
  6903. (save-excursion
  6904. (if (org-region-active-p)
  6905. (org-map-region 'org-promote (region-beginning) (region-end))
  6906. (org-promote)))
  6907. (org-fix-position-after-promote))
  6908. (defun org-do-demote ()
  6909. "Demote the current heading lower down the tree.
  6910. If the region is active in `transient-mark-mode', demote all
  6911. headings in the region."
  6912. (interactive)
  6913. (save-excursion
  6914. (if (org-region-active-p)
  6915. (org-map-region 'org-demote (region-beginning) (region-end))
  6916. (org-demote)))
  6917. (org-fix-position-after-promote))
  6918. (defun org-fix-position-after-promote ()
  6919. "Fix cursor position and indentation after demoting/promoting."
  6920. (let ((pos (point)))
  6921. (when (save-excursion
  6922. (beginning-of-line)
  6923. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6924. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6925. (cond ((eobp) (insert " "))
  6926. ((eolp) (insert " "))
  6927. ((equal (char-after) ?\s) (forward-char 1))))))
  6928. (defun org-current-level ()
  6929. "Return the level of the current entry, or nil if before the first headline.
  6930. The level is the number of stars at the beginning of the
  6931. headline. Use `org-reduced-level' to remove the effect of
  6932. `org-odd-levels'. Unlike to `org-outline-level', this function
  6933. ignores inlinetasks."
  6934. (let ((level (org-with-limited-levels (org-outline-level))))
  6935. (and (> level 0) level)))
  6936. (defun org-get-previous-line-level ()
  6937. "Return the outline depth of the last headline before the current line.
  6938. Returns 0 for the first headline in the buffer, and nil if before the
  6939. first headline."
  6940. (and (org-current-level)
  6941. (or (and (/= (line-beginning-position) (point-min))
  6942. (save-excursion (beginning-of-line 0) (org-current-level)))
  6943. 0)))
  6944. (defun org-reduced-level (l)
  6945. "Compute the effective level of a heading.
  6946. This takes into account the setting of `org-odd-levels-only'."
  6947. (cond
  6948. ((zerop l) 0)
  6949. (org-odd-levels-only (1+ (floor (/ l 2))))
  6950. (t l)))
  6951. (defun org-level-increment ()
  6952. "Return the number of stars that will be added or removed at a
  6953. time to headlines when structure editing, based on the value of
  6954. `org-odd-levels-only'."
  6955. (if org-odd-levels-only 2 1))
  6956. (defun org-get-valid-level (level &optional change)
  6957. "Rectify a level change under the influence of `org-odd-levels-only'.
  6958. LEVEL is a current level, CHANGE is by how much the level should
  6959. be modified. Even if CHANGE is nil, LEVEL may be returned
  6960. modified because even level numbers will become the next higher
  6961. odd number. Returns values greater than 0."
  6962. (if org-odd-levels-only
  6963. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6964. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6965. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6966. (max 1 (+ level (or change 0)))))
  6967. (defun org-promote ()
  6968. "Promote the current heading higher up the tree."
  6969. (org-with-wide-buffer
  6970. (org-back-to-heading t)
  6971. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6972. after-change-functions))
  6973. (level (save-match-data (funcall outline-level)))
  6974. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6975. (diff (abs (- level (length up-head) -1))))
  6976. (cond
  6977. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6978. (replace-match "# " nil t))
  6979. ((= level 1)
  6980. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6981. (t (replace-match up-head nil t)))
  6982. (unless (= level 1)
  6983. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6984. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6985. (run-hooks 'org-after-promote-entry-hook))))
  6986. (defun org-demote ()
  6987. "Demote the current heading lower down the tree."
  6988. (org-with-wide-buffer
  6989. (org-back-to-heading t)
  6990. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6991. after-change-functions))
  6992. (level (save-match-data (funcall outline-level)))
  6993. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6994. (diff (abs (- level (length down-head) -1))))
  6995. (replace-match down-head nil t)
  6996. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6997. (when org-adapt-indentation (org-fixup-indentation diff))
  6998. (run-hooks 'org-after-demote-entry-hook))))
  6999. (defun org-cycle-level ()
  7000. "Cycle the level of an empty headline through possible states.
  7001. This goes first to child, then to parent, level, then up the hierarchy.
  7002. After top level, it switches back to sibling level."
  7003. (interactive)
  7004. (let ((org-adapt-indentation nil))
  7005. (when (org-point-at-end-of-empty-headline)
  7006. (setq this-command 'org-cycle-level) ; Only needed for caching
  7007. (let ((cur-level (org-current-level))
  7008. (prev-level (org-get-previous-line-level)))
  7009. (cond
  7010. ;; If first headline in file, promote to top-level.
  7011. ((= prev-level 0)
  7012. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7013. do (org-do-promote)))
  7014. ;; If same level as prev, demote one.
  7015. ((= prev-level cur-level)
  7016. (org-do-demote))
  7017. ;; If parent is top-level, promote to top level if not already.
  7018. ((= prev-level 1)
  7019. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7020. do (org-do-promote)))
  7021. ;; If top-level, return to prev-level.
  7022. ((= cur-level 1)
  7023. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7024. do (org-do-demote)))
  7025. ;; If less than prev-level, promote one.
  7026. ((< cur-level prev-level)
  7027. (org-do-promote))
  7028. ;; If deeper than prev-level, promote until higher than
  7029. ;; prev-level.
  7030. ((> cur-level prev-level)
  7031. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7032. do (org-do-promote))))
  7033. t))))
  7034. (defun org-map-tree (fun)
  7035. "Call FUN for every heading underneath the current one."
  7036. (org-back-to-heading t)
  7037. (let ((level (funcall outline-level)))
  7038. (save-excursion
  7039. (funcall fun)
  7040. (while (and (progn
  7041. (outline-next-heading)
  7042. (> (funcall outline-level) level))
  7043. (not (eobp)))
  7044. (funcall fun)))))
  7045. (defun org-map-region (fun beg end)
  7046. "Call FUN for every heading between BEG and END."
  7047. (let ((org-ignore-region t))
  7048. (save-excursion
  7049. (setq end (copy-marker end))
  7050. (goto-char beg)
  7051. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7052. (< (point) end))
  7053. (funcall fun))
  7054. (while (and (progn
  7055. (outline-next-heading)
  7056. (< (point) end))
  7057. (not (eobp)))
  7058. (funcall fun)))))
  7059. (defun org-fixup-indentation (diff)
  7060. "Change the indentation in the current entry by DIFF.
  7061. DIFF is an integer. Indentation is done according to the
  7062. following rules:
  7063. - Planning information and property drawers are always indented
  7064. according to the new level of the headline;
  7065. - Footnote definitions and their contents are ignored;
  7066. - Inlinetasks' boundaries are not shifted;
  7067. - Empty lines are ignored;
  7068. - Other lines' indentation are shifted by DIFF columns, unless
  7069. it would introduce a structural change in the document, in
  7070. which case no shifting is done at all.
  7071. Assume point is at a heading or an inlinetask beginning."
  7072. (org-with-wide-buffer
  7073. (narrow-to-region (line-beginning-position)
  7074. (save-excursion
  7075. (if (org-with-limited-levels (org-at-heading-p))
  7076. (org-with-limited-levels (outline-next-heading))
  7077. (org-inlinetask-goto-end))
  7078. (point)))
  7079. (forward-line)
  7080. ;; Indent properly planning info and property drawer.
  7081. (when (looking-at-p org-planning-line-re)
  7082. (org-indent-line)
  7083. (forward-line))
  7084. (when (looking-at org-property-drawer-re)
  7085. (goto-char (match-end 0))
  7086. (forward-line)
  7087. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7088. (catch 'no-shift
  7089. (when (zerop diff) (throw 'no-shift nil))
  7090. ;; If DIFF is negative, first check if a shift is possible at all
  7091. ;; (e.g., it doesn't break structure). This can only happen if
  7092. ;; some contents are not properly indented.
  7093. (let ((case-fold-search t))
  7094. (when (< diff 0)
  7095. (let ((diff (- diff))
  7096. (forbidden-re (concat org-outline-regexp
  7097. "\\|"
  7098. (substring org-footnote-definition-re 1))))
  7099. (save-excursion
  7100. (while (not (eobp))
  7101. (cond
  7102. ((looking-at-p "[ \t]*$") (forward-line))
  7103. ((and (looking-at-p org-footnote-definition-re)
  7104. (let ((e (org-element-at-point)))
  7105. (and (eq (org-element-type e) 'footnote-definition)
  7106. (goto-char (org-element-property :end e))))))
  7107. ((looking-at-p org-outline-regexp) (forward-line))
  7108. ;; Give up if shifting would move before column 0 or
  7109. ;; if it would introduce a headline or a footnote
  7110. ;; definition.
  7111. (t
  7112. (skip-chars-forward " \t")
  7113. (let ((ind (current-column)))
  7114. (when (or (< ind diff)
  7115. (and (= ind diff) (looking-at-p forbidden-re)))
  7116. (throw 'no-shift nil)))
  7117. ;; Ignore contents of example blocks and source
  7118. ;; blocks if their indentation is meant to be
  7119. ;; preserved. Jump to block's closing line.
  7120. (beginning-of-line)
  7121. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7122. (let ((e (org-element-at-point)))
  7123. (and (memq (org-element-type e)
  7124. '(example-block src-block))
  7125. (or org-src-preserve-indentation
  7126. (org-element-property :preserve-indent e))
  7127. (goto-char (org-element-property :end e))
  7128. (progn (skip-chars-backward " \r\t\n")
  7129. (beginning-of-line)
  7130. t))))
  7131. (forward-line))))))))
  7132. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7133. ;; by DIFF. Also skip contents of source or example blocks
  7134. ;; when indentation is meant to be preserved.
  7135. (while (not (eobp))
  7136. (cond
  7137. ((and (looking-at-p org-footnote-definition-re)
  7138. (let ((e (org-element-at-point)))
  7139. (and (eq (org-element-type e) 'footnote-definition)
  7140. (goto-char (org-element-property :end e))))))
  7141. ((looking-at-p org-outline-regexp) (forward-line))
  7142. ((looking-at-p "[ \t]*$") (forward-line))
  7143. (t
  7144. (indent-line-to (+ (org-get-indentation) diff))
  7145. (beginning-of-line)
  7146. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7147. (let ((e (org-element-at-point)))
  7148. (and (memq (org-element-type e)
  7149. '(example-block src-block))
  7150. (or org-src-preserve-indentation
  7151. (org-element-property :preserve-indent e))
  7152. (goto-char (org-element-property :end e))
  7153. (progn (skip-chars-backward " \r\t\n")
  7154. (beginning-of-line)
  7155. t))))
  7156. (forward-line)))))))))
  7157. (defun org-convert-to-odd-levels ()
  7158. "Convert an Org file with all levels allowed to one with odd levels.
  7159. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7160. level 5 etc."
  7161. (interactive)
  7162. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7163. (let ((outline-level 'org-outline-level)
  7164. (org-odd-levels-only nil) n)
  7165. (save-excursion
  7166. (goto-char (point-min))
  7167. (while (re-search-forward "^\\*\\*+ " nil t)
  7168. (setq n (- (length (match-string 0)) 2))
  7169. (while (>= (setq n (1- n)) 0)
  7170. (org-demote))
  7171. (end-of-line 1))))))
  7172. (defun org-convert-to-oddeven-levels ()
  7173. "Convert an Org file with only odd levels to one with odd/even levels.
  7174. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7175. file contains a section with an even level, conversion would
  7176. destroy the structure of the file. An error is signaled in this
  7177. case."
  7178. (interactive)
  7179. (goto-char (point-min))
  7180. ;; First check if there are no even levels
  7181. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7182. (org-show-set-visibility 'canonical)
  7183. (error "Not all levels are odd in this file. Conversion not possible"))
  7184. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7185. (let ((outline-regexp org-outline-regexp)
  7186. (outline-level 'org-outline-level)
  7187. (org-odd-levels-only nil) n)
  7188. (save-excursion
  7189. (goto-char (point-min))
  7190. (while (re-search-forward "^\\*\\*+ " nil t)
  7191. (setq n (/ (1- (length (match-string 0))) 2))
  7192. (while (>= (setq n (1- n)) 0)
  7193. (org-promote))
  7194. (end-of-line 1))))))
  7195. (defun org-tr-level (n)
  7196. "Make N odd if required."
  7197. (if org-odd-levels-only (1+ (/ n 2)) n))
  7198. ;;; Vertical tree motion, cutting and pasting of subtrees
  7199. (defun org-move-subtree-up (&optional arg)
  7200. "Move the current subtree up past ARG headlines of the same level."
  7201. (interactive "p")
  7202. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7203. (defun org-move-subtree-down (&optional arg)
  7204. "Move the current subtree down past ARG headlines of the same level."
  7205. (interactive "p")
  7206. (setq arg (prefix-numeric-value arg))
  7207. (org-preserve-local-variables
  7208. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7209. 'org-get-last-sibling))
  7210. (ins-point (make-marker))
  7211. (cnt (abs arg))
  7212. (col (current-column))
  7213. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7214. ;; Select the tree
  7215. (org-back-to-heading)
  7216. (setq beg0 (point))
  7217. (save-excursion
  7218. (setq ne-beg (org-back-over-empty-lines))
  7219. (setq beg (point)))
  7220. (save-match-data
  7221. (save-excursion (outline-end-of-heading)
  7222. (setq folded (org-invisible-p)))
  7223. (progn (org-end-of-subtree nil t)
  7224. (unless (eobp) (backward-char))))
  7225. (outline-next-heading)
  7226. (setq ne-end (org-back-over-empty-lines))
  7227. (setq end (point))
  7228. (goto-char beg0)
  7229. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7230. ;; include less whitespace
  7231. (save-excursion
  7232. (goto-char beg)
  7233. (forward-line (- ne-beg ne-end))
  7234. (setq beg (point))))
  7235. ;; Find insertion point, with error handling
  7236. (while (> cnt 0)
  7237. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7238. (goto-char beg0)
  7239. (user-error "Cannot move past superior level or buffer limit"))
  7240. (setq cnt (1- cnt)))
  7241. (when (> arg 0)
  7242. ;; Moving forward - still need to move over subtree
  7243. (org-end-of-subtree t t)
  7244. (save-excursion
  7245. (org-back-over-empty-lines)
  7246. (or (bolp) (newline))))
  7247. (setq ne-ins (org-back-over-empty-lines))
  7248. (move-marker ins-point (point))
  7249. (setq txt (buffer-substring beg end))
  7250. (org-save-markers-in-region beg end)
  7251. (delete-region beg end)
  7252. (org-remove-empty-overlays-at beg)
  7253. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7254. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7255. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7256. (let ((bbb (point)))
  7257. (insert-before-markers txt)
  7258. (org-reinstall-markers-in-region bbb)
  7259. (move-marker ins-point bbb))
  7260. (or (bolp) (insert "\n"))
  7261. (setq ins-end (point))
  7262. (goto-char ins-point)
  7263. (org-skip-whitespace)
  7264. (when (and (< arg 0)
  7265. (org-first-sibling-p)
  7266. (> ne-ins ne-beg))
  7267. ;; Move whitespace back to beginning
  7268. (save-excursion
  7269. (goto-char ins-end)
  7270. (let ((kill-whole-line t))
  7271. (kill-line (- ne-ins ne-beg)) (point)))
  7272. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7273. (move-marker ins-point nil)
  7274. (if folded
  7275. (outline-hide-subtree)
  7276. (org-show-entry)
  7277. (org-show-children))
  7278. (org-clean-visibility-after-subtree-move)
  7279. ;; move back to the initial column we were at
  7280. (move-to-column col))))
  7281. (defvar org-subtree-clip ""
  7282. "Clipboard for cut and paste of subtrees.
  7283. This is actually only a copy of the kill, because we use the normal kill
  7284. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7285. (defvar org-subtree-clip-folded nil
  7286. "Was the last copied subtree folded?
  7287. This is used to fold the tree back after pasting.")
  7288. (defun org-cut-subtree (&optional n)
  7289. "Cut the current subtree into the clipboard.
  7290. With prefix arg N, cut this many sequential subtrees.
  7291. This is a short-hand for marking the subtree and then cutting it."
  7292. (interactive "p")
  7293. (org-copy-subtree n 'cut))
  7294. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7295. "Copy the current subtree into the clipboard.
  7296. With prefix arg N, copy this many sequential subtrees.
  7297. This is a short-hand for marking the subtree and then copying it.
  7298. If CUT is non-nil, actually cut the subtree.
  7299. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7300. of some markers in the region, even if CUT is non-nil. This is
  7301. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7302. (interactive "p")
  7303. (org-preserve-local-variables
  7304. (let (beg end folded (beg0 (point)))
  7305. (if (called-interactively-p 'any)
  7306. (org-back-to-heading nil) ; take what looks like a subtree
  7307. (org-back-to-heading t)) ; take what is really there
  7308. (setq beg (point))
  7309. (skip-chars-forward " \t\r\n")
  7310. (save-match-data
  7311. (if nosubtrees
  7312. (outline-next-heading)
  7313. (save-excursion (outline-end-of-heading)
  7314. (setq folded (org-invisible-p)))
  7315. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7316. (org-end-of-subtree t t)))
  7317. ;; Include the end of an inlinetask
  7318. (when (and (featurep 'org-inlinetask)
  7319. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7320. "END[ \t]*$")))
  7321. (end-of-line))
  7322. (setq end (point))
  7323. (goto-char beg0)
  7324. (when (> end beg)
  7325. (setq org-subtree-clip-folded folded)
  7326. (when (or cut force-store-markers)
  7327. (org-save-markers-in-region beg end))
  7328. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7329. (setq org-subtree-clip (current-kill 0))
  7330. (message "%s: Subtree(s) with %d characters"
  7331. (if cut "Cut" "Copied")
  7332. (length org-subtree-clip))))))
  7333. (defun org-paste-subtree (&optional level tree for-yank remove)
  7334. "Paste the clipboard as a subtree, with modification of headline level.
  7335. The entire subtree is promoted or demoted in order to match a new headline
  7336. level.
  7337. If the cursor is at the beginning of a headline, the same level as
  7338. that headline is used to paste the tree.
  7339. If not, the new level is derived from the *visible* headings
  7340. before and after the insertion point, and taken to be the inferior headline
  7341. level of the two. So if the previous visible heading is level 3 and the
  7342. next is level 4 (or vice versa), level 4 will be used for insertion.
  7343. This makes sure that the subtree remains an independent subtree and does
  7344. not swallow low level entries.
  7345. You can also force a different level, either by using a numeric prefix
  7346. argument, or by inserting the heading marker by hand. For example, if the
  7347. cursor is after \"*****\", then the tree will be shifted to level 5.
  7348. If optional TREE is given, use this text instead of the kill ring.
  7349. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7350. move back over whitespace before inserting, and move point to the end of
  7351. the inserted text when done.
  7352. When REMOVE is non-nil, remove the subtree from the clipboard."
  7353. (interactive "P")
  7354. (setq tree (or tree (and kill-ring (current-kill 0))))
  7355. (unless (org-kill-is-subtree-p tree)
  7356. (user-error
  7357. (substitute-command-keys
  7358. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7359. (org-with-limited-levels
  7360. (let* ((visp (not (org-invisible-p)))
  7361. (txt tree)
  7362. (old-level (if (string-match org-outline-regexp-bol txt)
  7363. (- (match-end 0) (match-beginning 0) 1)
  7364. -1))
  7365. (force-level
  7366. (cond
  7367. (level (prefix-numeric-value level))
  7368. ;; When point is right after the stars in an otherwise
  7369. ;; empty headline, use stars as the forced level.
  7370. ((and (looking-at-p "[ \t]*$")
  7371. (string-match-p "^\\*+ *"
  7372. (buffer-substring (line-beginning-position)
  7373. (point))))
  7374. (org-outline-level))
  7375. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7376. (previous-level
  7377. (save-excursion
  7378. (org-previous-visible-heading 1)
  7379. (if (org-at-heading-p) (org-outline-level) 1)))
  7380. (next-level
  7381. (save-excursion
  7382. (if (org-at-heading-p) (org-outline-level)
  7383. (org-next-visible-heading 1)
  7384. (if (org-at-heading-p) (org-outline-level) 1))))
  7385. (new-level (or force-level (max previous-level next-level)))
  7386. (shift (if (or (= old-level -1)
  7387. (= new-level -1)
  7388. (= old-level new-level))
  7389. 0
  7390. (- new-level old-level)))
  7391. (delta (if (> shift 0) -1 1))
  7392. (func (if (> shift 0) #'org-demote #'org-promote))
  7393. (org-odd-levels-only nil)
  7394. beg end newend)
  7395. ;; Remove the forced level indicator.
  7396. (when (and force-level (not level))
  7397. (delete-region (line-beginning-position) (point)))
  7398. ;; Paste before the next visible heading or at end of buffer,
  7399. ;; unless point is at the beginning of a headline.
  7400. (unless (and (bolp) (org-at-heading-p))
  7401. (org-next-visible-heading 1)
  7402. (unless (bolp) (insert "\n")))
  7403. (setq beg (point))
  7404. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7405. (insert-before-markers txt)
  7406. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7407. (setq newend (point))
  7408. (org-reinstall-markers-in-region beg)
  7409. (setq end (point))
  7410. (goto-char beg)
  7411. (skip-chars-forward " \t\n\r")
  7412. (setq beg (point))
  7413. (when (and (org-invisible-p) visp)
  7414. (save-excursion (outline-show-heading)))
  7415. ;; Shift if necessary.
  7416. (unless (= shift 0)
  7417. (save-restriction
  7418. (narrow-to-region beg end)
  7419. (while (not (= shift 0))
  7420. (org-map-region func (point-min) (point-max))
  7421. (setq shift (+ delta shift)))
  7422. (goto-char (point-min))
  7423. (setq newend (point-max))))
  7424. (when (or for-yank (called-interactively-p 'interactive))
  7425. (message "Clipboard pasted as level %d subtree" new-level))
  7426. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7427. kill-ring
  7428. (equal org-subtree-clip (current-kill 0))
  7429. org-subtree-clip-folded)
  7430. ;; The tree was folded before it was killed/copied
  7431. (outline-hide-subtree))
  7432. (when for-yank (goto-char newend))
  7433. (when remove (pop kill-ring)))))
  7434. (defun org-kill-is-subtree-p (&optional txt)
  7435. "Check if the current kill is an outline subtree, or a set of trees.
  7436. Returns nil if kill does not start with a headline, or if the first
  7437. headline level is not the largest headline level in the tree.
  7438. So this will actually accept several entries of equal levels as well,
  7439. which is OK for `org-paste-subtree'.
  7440. If optional TXT is given, check this string instead of the current kill."
  7441. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7442. (re (org-get-limited-outline-regexp))
  7443. (^re (concat "^" re))
  7444. (start-level (and kill
  7445. (string-match
  7446. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7447. kill)
  7448. (- (match-end 2) (match-beginning 2) 1)))
  7449. (start (1+ (or (match-beginning 2) -1))))
  7450. (if (not start-level)
  7451. (progn
  7452. nil) ;; does not even start with a heading
  7453. (catch 'exit
  7454. (while (setq start (string-match ^re kill (1+ start)))
  7455. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7456. (throw 'exit nil)))
  7457. t))))
  7458. (defvar org-markers-to-move nil
  7459. "Markers that should be moved with a cut-and-paste operation.
  7460. Those markers are stored together with their positions relative to
  7461. the start of the region.")
  7462. (defun org-save-markers-in-region (beg end)
  7463. "Check markers in region.
  7464. If these markers are between BEG and END, record their position relative
  7465. to BEG, so that after moving the block of text, we can put the markers back
  7466. into place.
  7467. This function gets called just before an entry or tree gets cut from the
  7468. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7469. called immediately, to move the markers with the entries."
  7470. (setq org-markers-to-move nil)
  7471. (when (featurep 'org-clock)
  7472. (org-clock-save-markers-for-cut-and-paste beg end))
  7473. (when (featurep 'org-agenda)
  7474. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7475. (defun org-check-and-save-marker (marker beg end)
  7476. "Check if MARKER is between BEG and END.
  7477. If yes, remember the marker and the distance to BEG."
  7478. (when (and (marker-buffer marker)
  7479. (equal (marker-buffer marker) (current-buffer))
  7480. (>= marker beg) (< marker end))
  7481. (push (cons marker (- marker beg)) org-markers-to-move)))
  7482. (defun org-reinstall-markers-in-region (beg)
  7483. "Move all remembered markers to their position relative to BEG."
  7484. (dolist (x org-markers-to-move)
  7485. (move-marker (car x) (+ beg (cdr x))))
  7486. (setq org-markers-to-move nil))
  7487. (defun org-narrow-to-subtree ()
  7488. "Narrow buffer to the current subtree."
  7489. (interactive)
  7490. (save-excursion
  7491. (save-match-data
  7492. (org-with-limited-levels
  7493. (narrow-to-region
  7494. (progn (org-back-to-heading t) (point))
  7495. (progn (org-end-of-subtree t t)
  7496. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7497. (point)))))))
  7498. (defun org-narrow-to-block ()
  7499. "Narrow buffer to the current block."
  7500. (interactive)
  7501. (let* ((case-fold-search t)
  7502. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7503. "^[ \t]*#\\+end_.*")))
  7504. (if blockp
  7505. (narrow-to-region (car blockp) (cdr blockp))
  7506. (user-error "Not in a block"))))
  7507. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7508. "Clone the task (subtree) at point N times.
  7509. The clones will be inserted as siblings.
  7510. In interactive use, the user will be prompted for the number of
  7511. clones to be produced. If the entry has a timestamp, the user
  7512. will also be prompted for a time shift, which may be a repeater
  7513. as used in time stamps, for example `+3d'. To disable this,
  7514. you can call the function with a universal prefix argument.
  7515. When a valid repeater is given and the entry contains any time
  7516. stamps, the clones will become a sequence in time, with time
  7517. stamps in the subtree shifted for each clone produced. If SHIFT
  7518. is nil or the empty string, time stamps will be left alone. The
  7519. ID property of the original subtree is removed.
  7520. In each clone, all the CLOCK entries will be removed. This
  7521. prevents Org from considering that the clocked times overlap.
  7522. If the original subtree did contain time stamps with a repeater,
  7523. the following will happen:
  7524. - the repeater will be removed in each clone
  7525. - an additional clone will be produced, with the current, unshifted
  7526. date(s) in the entry.
  7527. - the original entry will be placed *after* all the clones, with
  7528. repeater intact.
  7529. - the start days in the repeater in the original entry will be shifted
  7530. to past the last clone.
  7531. In this way you can spell out a number of instances of a repeating task,
  7532. and still retain the repeater to cover future instances of the task.
  7533. As described above, N+1 clones are produced when the original
  7534. subtree has a repeater. Setting N to 0, then, can be used to
  7535. remove the repeater from a subtree and create a shifted clone
  7536. with the original repeater."
  7537. (interactive "nNumber of clones to produce: ")
  7538. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7539. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7540. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7541. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7542. (shift
  7543. (or shift
  7544. (if (and (not (equal current-prefix-arg '(4)))
  7545. (save-excursion
  7546. (goto-char beg)
  7547. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7548. (read-from-minibuffer
  7549. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7550. ""))) ;No time shift
  7551. (doshift
  7552. (and (org-string-nw-p shift)
  7553. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7554. shift)
  7555. (user-error "Invalid shift specification %s" shift)))))
  7556. (goto-char end-of-tree)
  7557. (unless (bolp) (insert "\n"))
  7558. (let* ((end (point))
  7559. (template (buffer-substring beg end))
  7560. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7561. (shift-what (pcase (and doshift (match-string 2 shift))
  7562. (`nil nil)
  7563. ("d" 'day)
  7564. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7565. ("m" 'month)
  7566. ("y" 'year)
  7567. (_ (error "Unsupported time unit"))))
  7568. (nmin 1)
  7569. (nmax n)
  7570. (n-no-remove -1)
  7571. (idprop (org-entry-get nil "ID")))
  7572. (when (and doshift
  7573. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7574. template))
  7575. (delete-region beg end)
  7576. (setq end beg)
  7577. (setq nmin 0)
  7578. (setq nmax (1+ nmax))
  7579. (setq n-no-remove nmax))
  7580. (goto-char end)
  7581. (cl-loop for n from nmin to nmax do
  7582. (insert
  7583. ;; Prepare clone.
  7584. (with-temp-buffer
  7585. (insert template)
  7586. (org-mode)
  7587. (goto-char (point-min))
  7588. (org-show-subtree)
  7589. (and idprop (if org-clone-delete-id
  7590. (org-entry-delete nil "ID")
  7591. (org-id-get-create t)))
  7592. (unless (= n 0)
  7593. (while (re-search-forward org-clock-line-re nil t)
  7594. (delete-region (line-beginning-position)
  7595. (line-beginning-position 2)))
  7596. (goto-char (point-min))
  7597. (while (re-search-forward org-drawer-regexp nil t)
  7598. (org-remove-empty-drawer-at (point))))
  7599. (goto-char (point-min))
  7600. (when doshift
  7601. (while (re-search-forward org-ts-regexp-both nil t)
  7602. (org-timestamp-change (* n shift-n) shift-what))
  7603. (unless (= n n-no-remove)
  7604. (goto-char (point-min))
  7605. (while (re-search-forward org-ts-regexp nil t)
  7606. (save-excursion
  7607. (goto-char (match-beginning 0))
  7608. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7609. (delete-region (match-beginning 1) (match-end 1)))))))
  7610. (buffer-string)))))
  7611. (goto-char beg)))
  7612. ;;; Outline Sorting
  7613. (defun org-sort (&optional with-case)
  7614. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7615. Optional argument WITH-CASE means sort case-sensitively."
  7616. (interactive "P")
  7617. (org-call-with-arg
  7618. (cond ((org-at-table-p) #'org-table-sort-lines)
  7619. ((org-at-item-p) #'org-sort-list)
  7620. (t #'org-sort-entries))
  7621. with-case))
  7622. (defun org-sort-remove-invisible (s)
  7623. "Remove invisible part of links and emphasis markers from string S."
  7624. (remove-text-properties 0 (length s) org-rm-props s)
  7625. (replace-regexp-in-string
  7626. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7627. (replace-regexp-in-string
  7628. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7629. (org-link-display-format s)
  7630. t t) t t))
  7631. (defvar org-priority-regexp) ; defined later in the file
  7632. (defvar org-after-sorting-entries-or-items-hook nil
  7633. "Hook that is run after a bunch of entries or items have been sorted.
  7634. When children are sorted, the cursor is in the parent line when this
  7635. hook gets called. When a region or a plain list is sorted, the cursor
  7636. will be in the first entry of the sorted region/list.")
  7637. (defun org-sort-entries
  7638. (&optional with-case sorting-type getkey-func compare-func property
  7639. interactive?)
  7640. "Sort entries on a certain level of an outline tree.
  7641. If there is an active region, the entries in the region are sorted.
  7642. Else, if the cursor is before the first entry, sort the top-level items.
  7643. Else, the children of the entry at point are sorted.
  7644. Sorting can be alphabetically, numerically, by date/time as given by
  7645. a time stamp, by a property, by priority order, or by a custom function.
  7646. The command prompts for the sorting type unless it has been given to the
  7647. function through the SORTING-TYPE argument, which needs to be a character,
  7648. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7649. the precise meaning of each character:
  7650. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7651. c By creation time, which is assumed to be the first inactive time stamp
  7652. at the beginning of a line.
  7653. d By deadline date/time.
  7654. k By clocking time.
  7655. n Numerically, by converting the beginning of the entry/item to a number.
  7656. o By order of TODO keywords.
  7657. p By priority according to the cookie.
  7658. r By the value of a property.
  7659. s By scheduled date/time.
  7660. t By date/time, either the first active time stamp in the entry, or, if
  7661. none exist, by the first inactive one.
  7662. Capital letters will reverse the sort order.
  7663. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7664. called with point at the beginning of the record. It must return a
  7665. value that is compatible with COMPARE-FUNC, the function used to
  7666. compare entries.
  7667. Comparing entries ignores case by default. However, with an optional argument
  7668. WITH-CASE, the sorting considers case as well.
  7669. Sorting is done against the visible part of the headlines, it ignores hidden
  7670. links.
  7671. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7672. A non-nil value for INTERACTIVE? is used to signal that this
  7673. function is being called interactively."
  7674. (interactive (list current-prefix-arg nil nil nil nil t))
  7675. (let ((case-func (if with-case 'identity 'downcase))
  7676. start beg end stars re re2
  7677. txt what tmp)
  7678. ;; Find beginning and end of region to sort
  7679. (cond
  7680. ((org-region-active-p)
  7681. ;; we will sort the region
  7682. (setq end (region-end)
  7683. what "region")
  7684. (goto-char (region-beginning))
  7685. (unless (org-at-heading-p) (outline-next-heading))
  7686. (setq start (point)))
  7687. ((or (org-at-heading-p)
  7688. (ignore-errors (progn (org-back-to-heading) t)))
  7689. ;; we will sort the children of the current headline
  7690. (org-back-to-heading)
  7691. (setq start (point)
  7692. end (progn (org-end-of-subtree t t)
  7693. (or (bolp) (insert "\n"))
  7694. (when (>= (org-back-over-empty-lines) 1)
  7695. (forward-line 1))
  7696. (point))
  7697. what "children")
  7698. (goto-char start)
  7699. (outline-show-subtree)
  7700. (outline-next-heading))
  7701. (t
  7702. ;; we will sort the top-level entries in this file
  7703. (goto-char (point-min))
  7704. (or (org-at-heading-p) (outline-next-heading))
  7705. (setq start (point))
  7706. (goto-char (point-max))
  7707. (beginning-of-line 1)
  7708. (when (looking-at ".*?\\S-")
  7709. ;; File ends in a non-white line
  7710. (end-of-line 1)
  7711. (insert "\n"))
  7712. (setq end (point-max))
  7713. (setq what "top-level")
  7714. (goto-char start)
  7715. (org-show-all '(headings blocks))))
  7716. (setq beg (point))
  7717. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7718. (looking-at "\\(\\*+\\)")
  7719. (setq stars (match-string 1)
  7720. re (concat "^" (regexp-quote stars) " +")
  7721. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7722. txt (buffer-substring beg end))
  7723. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7724. (when (and (not (equal stars "*")) (string-match re2 txt))
  7725. (user-error "Region to sort contains a level above the first entry"))
  7726. (unless sorting-type
  7727. (message
  7728. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7729. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7730. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7731. what)
  7732. (setq sorting-type (read-char-exclusive)))
  7733. (unless getkey-func
  7734. (and (= (downcase sorting-type) ?f)
  7735. (setq getkey-func
  7736. (or (and interactive?
  7737. (org-read-function
  7738. "Function for extracting keys: "))
  7739. (error "Missing key extractor")))))
  7740. (and (= (downcase sorting-type) ?r)
  7741. (not property)
  7742. (setq property
  7743. (completing-read "Property: "
  7744. (mapcar #'list (org-buffer-property-keys t))
  7745. nil t)))
  7746. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7747. (message "Sorting entries...")
  7748. (save-restriction
  7749. (narrow-to-region start end)
  7750. (let ((restore-clock?
  7751. ;; The clock marker is lost when using `sort-subr'; mark
  7752. ;; the clock with temporary `:org-clock-marker-backup'
  7753. ;; text property.
  7754. (when (and (eq (org-clock-is-active) (current-buffer))
  7755. (<= start (marker-position org-clock-marker))
  7756. (>= end (marker-position org-clock-marker)))
  7757. (org-with-silent-modifications
  7758. (put-text-property (1- org-clock-marker) org-clock-marker
  7759. :org-clock-marker-backup t))
  7760. t))
  7761. (dcst (downcase sorting-type))
  7762. (case-fold-search nil)
  7763. (now (current-time)))
  7764. (org-preserve-local-variables
  7765. (sort-subr
  7766. (/= dcst sorting-type)
  7767. ;; This function moves to the beginning character of the
  7768. ;; "record" to be sorted.
  7769. (lambda nil
  7770. (if (re-search-forward re nil t)
  7771. (goto-char (match-beginning 0))
  7772. (goto-char (point-max))))
  7773. ;; This function moves to the last character of the "record" being
  7774. ;; sorted.
  7775. (lambda nil
  7776. (save-match-data
  7777. (condition-case nil
  7778. (outline-forward-same-level 1)
  7779. (error
  7780. (goto-char (point-max))))))
  7781. ;; This function returns the value that gets sorted against.
  7782. (lambda ()
  7783. (cond
  7784. ((= dcst ?n)
  7785. (string-to-number
  7786. (org-sort-remove-invisible (org-get-heading t t t t))))
  7787. ((= dcst ?a)
  7788. (funcall case-func
  7789. (org-sort-remove-invisible (org-get-heading t t t t))))
  7790. ((= dcst ?k)
  7791. (or (get-text-property (point) :org-clock-minutes) 0))
  7792. ((= dcst ?t)
  7793. (let ((end (save-excursion (outline-next-heading) (point))))
  7794. (if (or (re-search-forward org-ts-regexp end t)
  7795. (re-search-forward org-ts-regexp-both end t))
  7796. (org-time-string-to-seconds (match-string 0))
  7797. (float-time now))))
  7798. ((= dcst ?c)
  7799. (let ((end (save-excursion (outline-next-heading) (point))))
  7800. (if (re-search-forward
  7801. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7802. end t)
  7803. (org-time-string-to-seconds (match-string 0))
  7804. (float-time now))))
  7805. ((= dcst ?s)
  7806. (let ((end (save-excursion (outline-next-heading) (point))))
  7807. (if (re-search-forward org-scheduled-time-regexp end t)
  7808. (org-time-string-to-seconds (match-string 1))
  7809. (float-time now))))
  7810. ((= dcst ?d)
  7811. (let ((end (save-excursion (outline-next-heading) (point))))
  7812. (if (re-search-forward org-deadline-time-regexp end t)
  7813. (org-time-string-to-seconds (match-string 1))
  7814. (float-time now))))
  7815. ((= dcst ?p)
  7816. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7817. (string-to-char (match-string 2))
  7818. org-default-priority))
  7819. ((= dcst ?r)
  7820. (or (org-entry-get nil property) ""))
  7821. ((= dcst ?o)
  7822. (when (looking-at org-complex-heading-regexp)
  7823. (let* ((m (match-string 2))
  7824. (s (if (member m org-done-keywords) '- '+)))
  7825. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7826. ((= dcst ?f)
  7827. (if getkey-func
  7828. (progn
  7829. (setq tmp (funcall getkey-func))
  7830. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7831. tmp)
  7832. (error "Invalid key function `%s'" getkey-func)))
  7833. (t (error "Invalid sorting type `%c'" sorting-type))))
  7834. nil
  7835. (cond
  7836. ((= dcst ?a) 'org-string-collate-lessp)
  7837. ((= dcst ?f)
  7838. (or compare-func
  7839. (and interactive?
  7840. (org-read-function
  7841. (concat "Function for comparing keys "
  7842. "(empty for default `sort-subr' predicate): ")
  7843. 'allow-empty))))
  7844. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7845. (when restore-clock?
  7846. (move-marker org-clock-marker
  7847. (1+ (next-single-property-change
  7848. start :org-clock-marker-backup)))
  7849. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7850. '(:org-clock-marker-backup t)))))
  7851. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7852. (message "Sorting entries...done")))
  7853. (defun org-contextualize-keys (alist contexts)
  7854. "Return valid elements in ALIST depending on CONTEXTS.
  7855. `org-agenda-custom-commands' or `org-capture-templates' are the
  7856. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7857. or `org-capture-templates-contexts' are the associated contexts
  7858. definitions."
  7859. (let ((contexts
  7860. ;; normalize contexts
  7861. (mapcar
  7862. (lambda(c) (cond ((listp (cadr c))
  7863. (list (car c) (car c) (nth 1 c)))
  7864. ((string= "" (cadr c))
  7865. (list (car c) (car c) (nth 2 c)))
  7866. (t c)))
  7867. contexts))
  7868. (a alist) r s)
  7869. ;; loop over all commands or templates
  7870. (dolist (c a)
  7871. (let (vrules repl)
  7872. (cond
  7873. ((not (assoc (car c) contexts))
  7874. (push c r))
  7875. ((and (assoc (car c) contexts)
  7876. (setq vrules (org-contextualize-validate-key
  7877. (car c) contexts)))
  7878. (mapc (lambda (vr)
  7879. (unless (equal (car vr) (cadr vr))
  7880. (setq repl vr)))
  7881. vrules)
  7882. (if (not repl) (push c r)
  7883. (push (cadr repl) s)
  7884. (push
  7885. (cons (car c)
  7886. (cdr (or (assoc (cadr repl) alist)
  7887. (error "Undefined key `%s' as contextual replacement for `%s'"
  7888. (cadr repl) (car c)))))
  7889. r))))))
  7890. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7891. (delq
  7892. nil
  7893. (delete-dups
  7894. (mapcar (lambda (x)
  7895. (let ((tpl (car x)))
  7896. (unless (delq
  7897. nil
  7898. (mapcar (lambda (y)
  7899. (equal y tpl))
  7900. s))
  7901. x)))
  7902. (reverse r))))))
  7903. (defun org-contextualize-validate-key (key contexts)
  7904. "Check CONTEXTS for agenda or capture KEY."
  7905. (let (res)
  7906. (dolist (r contexts)
  7907. (dolist (rr (car (last r)))
  7908. (when
  7909. (and (equal key (car r))
  7910. (if (functionp rr) (funcall rr)
  7911. (or (and (eq (car rr) 'in-file)
  7912. (buffer-file-name)
  7913. (string-match (cdr rr) (buffer-file-name)))
  7914. (and (eq (car rr) 'in-mode)
  7915. (string-match (cdr rr) (symbol-name major-mode)))
  7916. (and (eq (car rr) 'in-buffer)
  7917. (string-match (cdr rr) (buffer-name)))
  7918. (when (and (eq (car rr) 'not-in-file)
  7919. (buffer-file-name))
  7920. (not (string-match (cdr rr) (buffer-file-name))))
  7921. (when (eq (car rr) 'not-in-mode)
  7922. (not (string-match (cdr rr) (symbol-name major-mode))))
  7923. (when (eq (car rr) 'not-in-buffer)
  7924. (not (string-match (cdr rr) (buffer-name)))))))
  7925. (push r res))))
  7926. (delete-dups (delq nil res))))
  7927. ;; Defined to provide a value for defcustom, since there is no
  7928. ;; string-collate-greaterp in Emacs.
  7929. (defun org-string-collate-greaterp (s1 s2)
  7930. "Return non-nil if S1 is greater than S2 in collation order."
  7931. (not (org-string-collate-lessp s1 s2)))
  7932. ;;;###autoload
  7933. (defun org-run-like-in-org-mode (cmd)
  7934. "Run a command, pretending that the current buffer is in Org mode.
  7935. This will temporarily bind local variables that are typically bound in
  7936. Org mode to the values they have in Org mode, and then interactively
  7937. call CMD."
  7938. (org-load-modules-maybe)
  7939. (let (binds)
  7940. (dolist (var (org-get-local-variables))
  7941. (when (or (not (boundp (car var)))
  7942. (eq (symbol-value (car var))
  7943. (default-value (car var))))
  7944. (push (list (car var) `(quote ,(cadr var))) binds)))
  7945. (eval `(let ,binds
  7946. (call-interactively (quote ,cmd))))))
  7947. (defun org-get-category (&optional pos force-refresh)
  7948. "Get the category applying to position POS."
  7949. (save-match-data
  7950. (when force-refresh (org-refresh-category-properties))
  7951. (let ((pos (or pos (point))))
  7952. (or (get-text-property pos 'org-category)
  7953. (progn (org-refresh-category-properties)
  7954. (get-text-property pos 'org-category))))))
  7955. ;;; Refresh properties
  7956. (defun org-refresh-properties (dprop tprop)
  7957. "Refresh buffer text properties.
  7958. DPROP is the drawer property and TPROP is either the
  7959. corresponding text property to set, or an alist with each element
  7960. being a text property (as a symbol) and a function to apply to
  7961. the value of the drawer property."
  7962. (let* ((case-fold-search t)
  7963. (inhibit-read-only t)
  7964. (inherit? (org-property-inherit-p dprop))
  7965. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7966. (global (and inherit? (org--property-global-value dprop nil))))
  7967. (org-with-silent-modifications
  7968. (org-with-point-at 1
  7969. ;; Set global values (e.g., values defined through
  7970. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7971. (when global (put-text-property (point-min) (point-max) tprop global))
  7972. ;; Set local values.
  7973. (while (re-search-forward property-re nil t)
  7974. (when (org-at-property-p)
  7975. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7976. (outline-next-heading))))))
  7977. (defun org-refresh-property (tprop p &optional inherit)
  7978. "Refresh the buffer text property TPROP from the drawer property P.
  7979. The refresh happens only for the current headline, or the whole
  7980. sub-tree if optional argument INHERIT is non-nil."
  7981. (unless (org-before-first-heading-p)
  7982. (save-excursion
  7983. (org-back-to-heading t)
  7984. (let ((start (point))
  7985. (end (save-excursion
  7986. (if inherit (org-end-of-subtree t t)
  7987. (or (outline-next-heading) (point-max))))))
  7988. (if (symbolp tprop)
  7989. ;; TPROP is a text property symbol.
  7990. (put-text-property start end tprop p)
  7991. ;; TPROP is an alist with (property . function) elements.
  7992. (pcase-dolist (`(,prop . ,f) tprop)
  7993. (put-text-property start end prop (funcall f p))))))))
  7994. (defun org-refresh-category-properties ()
  7995. "Refresh category text properties in the buffer."
  7996. (let ((case-fold-search t)
  7997. (inhibit-read-only t)
  7998. (default-category
  7999. (cond ((null org-category)
  8000. (if buffer-file-name
  8001. (file-name-sans-extension
  8002. (file-name-nondirectory buffer-file-name))
  8003. "???"))
  8004. ((symbolp org-category) (symbol-name org-category))
  8005. (t org-category))))
  8006. (org-with-silent-modifications
  8007. (org-with-wide-buffer
  8008. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8009. ;; This is the default category for the buffer. If none is
  8010. ;; found, fall-back to `org-category' or buffer file name.
  8011. (put-text-property
  8012. (point-min) (point-max)
  8013. 'org-category
  8014. (catch 'buffer-category
  8015. (goto-char (point-max))
  8016. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8017. (let ((element (org-element-at-point)))
  8018. (when (eq (org-element-type element) 'keyword)
  8019. (throw 'buffer-category
  8020. (org-element-property :value element)))))
  8021. default-category))
  8022. ;; Set sub-tree specific categories.
  8023. (goto-char (point-min))
  8024. (let ((regexp (org-re-property "CATEGORY")))
  8025. (while (re-search-forward regexp nil t)
  8026. (let ((value (match-string-no-properties 3)))
  8027. (when (org-at-property-p)
  8028. (put-text-property
  8029. (save-excursion (org-back-to-heading t) (point))
  8030. (save-excursion (org-end-of-subtree t t) (point))
  8031. 'org-category
  8032. value)))))))))
  8033. (defun org-refresh-stats-properties ()
  8034. "Refresh stats text properties in the buffer."
  8035. (org-with-silent-modifications
  8036. (org-with-point-at 1
  8037. (let ((regexp (concat org-outline-regexp-bol
  8038. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8039. (while (re-search-forward regexp nil t)
  8040. (let* ((numerator (string-to-number (match-string 1)))
  8041. (denominator (and (match-end 2)
  8042. (string-to-number (match-string 2))))
  8043. (stats (cond ((not denominator) numerator) ;percent
  8044. ((= denominator 0) 0)
  8045. (t (/ (* numerator 100) denominator)))))
  8046. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8047. 'org-stats stats)))))))
  8048. (defun org-refresh-effort-properties ()
  8049. "Refresh effort properties"
  8050. (org-refresh-properties
  8051. org-effort-property
  8052. '((effort . identity)
  8053. (effort-minutes . org-duration-to-minutes))))
  8054. ;;;; Link Stuff
  8055. ;;; Link abbreviations
  8056. (defun org-link-expand-abbrev (link)
  8057. "Apply replacements as defined in `org-link-abbrev-alist'."
  8058. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8059. (let* ((key (match-string 1 link))
  8060. (as (or (assoc key org-link-abbrev-alist-local)
  8061. (assoc key org-link-abbrev-alist)))
  8062. (tag (and (match-end 2) (match-string 3 link)))
  8063. rpl)
  8064. (if (not as)
  8065. link
  8066. (setq rpl (cdr as))
  8067. (cond
  8068. ((symbolp rpl) (funcall rpl tag))
  8069. ((string-match "%(\\([^)]+\\))" rpl)
  8070. (replace-match
  8071. (save-match-data
  8072. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8073. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8074. ((string-match "%h" rpl)
  8075. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8076. (t (concat rpl tag)))))
  8077. link))
  8078. ;;; Storing and inserting links
  8079. (defvar org-insert-link-history nil
  8080. "Minibuffer history for links inserted with `org-insert-link'.")
  8081. (defvar org-stored-links nil
  8082. "Contains the links stored with `org-store-link'.")
  8083. (defvar org-store-link-plist nil
  8084. "Plist with info about the most recently link created with `org-store-link'.")
  8085. (defun org-store-link-functions ()
  8086. "Return a list of functions that are called to create and store a link.
  8087. The functions defined in the :store property of
  8088. `org-link-parameters'.
  8089. Each function will be called in turn until one returns a non-nil
  8090. value. Each function should check if it is responsible for
  8091. creating this link (for example by looking at the major mode).
  8092. If not, it must exit and return nil. If yes, it should return
  8093. a non-nil value after calling `org-store-link-props' with a list
  8094. of properties and values. Special properties are:
  8095. :type The link prefix, like \"http\". This must be given.
  8096. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8097. This is obligatory as well.
  8098. :description Optional default description for the second pair
  8099. of brackets in an Org mode link. The user can still change
  8100. this when inserting this link into an Org mode buffer.
  8101. In addition to these, any additional properties can be specified
  8102. and then used in capture templates."
  8103. (cl-loop for link in org-link-parameters
  8104. with store-func
  8105. do (setq store-func (org-link-get-parameter (car link) :store))
  8106. if store-func
  8107. collect store-func))
  8108. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8109. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8110. ;;;###autoload
  8111. (defun org-store-link (arg &optional interactive?)
  8112. "Store an org-link to the current location.
  8113. \\<org-mode-map>
  8114. This link is added to `org-stored-links' and can later be inserted
  8115. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8116. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8117. A single
  8118. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8119. `org-gnus-prefer-web-links' for links to Usenet articles.
  8120. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8121. skipping storing functions that are not
  8122. part of Org core.
  8123. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8124. prefix ARG forces storing a link for each line in the
  8125. active region.
  8126. Assume the function is called interactively if INTERACTIVE? is
  8127. non-nil."
  8128. (interactive "P\np")
  8129. (org-load-modules-maybe)
  8130. (if (and (equal arg '(64)) (org-region-active-p))
  8131. (save-excursion
  8132. (let ((end (region-end)))
  8133. (goto-char (region-beginning))
  8134. (set-mark (point))
  8135. (while (< (point-at-eol) end)
  8136. (move-end-of-line 1) (activate-mark)
  8137. (let (current-prefix-arg)
  8138. (call-interactively 'org-store-link))
  8139. (move-beginning-of-line 2)
  8140. (set-mark (point)))))
  8141. (setq org-store-link-plist nil)
  8142. (let (link cpltxt desc description search txt custom-id agenda-link)
  8143. (cond
  8144. ;; Store a link using an external link type, if any function is
  8145. ;; available. If more than one can generate a link from current
  8146. ;; location, ask which one to use.
  8147. ((and (not (equal arg '(16)))
  8148. (let ((results-alist nil))
  8149. (dolist (f (org-store-link-functions))
  8150. (when (funcall f)
  8151. ;; XXX: return value is not link's plist, so we
  8152. ;; store the new value before it is modified. It
  8153. ;; would be cleaner to ask store link functions to
  8154. ;; return the plist instead.
  8155. (push (cons f (copy-sequence org-store-link-plist))
  8156. results-alist)))
  8157. (pcase results-alist
  8158. (`nil nil)
  8159. (`((,_ . ,_)) t) ;single choice: nothing to do
  8160. (`((,name . ,_) . ,_)
  8161. ;; Reinstate link plist associated to the chosen
  8162. ;; function.
  8163. (apply #'org-store-link-props
  8164. (cdr (assoc-string
  8165. (completing-read
  8166. "Which function for creating the link? "
  8167. (mapcar #'car results-alist)
  8168. nil t (symbol-name name))
  8169. results-alist)))
  8170. t))))
  8171. (setq link (plist-get org-store-link-plist :link))
  8172. (setq desc (or (plist-get org-store-link-plist :description)
  8173. link)))
  8174. ;; Store a link from a source code buffer.
  8175. ((org-src-edit-buffer-p)
  8176. (let ((coderef-format (org-src-coderef-format)))
  8177. (cond ((org-match-line (org-src-coderef-regexp coderef-format))
  8178. (setq link (format "(%s)" (match-string-no-properties 3))))
  8179. (interactive?
  8180. (let ((label (read-string "Code line label: ")))
  8181. (end-of-line)
  8182. (setq link (format coderef-format label))
  8183. (let ((gc (- 79 (length link))))
  8184. (if (< (current-column) gc)
  8185. (org-move-to-column gc t)
  8186. (insert " ")))
  8187. (insert link)
  8188. (setq link (concat "(" label ")"))
  8189. (setq desc nil)))
  8190. (t (setq link nil)))))
  8191. ;; We are in the agenda, link to referenced location
  8192. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8193. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8194. (get-text-property (point) 'org-marker))))
  8195. (when m
  8196. (org-with-point-at m
  8197. (setq agenda-link (org-store-link nil interactive?))))))
  8198. ((eq major-mode 'calendar-mode)
  8199. (let ((cd (calendar-cursor-to-date)))
  8200. (setq link
  8201. (format-time-string
  8202. (car org-time-stamp-formats)
  8203. (apply 'encode-time
  8204. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8205. nil nil nil))))
  8206. (org-store-link-props :type "calendar" :date cd)))
  8207. ((eq major-mode 'help-mode)
  8208. (setq link (concat "help:" (save-excursion
  8209. (goto-char (point-min))
  8210. (looking-at "^[^ ]+")
  8211. (match-string 0))))
  8212. (org-store-link-props :type "help"))
  8213. ((eq major-mode 'w3-mode)
  8214. (setq cpltxt (if (and (buffer-name)
  8215. (not (string-match "Untitled" (buffer-name))))
  8216. (buffer-name)
  8217. (url-view-url t))
  8218. link (url-view-url t))
  8219. (org-store-link-props :type "w3" :url (url-view-url t)))
  8220. ((eq major-mode 'image-mode)
  8221. (setq cpltxt (concat "file:"
  8222. (abbreviate-file-name buffer-file-name))
  8223. link cpltxt)
  8224. (org-store-link-props :type "image" :file buffer-file-name))
  8225. ;; In dired, store a link to the file of the current line
  8226. ((derived-mode-p 'dired-mode)
  8227. (let ((file (dired-get-filename nil t)))
  8228. (setq file (if file
  8229. (abbreviate-file-name
  8230. (expand-file-name (dired-get-filename nil t)))
  8231. ;; otherwise, no file so use current directory.
  8232. default-directory))
  8233. (setq cpltxt (concat "file:" file)
  8234. link cpltxt)))
  8235. ((setq search (run-hook-with-args-until-success
  8236. 'org-create-file-search-functions))
  8237. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8238. "::" search))
  8239. (setq cpltxt (or description link)))
  8240. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8241. (org-with-limited-levels
  8242. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8243. (cond
  8244. ;; Store a link using the target at point
  8245. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8246. (setq cpltxt
  8247. (concat "file:"
  8248. (abbreviate-file-name
  8249. (buffer-file-name (buffer-base-buffer)))
  8250. "::" (match-string 1))
  8251. link cpltxt))
  8252. ((and (featurep 'org-id)
  8253. (or (eq org-id-link-to-org-use-id t)
  8254. (and interactive?
  8255. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8256. (and (eq org-id-link-to-org-use-id
  8257. 'create-if-interactive-and-no-custom-id)
  8258. (not custom-id))))
  8259. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8260. ;; Store a link using the ID at point
  8261. (setq link (condition-case nil
  8262. (prog1 (org-id-store-link)
  8263. (setq desc (or (plist-get org-store-link-plist
  8264. :description)
  8265. "")))
  8266. (error
  8267. ;; Probably before first headline, link only to file
  8268. (concat "file:"
  8269. (abbreviate-file-name
  8270. (buffer-file-name (buffer-base-buffer))))))))
  8271. (t
  8272. ;; Just link to current headline
  8273. (setq cpltxt (concat "file:"
  8274. (abbreviate-file-name
  8275. (buffer-file-name (buffer-base-buffer)))))
  8276. ;; Add a context search string
  8277. (when (org-xor org-context-in-file-links
  8278. (equal arg '(4)))
  8279. (let* ((element (org-element-at-point))
  8280. (name (org-element-property :name element)))
  8281. (setq txt (cond
  8282. ((org-at-heading-p) nil)
  8283. (name)
  8284. ((org-region-active-p)
  8285. (buffer-substring (region-beginning) (region-end)))))
  8286. (when (or (null txt) (string-match "\\S-" txt))
  8287. (setq cpltxt
  8288. (concat cpltxt "::"
  8289. (condition-case nil
  8290. (org-make-org-heading-search-string txt)
  8291. (error "")))
  8292. desc (or name
  8293. (nth 4 (ignore-errors (org-heading-components)))
  8294. "NONE")))))
  8295. (when (string-match "::\\'" cpltxt)
  8296. (setq cpltxt (substring cpltxt 0 -2)))
  8297. (setq link cpltxt)))))
  8298. ((buffer-file-name (buffer-base-buffer))
  8299. ;; Just link to this file here.
  8300. (setq cpltxt (concat "file:"
  8301. (abbreviate-file-name
  8302. (buffer-file-name (buffer-base-buffer)))))
  8303. ;; Add a context string.
  8304. (when (org-xor org-context-in-file-links
  8305. (equal arg '(4)))
  8306. (setq txt (if (org-region-active-p)
  8307. (buffer-substring (region-beginning) (region-end))
  8308. (buffer-substring (point-at-bol) (point-at-eol))))
  8309. ;; Only use search option if there is some text.
  8310. (when (string-match "\\S-" txt)
  8311. (setq cpltxt
  8312. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8313. desc "NONE")))
  8314. (setq link cpltxt))
  8315. (interactive?
  8316. (user-error "No method for storing a link from this buffer"))
  8317. (t (setq link nil)))
  8318. ;; We're done setting link and desc, clean up
  8319. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8320. (setq link (or link cpltxt)
  8321. desc (or desc cpltxt))
  8322. (cond ((not desc))
  8323. ((equal desc "NONE") (setq desc nil))
  8324. (t (setq desc
  8325. (replace-regexp-in-string
  8326. org-bracket-link-analytic-regexp
  8327. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8328. desc))))
  8329. ;; Return the link
  8330. (if (not (and interactive? link))
  8331. (or agenda-link (and link (org-make-link-string link desc)))
  8332. (push (list link desc) org-stored-links)
  8333. (message "Stored: %s" (or desc link))
  8334. (when custom-id
  8335. (setq link (concat "file:" (abbreviate-file-name
  8336. (buffer-file-name)) "::#" custom-id))
  8337. (push (list link desc) org-stored-links))
  8338. (car org-stored-links)))))
  8339. (defun org-store-link-props (&rest plist)
  8340. "Store link properties.
  8341. The properties are pre-processed by extracting names, addresses
  8342. and dates."
  8343. (let ((x (plist-get plist :from)))
  8344. (when x
  8345. (let ((adr (mail-extract-address-components x)))
  8346. (setq plist (plist-put plist :fromname (car adr)))
  8347. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8348. (let ((x (plist-get plist :to)))
  8349. (when x
  8350. (let ((adr (mail-extract-address-components x)))
  8351. (setq plist (plist-put plist :toname (car adr)))
  8352. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8353. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8354. (when x
  8355. (setq plist (plist-put plist :date-timestamp
  8356. (format-time-string
  8357. (org-time-stamp-format t) x)))
  8358. (setq plist (plist-put plist :date-timestamp-inactive
  8359. (format-time-string
  8360. (org-time-stamp-format t t) x)))))
  8361. (let ((from (plist-get plist :from))
  8362. (to (plist-get plist :to)))
  8363. (when (and from to org-from-is-user-regexp)
  8364. (setq plist
  8365. (plist-put plist :fromto
  8366. (if (string-match org-from-is-user-regexp from)
  8367. (concat "to %t")
  8368. (concat "from %f"))))))
  8369. (setq org-store-link-plist plist))
  8370. (defun org-add-link-props (&rest plist)
  8371. "Add these properties to the link property list."
  8372. (let (key value)
  8373. (while plist
  8374. (setq key (pop plist) value (pop plist))
  8375. (setq org-store-link-plist
  8376. (plist-put org-store-link-plist key value)))))
  8377. (defun org-email-link-description (&optional fmt)
  8378. "Return the description part of an email link.
  8379. This takes information from `org-store-link-plist' and formats it
  8380. according to FMT (default from `org-email-link-description-format')."
  8381. (setq fmt (or fmt org-email-link-description-format))
  8382. (let* ((p org-store-link-plist)
  8383. (to (plist-get p :toaddress))
  8384. (from (plist-get p :fromaddress))
  8385. (table
  8386. (list
  8387. (cons "%c" (plist-get p :fromto))
  8388. (cons "%F" (plist-get p :from))
  8389. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8390. (cons "%T" (plist-get p :to))
  8391. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8392. (cons "%s" (plist-get p :subject))
  8393. (cons "%d" (plist-get p :date))
  8394. (cons "%m" (plist-get p :message-id)))))
  8395. (when (string-match "%c" fmt)
  8396. ;; Check if the user wrote this message
  8397. (if (and org-from-is-user-regexp from to
  8398. (save-match-data (string-match org-from-is-user-regexp from)))
  8399. (setq fmt (replace-match "to %t" t t fmt))
  8400. (setq fmt (replace-match "from %f" t t fmt))))
  8401. (org-replace-escapes fmt table)))
  8402. (defun org-make-org-heading-search-string (&optional string)
  8403. "Make search string for the current headline or STRING."
  8404. (let ((s (or string
  8405. (and (derived-mode-p 'org-mode)
  8406. (save-excursion
  8407. (org-back-to-heading t)
  8408. (org-element-property :raw-value (org-element-at-point))))))
  8409. (lines org-context-in-file-links))
  8410. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8411. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8412. (when (and string (integerp lines) (> lines 0))
  8413. (let ((slines (org-split-string s "\n")))
  8414. (when (< lines (length slines))
  8415. (setq s (mapconcat
  8416. 'identity
  8417. (reverse (nthcdr (- (length slines) lines)
  8418. (reverse slines))) "\n")))))
  8419. (mapconcat #'identity (split-string s) " ")))
  8420. (defconst org-link-escape-chars
  8421. ;;%20 %5B %5D %25
  8422. '(?\s ?\[ ?\] ?%)
  8423. "List of characters that should be escaped in a link when stored to Org.
  8424. This is the list that is used for internal purposes.")
  8425. (defun org-make-link-string (link &optional description)
  8426. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8427. (unless (org-string-nw-p link) (error "Empty link"))
  8428. (let ((uri (cond ((string-match org-link-types-re link)
  8429. (concat (match-string 1 link)
  8430. (org-link-escape (substring link (match-end 1)))))
  8431. ((or (file-name-absolute-p link)
  8432. (string-match-p "\\`\\.\\.?/" link))
  8433. (org-link-escape link))
  8434. ;; For readability, do not encode space characters
  8435. ;; in fuzzy links.
  8436. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8437. (description
  8438. (and (org-string-nw-p description)
  8439. ;; Remove brackets from description, as they are fatal.
  8440. (replace-regexp-in-string
  8441. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8442. (org-trim description)))))
  8443. (format "[[%s]%s]"
  8444. uri
  8445. (if description (format "[%s]" description) ""))))
  8446. (defun org-link-escape (text &optional table merge)
  8447. "Return percent escaped representation of TEXT.
  8448. TEXT is a string with the text to escape.
  8449. Optional argument TABLE is a list with characters that should be
  8450. escaped. When nil, `org-link-escape-chars' is used.
  8451. If optional argument MERGE is set, merge TABLE into
  8452. `org-link-escape-chars'."
  8453. (let ((characters-to-encode
  8454. (cond ((null table) org-link-escape-chars)
  8455. (merge (append org-link-escape-chars table))
  8456. (t table))))
  8457. (mapconcat
  8458. (lambda (c)
  8459. (if (or (memq c characters-to-encode)
  8460. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8461. (mapconcat (lambda (e) (format "%%%.2X" e))
  8462. (or (encode-coding-char c 'utf-8)
  8463. (error "Unable to percent escape character: %c" c))
  8464. "")
  8465. (char-to-string c)))
  8466. text "")))
  8467. (defun org-link-unescape (str)
  8468. "Unhex hexified Unicode parts in string STR.
  8469. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8470. reciprocal of `org-link-escape', which see."
  8471. (if (org-string-nw-p str)
  8472. (replace-regexp-in-string
  8473. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8474. str))
  8475. (defun org-link-unescape-compound (hex)
  8476. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8477. Note: this function also decodes single byte encodings like
  8478. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8479. (save-match-data
  8480. (let* ((bytes (cdr (split-string hex "%")))
  8481. (ret "")
  8482. (eat 0)
  8483. (sum 0))
  8484. (while bytes
  8485. (let* ((val (string-to-number (pop bytes) 16))
  8486. (shift-xor
  8487. (if (= 0 eat)
  8488. (cond
  8489. ((>= val 252) (cons 6 252))
  8490. ((>= val 248) (cons 5 248))
  8491. ((>= val 240) (cons 4 240))
  8492. ((>= val 224) (cons 3 224))
  8493. ((>= val 192) (cons 2 192))
  8494. (t (cons 0 0)))
  8495. (cons 6 128))))
  8496. (when (>= val 192) (setq eat (car shift-xor)))
  8497. (setq val (logxor val (cdr shift-xor)))
  8498. (setq sum (+ (lsh sum (car shift-xor)) val))
  8499. (when (> eat 0) (setq eat (- eat 1)))
  8500. (cond
  8501. ((= 0 eat) ;multi byte
  8502. (setq ret (concat ret (char-to-string sum)))
  8503. (setq sum 0))
  8504. ((not bytes) ; single byte(s)
  8505. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8506. ret)))
  8507. (defun org-link-unescape-single-byte-sequence (hex)
  8508. "Unhexify hex-encoded single byte character sequences."
  8509. (mapconcat (lambda (byte)
  8510. (char-to-string (string-to-number byte 16)))
  8511. (cdr (split-string hex "%")) ""))
  8512. (defun org-fixup-message-id-for-http (s)
  8513. "Replace special characters in a message id, so it can be used in an http query."
  8514. (when (string-match "%" s)
  8515. (setq s (mapconcat (lambda (c)
  8516. (if (eq c ?%)
  8517. "%25"
  8518. (char-to-string c)))
  8519. s "")))
  8520. (while (string-match "<" s)
  8521. (setq s (replace-match "%3C" t t s)))
  8522. (while (string-match ">" s)
  8523. (setq s (replace-match "%3E" t t s)))
  8524. (while (string-match "@" s)
  8525. (setq s (replace-match "%40" t t s)))
  8526. s)
  8527. (defun org-link-prettify (link)
  8528. "Return a human-readable representation of LINK.
  8529. The car of LINK must be a raw link.
  8530. The cdr of LINK must be either a link description or nil."
  8531. (let ((desc (or (cadr link) "<no description>")))
  8532. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8533. "<" (car link) ">")))
  8534. ;;;###autoload
  8535. (defun org-insert-link-global ()
  8536. "Insert a link like Org mode does.
  8537. This command can be called in any mode to insert a link in Org syntax."
  8538. (interactive)
  8539. (org-load-modules-maybe)
  8540. (org-run-like-in-org-mode 'org-insert-link))
  8541. (defun org-insert-all-links (arg &optional pre post)
  8542. "Insert all links in `org-stored-links'.
  8543. When a universal prefix, do not delete the links from `org-stored-links'.
  8544. When `ARG' is a number, insert the last N link(s).
  8545. `PRE' and `POST' are optional arguments to define a string to
  8546. prepend or to append."
  8547. (interactive "P")
  8548. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8549. (links (copy-sequence org-stored-links))
  8550. (pr (or pre "- "))
  8551. (po (or post "\n"))
  8552. (cnt 1) l)
  8553. (if (null org-stored-links)
  8554. (message "No link to insert")
  8555. (while (and (or (listp arg) (>= arg cnt))
  8556. (setq l (if (listp arg)
  8557. (pop links)
  8558. (pop org-stored-links))))
  8559. (setq cnt (1+ cnt))
  8560. (insert pr)
  8561. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8562. (insert po)))))
  8563. (defun org-insert-last-stored-link (arg)
  8564. "Insert the last link stored in `org-stored-links'."
  8565. (interactive "p")
  8566. (org-insert-all-links arg "" "\n"))
  8567. (defun org-link-fontify-links-to-this-file ()
  8568. "Fontify links to the current file in `org-stored-links'."
  8569. (let ((f (buffer-file-name)) a b)
  8570. (setq a (mapcar (lambda(l)
  8571. (let ((ll (car l)))
  8572. (when (and (string-match "^file:\\(.+\\)::" ll)
  8573. (equal f (expand-file-name (match-string 1 ll))))
  8574. ll)))
  8575. org-stored-links))
  8576. (when (featurep 'org-id)
  8577. (setq b (mapcar (lambda(l)
  8578. (let ((ll (car l)))
  8579. (when (and (string-match "^id:\\(.+\\)$" ll)
  8580. (equal f (expand-file-name
  8581. (or (org-id-find-id-file
  8582. (match-string 1 ll)) ""))))
  8583. ll)))
  8584. org-stored-links)))
  8585. (mapcar (lambda(l)
  8586. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8587. (delq nil (append a b)))))
  8588. (defvar org--links-history nil)
  8589. (defun org-insert-link (&optional complete-file link-location default-description)
  8590. "Insert a link. At the prompt, enter the link.
  8591. Completion can be used to insert any of the link protocol prefixes in use.
  8592. The history can be used to select a link previously stored with
  8593. `org-store-link'. When the empty string is entered (i.e. if you just
  8594. press `RET' at the prompt), the link defaults to the most recently
  8595. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8596. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8597. You will also be prompted for a description, and if one is given, it will
  8598. be displayed in the buffer instead of the link.
  8599. If there is already a link at point, this command will allow you to edit
  8600. link and description parts.
  8601. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8602. file name can be
  8603. selected using completion. The path to the file will be relative to the
  8604. current directory if the file is in the current directory or a subdirectory.
  8605. Otherwise, the link will be the absolute path as completed in the minibuffer
  8606. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8607. option `org-link-file-path-type'.
  8608. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8609. absolute path even if the file is in
  8610. the current directory or below.
  8611. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8612. prefix negates `org-keep-stored-link-after-insertion'.
  8613. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8614. the link location instead of reading one interactively.
  8615. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8616. be used as the default description. Otherwise, if
  8617. `org-make-link-description-function' is non-nil, this function
  8618. will be called with the link target, and the result will be the
  8619. default link description. When called non-interactivily, don't
  8620. allow to edit the default description."
  8621. (interactive "P")
  8622. (let* ((wcf (current-window-configuration))
  8623. (origbuf (current-buffer))
  8624. (region (when (org-region-active-p)
  8625. (buffer-substring (region-beginning) (region-end))))
  8626. (remove (and region (list (region-beginning) (region-end))))
  8627. (desc region)
  8628. (link link-location)
  8629. (abbrevs org-link-abbrev-alist-local)
  8630. entry all-prefixes auto-desc)
  8631. (cond
  8632. (link-location) ; specified by arg, just use it.
  8633. ((org-in-regexp org-bracket-link-regexp 1)
  8634. ;; We do have a link at point, and we are going to edit it.
  8635. (setq remove (list (match-beginning 0) (match-end 0)))
  8636. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8637. (setq link (read-string "Link: "
  8638. (org-link-unescape
  8639. (match-string-no-properties 1)))))
  8640. ((or (org-in-regexp org-angle-link-re)
  8641. (org-in-regexp org-plain-link-re))
  8642. ;; Convert to bracket link
  8643. (setq remove (list (match-beginning 0) (match-end 0))
  8644. link (read-string "Link: "
  8645. (org-unbracket-string "<" ">" (match-string 0)))))
  8646. ((member complete-file '((4) (16)))
  8647. ;; Completing read for file names.
  8648. (setq link (org-file-complete-link complete-file)))
  8649. (t
  8650. ;; Read link, with completion for stored links.
  8651. (org-link-fontify-links-to-this-file)
  8652. (org-switch-to-buffer-other-window "*Org Links*")
  8653. (with-current-buffer "*Org Links*"
  8654. (erase-buffer)
  8655. (insert "Insert a link.
  8656. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8657. (when org-stored-links
  8658. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8659. (insert (mapconcat 'org-link-prettify
  8660. (reverse org-stored-links) "\n")))
  8661. (goto-char (point-min)))
  8662. (let ((cw (selected-window)))
  8663. (select-window (get-buffer-window "*Org Links*" 'visible))
  8664. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8665. (unless (pos-visible-in-window-p (point-max))
  8666. (org-fit-window-to-buffer))
  8667. (and (window-live-p cw) (select-window cw)))
  8668. (setq all-prefixes (append (mapcar 'car abbrevs)
  8669. (mapcar 'car org-link-abbrev-alist)
  8670. (org-link-types)))
  8671. (unwind-protect
  8672. ;; Fake a link history, containing the stored links.
  8673. (let ((org--links-history
  8674. (append (mapcar #'car org-stored-links)
  8675. org-insert-link-history)))
  8676. (setq link
  8677. (org-completing-read
  8678. "Link: "
  8679. (append
  8680. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8681. (mapcar #'car org-stored-links))
  8682. nil nil nil
  8683. 'org--links-history
  8684. (caar org-stored-links)))
  8685. (unless (org-string-nw-p link) (user-error "No link selected"))
  8686. (dolist (l org-stored-links)
  8687. (when (equal link (cadr l))
  8688. (setq link (car l))
  8689. (setq auto-desc t)))
  8690. (when (or (member link all-prefixes)
  8691. (and (equal ":" (substring link -1))
  8692. (member (substring link 0 -1) all-prefixes)
  8693. (setq link (substring link 0 -1))))
  8694. (setq link (with-current-buffer origbuf
  8695. (org-link-try-special-completion link)))))
  8696. (set-window-configuration wcf)
  8697. (kill-buffer "*Org Links*"))
  8698. (setq entry (assoc link org-stored-links))
  8699. (or entry (push link org-insert-link-history))
  8700. (setq desc (or desc (nth 1 entry)))))
  8701. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8702. (not org-keep-stored-link-after-insertion))
  8703. (setq org-stored-links (delq (assoc link org-stored-links)
  8704. org-stored-links)))
  8705. (when (and (string-match org-plain-link-re link)
  8706. (not (string-match org-ts-regexp link)))
  8707. ;; URL-like link, normalize the use of angular brackets.
  8708. (setq link (org-unbracket-string "<" ">" link)))
  8709. ;; Check if we are linking to the current file with a search
  8710. ;; option If yes, simplify the link by using only the search
  8711. ;; option.
  8712. (when (and buffer-file-name
  8713. (let ((case-fold-search nil))
  8714. (string-match "\\`file:\\(.+?\\)::" link)))
  8715. (let ((path (match-string-no-properties 1 link))
  8716. (search (substring-no-properties link (match-end 0))))
  8717. (save-match-data
  8718. (when (equal (file-truename buffer-file-name) (file-truename path))
  8719. ;; We are linking to this same file, with a search option
  8720. (setq link search)))))
  8721. ;; Check if we can/should use a relative path. If yes, simplify
  8722. ;; the link.
  8723. (let ((case-fold-search nil))
  8724. (when (string-match "\\`\\(file\\|docview\\):" link)
  8725. (let* ((type (match-string-no-properties 0 link))
  8726. (path-start (match-end 0))
  8727. (search (and (string-match "::\\(.*\\)\\'" link)
  8728. (match-string 1 link)))
  8729. (path
  8730. (if search
  8731. (substring-no-properties
  8732. link path-start (match-beginning 0))
  8733. (substring-no-properties link (match-end 0))))
  8734. (origpath path))
  8735. (cond
  8736. ((or (eq org-link-file-path-type 'absolute)
  8737. (equal complete-file '(16)))
  8738. (setq path (abbreviate-file-name (expand-file-name path))))
  8739. ((eq org-link-file-path-type 'noabbrev)
  8740. (setq path (expand-file-name path)))
  8741. ((eq org-link-file-path-type 'relative)
  8742. (setq path (file-relative-name path)))
  8743. (t
  8744. (save-match-data
  8745. (if (string-match (concat "^" (regexp-quote
  8746. (expand-file-name
  8747. (file-name-as-directory
  8748. default-directory))))
  8749. (expand-file-name path))
  8750. ;; We are linking a file with relative path name.
  8751. (setq path (substring (expand-file-name path)
  8752. (match-end 0)))
  8753. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8754. (setq link (concat type path (and search (concat "::" search))))
  8755. (when (equal desc origpath)
  8756. (setq desc path)))))
  8757. (unless auto-desc
  8758. (let ((initial-input
  8759. (cond
  8760. (default-description)
  8761. ((not org-make-link-description-function) desc)
  8762. (t (condition-case nil
  8763. (funcall org-make-link-description-function link desc)
  8764. (error
  8765. (message "Can't get link description from `%s'"
  8766. (symbol-name org-make-link-description-function))
  8767. (sit-for 2)
  8768. nil))))))
  8769. (setq desc (if (called-interactively-p 'any)
  8770. (read-string "Description: " initial-input)
  8771. initial-input))))
  8772. (unless (string-match "\\S-" desc) (setq desc nil))
  8773. (when remove (apply 'delete-region remove))
  8774. (insert (org-make-link-string link desc))
  8775. ;; Redisplay so as the new link has proper invisible characters.
  8776. (sit-for 0)))
  8777. (defun org-link-try-special-completion (type)
  8778. "If there is completion support for link type TYPE, offer it."
  8779. (let ((fun (org-link-get-parameter type :complete)))
  8780. (if (functionp fun)
  8781. (funcall fun)
  8782. (read-string "Link (no completion support): " (concat type ":")))))
  8783. (defun org-file-complete-link (&optional arg)
  8784. "Create a file link using completion."
  8785. (let ((file (read-file-name "File: "))
  8786. (pwd (file-name-as-directory (expand-file-name ".")))
  8787. (pwd1 (file-name-as-directory (abbreviate-file-name
  8788. (expand-file-name ".")))))
  8789. (cond ((equal arg '(16))
  8790. (concat "file:"
  8791. (abbreviate-file-name (expand-file-name file))))
  8792. ((string-match
  8793. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8794. (concat "file:" (match-string 1 file)))
  8795. ((string-match
  8796. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8797. (expand-file-name file))
  8798. (concat "file:"
  8799. (match-string 1 (expand-file-name file))))
  8800. (t (concat "file:" file)))))
  8801. ;;; Opening/following a link
  8802. (defvar org-link-search-failed nil)
  8803. (defvar org-open-link-functions nil
  8804. "Hook for functions finding a plain text link.
  8805. These functions must take a single argument, the link content.
  8806. They will be called for links that look like [[link text][description]]
  8807. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8808. like a filename (e.g. \"./blue.png\").
  8809. These functions will be called *before* Org attempts to resolve the
  8810. link by doing text searches in the current buffer - so if you want a
  8811. link \"[[target]]\" to still find \"<<target>>\", your function should
  8812. handle this as a special case.
  8813. When the function does handle the link, it must return a non-nil value.
  8814. If it decides that it is not responsible for this link, it must return
  8815. nil to indicate that that Org can continue with other options like
  8816. exact and fuzzy text search.")
  8817. (defun org-next-link (&optional search-backward)
  8818. "Move forward to the next link.
  8819. If the link is in hidden text, expose it."
  8820. (interactive "P")
  8821. (when (and org-link-search-failed (eq this-command last-command))
  8822. (goto-char (point-min))
  8823. (message "Link search wrapped back to beginning of buffer"))
  8824. (setq org-link-search-failed nil)
  8825. (let* ((pos (point))
  8826. (ct (org-context))
  8827. (a (assq :link ct))
  8828. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8829. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8830. ((looking-at org-any-link-re)
  8831. ;; Don't stay stuck at link without an org-link face
  8832. (forward-char (if search-backward -1 1))))
  8833. (if (funcall srch-fun org-any-link-re nil t)
  8834. (progn
  8835. (goto-char (match-beginning 0))
  8836. (when (org-invisible-p) (org-show-context)))
  8837. (goto-char pos)
  8838. (setq org-link-search-failed t)
  8839. (message "No further link found"))))
  8840. (defun org-previous-link ()
  8841. "Move backward to the previous link.
  8842. If the link is in hidden text, expose it."
  8843. (interactive)
  8844. (funcall 'org-next-link t))
  8845. (defun org-translate-link (s)
  8846. "Translate a link string if a translation function has been defined."
  8847. (with-temp-buffer
  8848. (insert (org-trim s))
  8849. (org-trim (org-element-interpret-data (org-element-context)))))
  8850. (defun org-translate-link-from-planner (type path)
  8851. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8852. This is still an experimental function, your mileage may vary."
  8853. (cond
  8854. ((member type '("http" "https" "news" "ftp"))
  8855. ;; standard Internet links are the same.
  8856. nil)
  8857. ((and (equal type "irc") (string-match "^//" path))
  8858. ;; Planner has two / at the beginning of an irc link, we have 1.
  8859. ;; We should have zero, actually....
  8860. (setq path (substring path 1)))
  8861. ((and (equal type "lisp") (string-match "^/" path))
  8862. ;; Planner has a slash, we do not.
  8863. (setq type "elisp" path (substring path 1)))
  8864. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8865. ;; A typical message link. Planner has the id after the final slash,
  8866. ;; we separate it with a hash mark
  8867. (setq path (concat (match-string 1 path) "#"
  8868. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8869. (cons type path))
  8870. (defun org-find-file-at-mouse (ev)
  8871. "Open file link or URL at mouse."
  8872. (interactive "e")
  8873. (mouse-set-point ev)
  8874. (org-open-at-point 'in-emacs))
  8875. (defun org-open-at-mouse (ev)
  8876. "Open file link or URL at mouse.
  8877. See the docstring of `org-open-file' for details."
  8878. (interactive "e")
  8879. (mouse-set-point ev)
  8880. (when (eq major-mode 'org-agenda-mode)
  8881. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8882. (org-open-at-point))
  8883. (defvar org-window-config-before-follow-link nil
  8884. "The window configuration before following a link.
  8885. This is saved in case the need arises to restore it.")
  8886. ;;;###autoload
  8887. (defun org-open-at-point-global ()
  8888. "Follow a link or time-stamp like Org mode does.
  8889. This command can be called in any mode to follow an external link
  8890. or a time-stamp that has Org mode syntax. Its behavior is
  8891. undefined when called on internal links (e.g., fuzzy links).
  8892. Raise an error when there is nothing to follow. "
  8893. (interactive)
  8894. (cond ((org-in-regexp org-any-link-re)
  8895. (org-open-link-from-string (match-string-no-properties 0)))
  8896. ((or (org-in-regexp org-ts-regexp-both nil t)
  8897. (org-in-regexp org-tsr-regexp-both nil t))
  8898. (org-follow-timestamp-link))
  8899. (t (user-error "No link found"))))
  8900. ;;;###autoload
  8901. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8902. "Open a link in the string S, as if it was in Org mode."
  8903. (interactive "sLink: \nP")
  8904. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8905. (with-temp-buffer
  8906. (let ((org-inhibit-startup (not reference-buffer)))
  8907. (org-mode)
  8908. (insert s)
  8909. (goto-char (point-min))
  8910. (when reference-buffer
  8911. (setq org-link-abbrev-alist-local
  8912. (with-current-buffer reference-buffer
  8913. org-link-abbrev-alist-local)))
  8914. (org-open-at-point arg reference-buffer)))))
  8915. (defvar org-open-at-point-functions nil
  8916. "Hook that is run when following a link at point.
  8917. Functions in this hook must return t if they identify and follow
  8918. a link at point. If they don't find anything interesting at point,
  8919. they must return nil.")
  8920. (defvar org-link-search-inhibit-query nil)
  8921. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8922. (defun org--open-doi-link (path)
  8923. "Open a \"doi\" type link.
  8924. PATH is a the path to search for, as a string."
  8925. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8926. (defun org--open-elisp-link (path)
  8927. "Open a \"elisp\" type link.
  8928. PATH is the sexp to evaluate, as a string."
  8929. (let ((cmd path))
  8930. (if (or (and (org-string-nw-p
  8931. org-confirm-elisp-link-not-regexp)
  8932. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8933. (not org-confirm-elisp-link-function)
  8934. (funcall org-confirm-elisp-link-function
  8935. (format "Execute \"%s\" as elisp? "
  8936. (org-add-props cmd nil 'face 'org-warning))))
  8937. (message "%s => %s" cmd
  8938. (if (eq (string-to-char cmd) ?\()
  8939. (eval (read cmd))
  8940. (call-interactively (read cmd))))
  8941. (user-error "Abort"))))
  8942. (defun org--open-help-link (path)
  8943. "Open a \"help\" type link.
  8944. PATH is a symbol name, as a string."
  8945. (pcase (intern path)
  8946. ((and (pred fboundp) variable) (describe-function variable))
  8947. ((and (pred boundp) function) (describe-variable function))
  8948. (name (user-error "Unknown function or variable: %s" name))))
  8949. (defun org--open-shell-link (path)
  8950. "Open a \"shell\" type link.
  8951. PATH is the command to execute, as a string."
  8952. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  8953. (cmd path))
  8954. (if (or (and (org-string-nw-p
  8955. org-confirm-shell-link-not-regexp)
  8956. (string-match
  8957. org-confirm-shell-link-not-regexp cmd))
  8958. (not org-confirm-shell-link-function)
  8959. (funcall org-confirm-shell-link-function
  8960. (format "Execute \"%s\" in shell? "
  8961. (org-add-props cmd nil
  8962. 'face 'org-warning))))
  8963. (progn
  8964. (message "Executing %s" cmd)
  8965. (shell-command cmd buf)
  8966. (when (featurep 'midnight)
  8967. (setq clean-buffer-list-kill-buffer-names
  8968. (cons (buffer-name buf)
  8969. clean-buffer-list-kill-buffer-names))))
  8970. (user-error "Abort"))))
  8971. (defun org-open-at-point (&optional arg reference-buffer)
  8972. "Open link, timestamp, footnote or tags at point.
  8973. When point is on a link, follow it. Normally, files will be
  8974. opened by an appropriate application. If the optional prefix
  8975. argument ARG is non-nil, Emacs will visit the file. With
  8976. a double prefix argument, try to open outside of Emacs, in the
  8977. application the system uses for this file type.
  8978. When point is on a timestamp, open the agenda at the day
  8979. specified.
  8980. When point is a footnote definition, move to the first reference
  8981. found. If it is on a reference, move to the associated
  8982. definition.
  8983. When point is on a headline, display a list of every link in the
  8984. entry, so it is possible to pick one, or all, of them. If point
  8985. is on a tag, call `org-tags-view' instead.
  8986. When optional argument REFERENCE-BUFFER is non-nil, it should
  8987. specify a buffer from where the link search should happen. This
  8988. is used internally by `org-open-link-from-string'.
  8989. On top of syntactically correct links, this function will also
  8990. try to open links and time-stamps in comments, example
  8991. blocks... i.e., whenever point is on something looking like
  8992. a timestamp or a link."
  8993. (interactive "P")
  8994. ;; On a code block, open block's results.
  8995. (unless (call-interactively 'org-babel-open-src-block-result)
  8996. (org-load-modules-maybe)
  8997. (setq org-window-config-before-follow-link (current-window-configuration))
  8998. (org-remove-occur-highlights nil nil t)
  8999. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9000. (let* ((context
  9001. ;; Only consider supported types, even if they are not
  9002. ;; the closest one.
  9003. (org-element-lineage
  9004. (org-element-context)
  9005. '(clock footnote-definition footnote-reference headline
  9006. inlinetask link timestamp)
  9007. t))
  9008. (type (org-element-type context))
  9009. (value (org-element-property :value context)))
  9010. (cond
  9011. ;; On a headline or an inlinetask, but not on a timestamp,
  9012. ;; a link, a footnote reference.
  9013. ((memq type '(headline inlinetask))
  9014. (org-match-line org-complex-heading-regexp)
  9015. (if (and (match-beginning 5)
  9016. (>= (point) (match-beginning 5))
  9017. (< (point) (match-end 5)))
  9018. ;; On tags.
  9019. (org-tags-view arg (substring (match-string 5) 0 -1))
  9020. ;; Not on tags.
  9021. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9022. (`(nil . ,_)
  9023. (require 'org-attach)
  9024. (org-attach-reveal 'if-exists))
  9025. (`(,links . ,links-end)
  9026. (dolist (link (if (stringp links) (list links) links))
  9027. (search-forward link nil links-end)
  9028. (goto-char (match-beginning 0))
  9029. (org-open-at-point))))))
  9030. ;; On a footnote reference or at definition's label.
  9031. ((or (eq type 'footnote-reference)
  9032. (and (eq type 'footnote-definition)
  9033. (save-excursion
  9034. ;; Do not validate action when point is on the
  9035. ;; spaces right after the footnote label, in
  9036. ;; order to be on par with behavior on links.
  9037. (skip-chars-forward " \t")
  9038. (let ((begin
  9039. (org-element-property :contents-begin context)))
  9040. (if begin (< (point) begin)
  9041. (= (org-element-property :post-affiliated context)
  9042. (line-beginning-position)))))))
  9043. (org-footnote-action))
  9044. ;; No valid context. Ignore catch-all types like `headline'.
  9045. ;; If point is on something looking like a link or
  9046. ;; a time-stamp, try opening it. It may be useful in
  9047. ;; comments, example blocks...
  9048. ((memq type '(footnote-definition headline inlinetask nil))
  9049. (call-interactively #'org-open-at-point-global))
  9050. ;; On a clock line, make sure point is on the timestamp
  9051. ;; before opening it.
  9052. ((and (eq type 'clock)
  9053. value
  9054. (>= (point) (org-element-property :begin value))
  9055. (<= (point) (org-element-property :end value)))
  9056. (org-follow-timestamp-link))
  9057. ;; Do nothing on white spaces after an object.
  9058. ((>= (point)
  9059. (save-excursion
  9060. (goto-char (org-element-property :end context))
  9061. (skip-chars-backward " \t")
  9062. (point)))
  9063. (user-error "No link found"))
  9064. ((eq type 'timestamp) (org-follow-timestamp-link))
  9065. ((eq type 'link)
  9066. (let ((type (org-element-property :type context))
  9067. (path (org-link-unescape (org-element-property :path context))))
  9068. ;; Switch back to REFERENCE-BUFFER needed when called in
  9069. ;; a temporary buffer through `org-open-link-from-string'.
  9070. (with-current-buffer (or reference-buffer (current-buffer))
  9071. (cond
  9072. ((equal type "file")
  9073. (if (string-match "[*?{]" (file-name-nondirectory path))
  9074. (dired path)
  9075. ;; Look into `org-link-parameters' in order to find
  9076. ;; a DEDICATED-FUNCTION to open file. The function
  9077. ;; will be applied on raw link instead of parsed
  9078. ;; link due to the limitation in `org-add-link-type'
  9079. ;; ("open" function called with a single argument).
  9080. ;; If no such function is found, fallback to
  9081. ;; `org-open-file'.
  9082. (let* ((option (org-element-property :search-option context))
  9083. (app (org-element-property :application context))
  9084. (dedicated-function
  9085. (org-link-get-parameter
  9086. (if app (concat type "+" app) type)
  9087. :follow)))
  9088. (if dedicated-function
  9089. (funcall dedicated-function
  9090. (concat path
  9091. (and option (concat "::" option))))
  9092. (apply #'org-open-file
  9093. path
  9094. (cond (arg)
  9095. ((equal app "emacs") 'emacs)
  9096. ((equal app "sys") 'system))
  9097. (cond ((not option) nil)
  9098. ((string-match-p "\\`[0-9]+\\'" option)
  9099. (list (string-to-number option)))
  9100. (t (list nil
  9101. (org-link-unescape option)))))))))
  9102. ((functionp (org-link-get-parameter type :follow))
  9103. (funcall (org-link-get-parameter type :follow) path))
  9104. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9105. (unless (run-hook-with-args-until-success
  9106. 'org-open-link-functions path)
  9107. (if (not arg) (org-mark-ring-push)
  9108. (switch-to-buffer-other-window
  9109. (org-get-buffer-for-internal-link (current-buffer))))
  9110. (let ((destination
  9111. (org-with-wide-buffer
  9112. (if (equal type "radio")
  9113. (org-search-radio-target
  9114. (org-element-property :path context))
  9115. (org-link-search
  9116. (if (member type '("custom-id" "coderef"))
  9117. (org-element-property :raw-link context)
  9118. path)
  9119. ;; Prevent fuzzy links from matching
  9120. ;; themselves.
  9121. (and (equal type "fuzzy")
  9122. (+ 2 (org-element-property :begin context)))))
  9123. (point))))
  9124. (unless (and (<= (point-min) destination)
  9125. (>= (point-max) destination))
  9126. (widen))
  9127. (goto-char destination))))
  9128. (t (browse-url-at-point))))))
  9129. (t (user-error "No link found")))))
  9130. (run-hook-with-args 'org-follow-link-hook)))
  9131. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9132. "Offer links in the current entry and return the selected link.
  9133. If there is only one link, return it.
  9134. If NTH is an integer, return the NTH link found.
  9135. If ZERO is a string, check also this string for a link, and if
  9136. there is one, return it."
  9137. (with-current-buffer buffer
  9138. (org-with-wide-buffer
  9139. (goto-char marker)
  9140. (let ((cnt ?0)
  9141. have-zero end links link c)
  9142. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9143. (push (match-string 0 zero) links)
  9144. (setq cnt (1- cnt) have-zero t))
  9145. (save-excursion
  9146. (org-back-to-heading t)
  9147. (setq end (save-excursion (outline-next-heading) (point)))
  9148. (while (re-search-forward org-any-link-re end t)
  9149. (push (match-string 0) links))
  9150. (setq links (org-uniquify (reverse links))))
  9151. (cond
  9152. ((null links)
  9153. (message "No links"))
  9154. ((equal (length links) 1)
  9155. (setq link (car links)))
  9156. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9157. (setq link (nth (if have-zero nth (1- nth)) links)))
  9158. (t ; we have to select a link
  9159. (save-excursion
  9160. (save-window-excursion
  9161. (delete-other-windows)
  9162. (with-output-to-temp-buffer "*Select Link*"
  9163. (dolist (l links)
  9164. (cond
  9165. ((not (string-match org-bracket-link-regexp l))
  9166. (princ (format "[%c] %s\n" (cl-incf cnt)
  9167. (org-unbracket-string "<" ">" l))))
  9168. ((match-end 3)
  9169. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9170. (match-string 3 l) (match-string 1 l))))
  9171. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9172. (match-string 1 l)))))))
  9173. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9174. (message "Select link to open, RET to open all:")
  9175. (setq c (read-char-exclusive))
  9176. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9177. (when (equal c ?q) (user-error "Abort"))
  9178. (if (equal c ?\C-m)
  9179. (setq link links)
  9180. (setq nth (- c ?0))
  9181. (when have-zero (setq nth (1+ nth)))
  9182. (unless (and (integerp nth) (>= (length links) nth))
  9183. (user-error "Invalid link selection"))
  9184. (setq link (nth (1- nth) links)))))
  9185. (cons link end)))))
  9186. ;; TODO: These functions are deprecated since `org-open-at-point'
  9187. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9188. (defun org-open-file-with-system (path)
  9189. "Open file at PATH using the system way of opening it."
  9190. (org-open-file path 'system))
  9191. (defun org-open-file-with-emacs (path)
  9192. "Open file at PATH in Emacs."
  9193. (org-open-file path 'emacs))
  9194. ;;; File search
  9195. (defvar org-create-file-search-functions nil
  9196. "List of functions to construct the right search string for a file link.
  9197. These functions are called in turn with point at the location to
  9198. which the link should point.
  9199. A function in the hook should first test if it would like to
  9200. handle this file type, for example by checking the `major-mode'
  9201. or the file extension. If it decides not to handle this file, it
  9202. should just return nil to give other functions a chance. If it
  9203. does handle the file, it must return the search string to be used
  9204. when following the link. The search string will be part of the
  9205. file link, given after a double colon, and `org-open-at-point'
  9206. will automatically search for it. If special measures must be
  9207. taken to make the search successful, another function should be
  9208. added to the companion hook `org-execute-file-search-functions',
  9209. which see.
  9210. A function in this hook may also use `setq' to set the variable
  9211. `description' to provide a suggestion for the descriptive text to
  9212. be used for this link when it gets inserted into an Org buffer
  9213. with \\[org-insert-link].")
  9214. (defvar org-execute-file-search-functions nil
  9215. "List of functions to execute a file search triggered by a link.
  9216. Functions added to this hook must accept a single argument, the
  9217. search string that was part of the file link, the part after the
  9218. double colon. The function must first check if it would like to
  9219. handle this search, for example by checking the `major-mode' or
  9220. the file extension. If it decides not to handle this search, it
  9221. should just return nil to give other functions a chance. If it
  9222. does handle the search, it must return a non-nil value to keep
  9223. other functions from trying.
  9224. Each function can access the current prefix argument through the
  9225. variable `current-prefix-arg'. Note that a single prefix is used
  9226. to force opening a link in Emacs, so it may be good to only use a
  9227. numeric or double prefix to guide the search function.
  9228. In case this is needed, a function in this hook can also restore
  9229. the window configuration before `org-open-at-point' was called using:
  9230. (set-window-configuration org-window-config-before-follow-link)")
  9231. (defun org-search-radio-target (target)
  9232. "Search a radio target matching TARGET in current buffer.
  9233. White spaces are not significant."
  9234. (let ((re (format "<<<%s>>>"
  9235. (mapconcat #'regexp-quote
  9236. (split-string target)
  9237. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9238. (origin (point)))
  9239. (goto-char (point-min))
  9240. (catch :radio-match
  9241. (while (re-search-forward re nil t)
  9242. (backward-char)
  9243. (let ((object (org-element-context)))
  9244. (when (eq (org-element-type object) 'radio-target)
  9245. (goto-char (org-element-property :begin object))
  9246. (org-show-context 'link-search)
  9247. (throw :radio-match nil))))
  9248. (goto-char origin)
  9249. (user-error "No match for radio target: %s" target))))
  9250. (defun org-link-search (s &optional avoid-pos stealth)
  9251. "Search for a search string S.
  9252. If S starts with \"#\", it triggers a custom ID search.
  9253. If S is enclosed within parenthesis, it initiates a coderef
  9254. search.
  9255. If S is surrounded by forward slashes, it is interpreted as
  9256. a regular expression. In Org mode files, this will create an
  9257. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9258. to list matches. If the current buffer is in `dired-mode', grep
  9259. will be used to search in all files.
  9260. When AVOID-POS is given, ignore matches near that position.
  9261. When optional argument STEALTH is non-nil, do not modify
  9262. visibility around point, thus ignoring `org-show-context-detail'
  9263. variable.
  9264. Search is case-insensitive and ignores white spaces. Return type
  9265. of matched result, which is either `dedicated' or `fuzzy'."
  9266. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9267. (let* ((case-fold-search t)
  9268. (origin (point))
  9269. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9270. (starred (eq (string-to-char normalized) ?*))
  9271. (words (split-string (if starred (substring s 1) s)))
  9272. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9273. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9274. type)
  9275. (cond
  9276. ;; Check if there are any special search functions.
  9277. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9278. ((eq (string-to-char s) ?#)
  9279. ;; Look for a custom ID S if S starts with "#".
  9280. (let* ((id (substring normalized 1))
  9281. (match (org-find-property "CUSTOM_ID" id)))
  9282. (if match (progn (goto-char match) (setf type 'dedicated))
  9283. (error "No match for custom ID: %s" id))))
  9284. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9285. ;; Look for coderef targets if S is enclosed within parenthesis.
  9286. (let ((coderef (match-string-no-properties 1 normalized))
  9287. (re (substring s-single-re 1 -1)))
  9288. (goto-char (point-min))
  9289. (catch :coderef-match
  9290. (while (re-search-forward re nil t)
  9291. (let ((element (org-element-at-point)))
  9292. (when (and (memq (org-element-type element)
  9293. '(example-block src-block))
  9294. ;; Build proper regexp according to current
  9295. ;; block's label format.
  9296. (let ((label-fmt
  9297. (regexp-quote
  9298. (or (org-element-property :label-fmt element)
  9299. org-coderef-label-format))))
  9300. (save-excursion
  9301. (beginning-of-line)
  9302. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9303. (format label-fmt coderef))))))
  9304. (setq type 'dedicated)
  9305. (goto-char (match-beginning 1))
  9306. (throw :coderef-match nil))))
  9307. (goto-char origin)
  9308. (error "No match for coderef: %s" coderef))))
  9309. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9310. ;; Look for a regular expression.
  9311. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9312. (match-string 1 s)))
  9313. ;; From here, we handle fuzzy links.
  9314. ;;
  9315. ;; Look for targets, only if not in a headline search.
  9316. ((and (not starred)
  9317. (let ((target (format "<<%s>>" s-multi-re)))
  9318. (catch :target-match
  9319. (goto-char (point-min))
  9320. (while (re-search-forward target nil t)
  9321. (backward-char)
  9322. (let ((context (org-element-context)))
  9323. (when (eq (org-element-type context) 'target)
  9324. (setq type 'dedicated)
  9325. (goto-char (org-element-property :begin context))
  9326. (throw :target-match t))))
  9327. nil))))
  9328. ;; Look for elements named after S, only if not in a headline
  9329. ;; search.
  9330. ((and (not starred)
  9331. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9332. (catch :name-match
  9333. (goto-char (point-min))
  9334. (while (re-search-forward name nil t)
  9335. (let ((element (org-element-at-point)))
  9336. (when (equal words
  9337. (split-string
  9338. (org-element-property :name element)))
  9339. (setq type 'dedicated)
  9340. (beginning-of-line)
  9341. (throw :name-match t))))
  9342. nil))))
  9343. ;; Regular text search. Prefer headlines in Org mode buffers.
  9344. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9345. ;; statistics cookies and tags.
  9346. ((and (derived-mode-p 'org-mode)
  9347. (let ((title-re
  9348. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9349. org-outline-regexp-bol
  9350. org-comment-string
  9351. (mapconcat #'regexp-quote words ".+")))
  9352. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9353. (comment-re (eval-when-compile
  9354. (format "\\`%s[ \t]+" org-comment-string))))
  9355. (goto-char (point-min))
  9356. (catch :found
  9357. (while (re-search-forward title-re nil t)
  9358. (when (equal words
  9359. (split-string
  9360. (replace-regexp-in-string
  9361. cookie-re ""
  9362. (replace-regexp-in-string
  9363. comment-re "" (org-get-heading t t t)))))
  9364. (throw :found t)))
  9365. nil)))
  9366. (beginning-of-line)
  9367. (setq type 'dedicated))
  9368. ;; Offer to create non-existent headline depending on
  9369. ;; `org-link-search-must-match-exact-headline'.
  9370. ((and (derived-mode-p 'org-mode)
  9371. (not org-link-search-inhibit-query)
  9372. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9373. (yes-or-no-p "No match - create this as a new heading? "))
  9374. (goto-char (point-max))
  9375. (unless (bolp) (newline))
  9376. (org-insert-heading nil t t)
  9377. (insert s "\n")
  9378. (beginning-of-line 0))
  9379. ;; Only headlines are looked after. No need to process
  9380. ;; further: throw an error.
  9381. ((and (derived-mode-p 'org-mode)
  9382. (or starred org-link-search-must-match-exact-headline))
  9383. (goto-char origin)
  9384. (error "No match for fuzzy expression: %s" normalized))
  9385. ;; Regular text search.
  9386. ((catch :fuzzy-match
  9387. (goto-char (point-min))
  9388. (while (re-search-forward s-multi-re nil t)
  9389. ;; Skip match if it contains AVOID-POS or it is included in
  9390. ;; a link with a description but outside the description.
  9391. (unless (or (and avoid-pos
  9392. (<= (match-beginning 0) avoid-pos)
  9393. (> (match-end 0) avoid-pos))
  9394. (and (save-match-data
  9395. (org-in-regexp org-bracket-link-regexp))
  9396. (match-beginning 3)
  9397. (or (> (match-beginning 3) (point))
  9398. (<= (match-end 3) (point)))
  9399. (org-element-lineage
  9400. (save-match-data (org-element-context))
  9401. '(link) t)))
  9402. (goto-char (match-beginning 0))
  9403. (setq type 'fuzzy)
  9404. (throw :fuzzy-match t)))
  9405. nil))
  9406. ;; All failed. Throw an error.
  9407. (t (goto-char origin)
  9408. (error "No match for fuzzy expression: %s" normalized)))
  9409. ;; Disclose surroundings of match, if appropriate.
  9410. (when (and (derived-mode-p 'org-mode) (not stealth))
  9411. (org-show-context 'link-search))
  9412. type))
  9413. (defun org-get-buffer-for-internal-link (buffer)
  9414. "Return a buffer to be used for displaying the link target of internal links."
  9415. (cond
  9416. ((not org-display-internal-link-with-indirect-buffer)
  9417. buffer)
  9418. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9419. (message "Buffer is already a clone, not making another one")
  9420. ;; we also do not modify visibility in this case
  9421. buffer)
  9422. (t ; make a new indirect buffer for displaying the link
  9423. (let* ((bn (buffer-name buffer))
  9424. (ibn (concat bn "(Clone)"))
  9425. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9426. (with-current-buffer ib (org-overview))
  9427. ib))))
  9428. (defun org-do-occur (regexp &optional cleanup)
  9429. "Call the Emacs command `occur'.
  9430. If CLEANUP is non-nil, remove the printout of the regular expression
  9431. in the *Occur* buffer. This is useful if the regex is long and not useful
  9432. to read."
  9433. (occur regexp)
  9434. (when cleanup
  9435. (let ((cwin (selected-window)) win beg end)
  9436. (when (setq win (get-buffer-window "*Occur*"))
  9437. (select-window win))
  9438. (goto-char (point-min))
  9439. (when (re-search-forward "match[a-z]+" nil t)
  9440. (setq beg (match-end 0))
  9441. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9442. (setq end (1- (match-beginning 0)))))
  9443. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9444. (goto-char (point-min))
  9445. (select-window cwin))))
  9446. ;;; The Mark Ring
  9447. (defvar org-mark-ring nil
  9448. "Mark ring for positions before jumps in Org mode.")
  9449. (defvar org-mark-ring-last-goto nil
  9450. "Last position in the mark ring used to go back.")
  9451. ;; Fill and close the ring
  9452. (setq org-mark-ring nil)
  9453. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9454. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9455. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9456. org-mark-ring)
  9457. (defun org-mark-ring-push (&optional pos buffer)
  9458. "Put the current position into the mark ring and rotate it.
  9459. Also push position into the Emacs mark ring. If optional
  9460. argument POS and BUFFER are not nil, mark this location instead."
  9461. (interactive)
  9462. (let ((pos (or pos (point)))
  9463. (buffer (or buffer (current-buffer))))
  9464. (with-current-buffer buffer
  9465. (org-with-point-at pos (push-mark nil t)))
  9466. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9467. (move-marker (car org-mark-ring) pos buffer))
  9468. (message
  9469. (substitute-command-keys
  9470. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9471. (defun org-mark-ring-goto (&optional n)
  9472. "Jump to the previous position in the mark ring.
  9473. With prefix arg N, jump back that many stored positions. When
  9474. called several times in succession, walk through the entire ring.
  9475. Org mode commands jumping to a different position in the current file,
  9476. or to another Org file, automatically push the old position onto the ring."
  9477. (interactive "p")
  9478. (let (p m)
  9479. (if (eq last-command this-command)
  9480. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9481. (setq p org-mark-ring))
  9482. (setq org-mark-ring-last-goto p)
  9483. (setq m (car p))
  9484. (pop-to-buffer-same-window (marker-buffer m))
  9485. (goto-char m)
  9486. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9487. (defun org-add-angle-brackets (s)
  9488. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9489. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9490. s)
  9491. ;;; Following specific links
  9492. (defvar org-agenda-buffer-tmp-name)
  9493. (defvar org-agenda-start-on-weekday)
  9494. (defun org-follow-timestamp-link ()
  9495. "Open an agenda view for the time-stamp date/range at point."
  9496. (cond
  9497. ((org-at-date-range-p t)
  9498. (let ((org-agenda-start-on-weekday)
  9499. (t1 (match-string 1))
  9500. (t2 (match-string 2)) tt1 tt2)
  9501. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9502. tt2 (time-to-days (org-time-string-to-time t2)))
  9503. (let ((org-agenda-buffer-tmp-name
  9504. (format "*Org Agenda(a:%s)"
  9505. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9506. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9507. ((org-at-timestamp-p 'lax)
  9508. (let ((org-agenda-buffer-tmp-name
  9509. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9510. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9511. (substring (match-string 1) 0 10)))
  9512. 1)))
  9513. (t (error "This should not happen"))))
  9514. ;;; Following file links
  9515. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9516. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9517. (declare-function mailcap-mime-info
  9518. "mailcap" (string &optional request no-decode))
  9519. (defvar org-wait nil)
  9520. (defun org-open-file (path &optional in-emacs line search)
  9521. "Open the file at PATH.
  9522. First, this expands any special file name abbreviations. Then the
  9523. configuration variable `org-file-apps' is checked if it contains an
  9524. entry for this file type, and if yes, the corresponding command is launched.
  9525. If no application is found, Emacs simply visits the file.
  9526. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9527. With a double \\[universal-argument] \\[universal-argument] \
  9528. prefix arg, Org tries to avoid opening in Emacs
  9529. and to use an external application to visit the file.
  9530. Optional LINE specifies a line to go to, optional SEARCH a string
  9531. to search for. If LINE or SEARCH is given, the file will be
  9532. opened in Emacs, unless an entry from org-file-apps that makes
  9533. use of groups in a regexp matches.
  9534. If you want to change the way frames are used when following a
  9535. link, please customize `org-link-frame-setup'.
  9536. If the file does not exist, an error is thrown."
  9537. (let* ((file (if (equal path "")
  9538. buffer-file-name
  9539. (substitute-in-file-name (expand-file-name path))))
  9540. (file-apps (append org-file-apps (org-default-apps)))
  9541. (apps (cl-remove-if
  9542. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9543. (apps-dlink (cl-remove-if-not
  9544. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9545. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  9546. (dirp (unless remp (file-directory-p file)))
  9547. (file (if (and dirp org-open-directory-means-index-dot-org)
  9548. (concat (file-name-as-directory file) "index.org")
  9549. file))
  9550. (a-m-a-p (assq 'auto-mode apps))
  9551. (dfile (downcase file))
  9552. ;; Reconstruct the original link from the PATH, LINE and
  9553. ;; SEARCH args.
  9554. (link (cond (line (concat file "::" (number-to-string line)))
  9555. (search (concat file "::" search))
  9556. (t file)))
  9557. (dlink (downcase link))
  9558. (ext
  9559. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9560. (match-string 1 dfile)))
  9561. (save-position-maybe
  9562. (let ((old-buffer (current-buffer))
  9563. (old-pos (point))
  9564. (old-mode major-mode))
  9565. (lambda ()
  9566. (and (derived-mode-p 'org-mode)
  9567. (eq old-mode 'org-mode)
  9568. (or (not (eq old-buffer (current-buffer)))
  9569. (not (eq old-pos (point))))
  9570. (org-mark-ring-push old-pos old-buffer)))))
  9571. cmd link-match-data)
  9572. (cond
  9573. ((member in-emacs '((16) system))
  9574. (setq cmd (cdr (assq 'system apps))))
  9575. (in-emacs (setq cmd 'emacs))
  9576. (t
  9577. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9578. (and dirp (cdr (assq 'directory apps)))
  9579. ;; First, try matching against apps-dlink if we
  9580. ;; get a match here, store the match data for
  9581. ;; later.
  9582. (let ((match (assoc-default dlink apps-dlink
  9583. 'string-match)))
  9584. (if match
  9585. (progn (setq link-match-data (match-data))
  9586. match)
  9587. (progn (setq in-emacs (or in-emacs line search))
  9588. nil))) ; if we have no match in apps-dlink,
  9589. ; always open the file in emacs if line or search
  9590. ; is given (for backwards compatibility)
  9591. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9592. 'string-match)
  9593. (cdr (assoc ext apps))
  9594. (cdr (assq t apps))))))
  9595. (when (eq cmd 'system)
  9596. (setq cmd (cdr (assq 'system apps))))
  9597. (when (eq cmd 'default)
  9598. (setq cmd (cdr (assoc t apps))))
  9599. (when (eq cmd 'mailcap)
  9600. (require 'mailcap)
  9601. (mailcap-parse-mailcaps)
  9602. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9603. (command (mailcap-mime-info mime-type)))
  9604. (if (stringp command)
  9605. (setq cmd command)
  9606. (setq cmd 'emacs))))
  9607. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9608. (not (file-exists-p file))
  9609. (not org-open-non-existing-files))
  9610. (user-error "No such file: %s" file))
  9611. (cond
  9612. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9613. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9614. (while (string-match "['\"]%s['\"]" cmd)
  9615. (setq cmd (replace-match "%s" t t cmd)))
  9616. (setq cmd (replace-regexp-in-string
  9617. "%s"
  9618. (shell-quote-argument (convert-standard-filename file))
  9619. cmd
  9620. nil t))
  9621. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9622. (save-match-data
  9623. (let ((match-index 1)
  9624. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9625. (set-match-data link-match-data)
  9626. (while (<= match-index number-of-groups)
  9627. (let ((regex (concat "%" (number-to-string match-index)))
  9628. (replace-with (match-string match-index dlink)))
  9629. (while (string-match regex cmd)
  9630. (setq cmd (replace-match replace-with t t cmd))))
  9631. (setq match-index (+ match-index 1)))))
  9632. (save-window-excursion
  9633. (message "Running %s...done" cmd)
  9634. (start-process-shell-command cmd nil cmd)
  9635. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9636. ((or (stringp cmd)
  9637. (eq cmd 'emacs))
  9638. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9639. (widen)
  9640. (cond (line (org-goto-line line)
  9641. (when (derived-mode-p 'org-mode) (org-reveal)))
  9642. (search (condition-case err
  9643. (org-link-search search)
  9644. ;; Save position before error-ing out so user
  9645. ;; can easily move back to the original buffer.
  9646. (error (funcall save-position-maybe)
  9647. (error (nth 1 err)))))))
  9648. ((functionp cmd)
  9649. (save-match-data
  9650. (set-match-data link-match-data)
  9651. (condition-case nil
  9652. (funcall cmd file link)
  9653. ;; FIXME: Remove this check when most default installations
  9654. ;; of Emacs have at least Org 9.0.
  9655. ((debug wrong-number-of-arguments wrong-type-argument
  9656. invalid-function)
  9657. (user-error "Please see Org News for version 9.0 about \
  9658. `org-file-apps'--Lisp error: %S" cmd)))))
  9659. ((consp cmd)
  9660. ;; FIXME: Remove this check when most default installations of
  9661. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9662. ;; fall back to `org-link-frame-setup' for an old usage of
  9663. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9664. (user-error "Please see Org News for version 9.0 about \
  9665. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9666. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9667. (funcall save-position-maybe)))
  9668. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9669. "This function returns non-nil if `entry' uses a regular
  9670. expression which should be matched against the whole link by
  9671. org-open-file.
  9672. It assumes that is the case when the entry uses a regular
  9673. expression which has at least one grouping construct and the
  9674. action is either a lisp form or a command string containing
  9675. `%1', i.e. using at least one subexpression match as a
  9676. parameter."
  9677. (let ((selector (car entry))
  9678. (action (cdr entry)))
  9679. (if (stringp selector)
  9680. (and (> (regexp-opt-depth selector) 0)
  9681. (or (and (stringp action)
  9682. (string-match "%[0-9]" action))
  9683. (consp action)))
  9684. nil)))
  9685. (defun org-default-apps ()
  9686. "Return the default applications for this operating system."
  9687. (cond
  9688. ((eq system-type 'darwin)
  9689. org-file-apps-defaults-macosx)
  9690. ((eq system-type 'windows-nt)
  9691. org-file-apps-defaults-windowsnt)
  9692. (t org-file-apps-defaults-gnu)))
  9693. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9694. "Convert extensions to regular expressions in the cars of LIST.
  9695. Also, weed out any non-string entries, because the return value is used
  9696. only for regexp matching.
  9697. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9698. point to the symbol `emacs', indicating that the file should
  9699. be opened in Emacs."
  9700. (append
  9701. (delq nil
  9702. (mapcar (lambda (x)
  9703. (unless (not (stringp (car x)))
  9704. (if (string-match "\\W" (car x))
  9705. x
  9706. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9707. list))
  9708. (when add-auto-mode
  9709. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9710. (defvar ange-ftp-name-format)
  9711. (defun org-file-remote-p (file)
  9712. "Test whether FILE specifies a location on a remote system.
  9713. Return non-nil if the location is indeed remote.
  9714. For example, the filename \"/user@host:/foo\" specifies a location
  9715. on the system \"/user@host:\"."
  9716. (cond ((fboundp 'file-remote-p)
  9717. (file-remote-p file))
  9718. ((fboundp 'tramp-handle-file-remote-p)
  9719. (tramp-handle-file-remote-p file))
  9720. ((and (boundp 'ange-ftp-name-format)
  9721. (string-match (car ange-ftp-name-format) file))
  9722. t)))
  9723. ;;;; Refiling
  9724. (defun org-get-org-file ()
  9725. "Read a filename, with default directory `org-directory'."
  9726. (let ((default (or org-default-notes-file remember-data-file)))
  9727. (read-file-name (format "File name [%s]: " default)
  9728. (file-name-as-directory org-directory)
  9729. default)))
  9730. (defun org-notes-order-reversed-p ()
  9731. "Check if the current file should receive notes in reversed order."
  9732. (cond
  9733. ((not org-reverse-note-order) nil)
  9734. ((eq t org-reverse-note-order) t)
  9735. ((not (listp org-reverse-note-order)) nil)
  9736. (t (catch 'exit
  9737. (dolist (entry org-reverse-note-order)
  9738. (when (string-match (car entry) buffer-file-name)
  9739. (throw 'exit (cdr entry))))))))
  9740. (defvar org-refile-target-table nil
  9741. "The list of refile targets, created by `org-refile'.")
  9742. (defvar org-agenda-new-buffers nil
  9743. "Buffers created to visit agenda files.")
  9744. (defvar org-refile-cache nil
  9745. "Cache for refile targets.")
  9746. (defvar org-refile-markers nil
  9747. "All the markers used for caching refile locations.")
  9748. (defun org-refile-marker (pos)
  9749. "Get a new refile marker, but only if caching is in use."
  9750. (if (not org-refile-use-cache)
  9751. pos
  9752. (let ((m (make-marker)))
  9753. (move-marker m pos)
  9754. (push m org-refile-markers)
  9755. m)))
  9756. (defun org-refile-cache-clear ()
  9757. "Clear the refile cache and disable all the markers."
  9758. (dolist (m org-refile-markers) (move-marker m nil))
  9759. (setq org-refile-markers nil)
  9760. (setq org-refile-cache nil)
  9761. (message "Refile cache has been cleared"))
  9762. (defun org-refile-cache-check-set (set)
  9763. "Check if all the markers in the cache still have live buffers."
  9764. (let (marker)
  9765. (catch 'exit
  9766. (while (and set (setq marker (nth 3 (pop set))))
  9767. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9768. (when (and marker (null (marker-buffer marker)))
  9769. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9770. (sit-for 3)
  9771. (throw 'exit nil)))
  9772. t)))
  9773. (defun org-refile-cache-put (set &rest identifiers)
  9774. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9775. (let* ((key (sha1 (prin1-to-string identifiers)))
  9776. (entry (assoc key org-refile-cache)))
  9777. (if entry
  9778. (setcdr entry set)
  9779. (push (cons key set) org-refile-cache))))
  9780. (defun org-refile-cache-get (&rest identifiers)
  9781. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9782. (cond
  9783. ((not org-refile-cache) nil)
  9784. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9785. (t
  9786. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9787. org-refile-cache))))
  9788. (and set (org-refile-cache-check-set set) set)))))
  9789. (defvar org-outline-path-cache nil
  9790. "Alist between buffer positions and outline paths.
  9791. It value is an alist (POSITION . PATH) where POSITION is the
  9792. buffer position at the beginning of an entry and PATH is a list
  9793. of strings describing the outline path for that entry, in reverse
  9794. order.")
  9795. (defun org-refile-get-targets (&optional default-buffer)
  9796. "Produce a table with refile targets."
  9797. (let ((case-fold-search nil)
  9798. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9799. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9800. targets tgs files desc descre)
  9801. (message "Getting targets...")
  9802. (with-current-buffer (or default-buffer (current-buffer))
  9803. (dolist (entry entries)
  9804. (setq files (car entry) desc (cdr entry))
  9805. (cond
  9806. ((null files) (setq files (list (current-buffer))))
  9807. ((eq files 'org-agenda-files)
  9808. (setq files (org-agenda-files 'unrestricted)))
  9809. ((and (symbolp files) (fboundp files))
  9810. (setq files (funcall files)))
  9811. ((and (symbolp files) (boundp files))
  9812. (setq files (symbol-value files))))
  9813. (when (stringp files) (setq files (list files)))
  9814. (cond
  9815. ((eq (car desc) :tag)
  9816. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9817. ((eq (car desc) :todo)
  9818. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9819. ((eq (car desc) :regexp)
  9820. (setq descre (cdr desc)))
  9821. ((eq (car desc) :level)
  9822. (setq descre (concat "^\\*\\{" (number-to-string
  9823. (if org-odd-levels-only
  9824. (1- (* 2 (cdr desc)))
  9825. (cdr desc)))
  9826. "\\}[ \t]")))
  9827. ((eq (car desc) :maxlevel)
  9828. (setq descre (concat "^\\*\\{1," (number-to-string
  9829. (if org-odd-levels-only
  9830. (1- (* 2 (cdr desc)))
  9831. (cdr desc)))
  9832. "\\}[ \t]")))
  9833. (t (error "Bad refiling target description %s" desc)))
  9834. (dolist (f files)
  9835. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9836. (or
  9837. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9838. (progn
  9839. (when (bufferp f)
  9840. (setq f (buffer-file-name (buffer-base-buffer f))))
  9841. (setq f (and f (expand-file-name f)))
  9842. (when (eq org-refile-use-outline-path 'file)
  9843. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9844. (when (eq org-refile-use-outline-path 'buffer-name)
  9845. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9846. (when (eq org-refile-use-outline-path 'full-file-path)
  9847. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9848. (org-with-wide-buffer
  9849. (goto-char (point-min))
  9850. (setq org-outline-path-cache nil)
  9851. (while (re-search-forward descre nil t)
  9852. (beginning-of-line)
  9853. (let ((case-fold-search nil))
  9854. (looking-at org-complex-heading-regexp))
  9855. (let ((begin (point))
  9856. (heading (match-string-no-properties 4)))
  9857. (unless (or (and
  9858. org-refile-target-verify-function
  9859. (not
  9860. (funcall org-refile-target-verify-function)))
  9861. (not heading))
  9862. (let ((re (format org-complex-heading-regexp-format
  9863. (regexp-quote heading)))
  9864. (target
  9865. (if (not org-refile-use-outline-path) heading
  9866. (mapconcat
  9867. #'identity
  9868. (append
  9869. (pcase org-refile-use-outline-path
  9870. (`file (list (file-name-nondirectory
  9871. (buffer-file-name
  9872. (buffer-base-buffer)))))
  9873. (`full-file-path
  9874. (list (buffer-file-name
  9875. (buffer-base-buffer))))
  9876. (`buffer-name
  9877. (list (buffer-name
  9878. (buffer-base-buffer))))
  9879. (_ nil))
  9880. (mapcar (lambda (s) (replace-regexp-in-string
  9881. "/" "\\/" s nil t))
  9882. (org-get-outline-path t t)))
  9883. "/"))))
  9884. (push (list target f re (org-refile-marker (point)))
  9885. tgs)))
  9886. (when (= (point) begin)
  9887. ;; Verification function has not moved point.
  9888. (end-of-line)))))))
  9889. (when org-refile-use-cache
  9890. (org-refile-cache-put tgs (buffer-file-name) descre))
  9891. (setq targets (append tgs targets))))))
  9892. (message "Getting targets...done")
  9893. (delete-dups (nreverse targets))))
  9894. (defun org--get-outline-path-1 (&optional use-cache)
  9895. "Return outline path to current headline.
  9896. Outline path is a list of strings, in reverse order. When
  9897. optional argument USE-CACHE is non-nil, make use of a cache. See
  9898. `org-get-outline-path' for details.
  9899. Assume buffer is widened and point is on a headline."
  9900. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9901. (let ((p (point))
  9902. (heading (let ((case-fold-search nil))
  9903. (looking-at org-complex-heading-regexp)
  9904. (if (not (match-end 4)) ""
  9905. ;; Remove statistics cookies.
  9906. (org-trim
  9907. (org-link-display-format
  9908. (replace-regexp-in-string
  9909. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9910. (match-string-no-properties 4))))))))
  9911. (if (org-up-heading-safe)
  9912. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9913. (when use-cache
  9914. (push (cons p path) org-outline-path-cache))
  9915. path)
  9916. ;; This is a new root node. Since we assume we are moving
  9917. ;; forward, we can drop previous cache so as to limit number
  9918. ;; of associations there.
  9919. (let ((path (list heading)))
  9920. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9921. path)))))
  9922. (defun org-get-outline-path (&optional with-self use-cache)
  9923. "Return the outline path to the current entry.
  9924. An outline path is a list of ancestors for current headline, as
  9925. a list of strings. Statistics cookies are removed and links are
  9926. replaced with their description, if any, or their path otherwise.
  9927. When optional argument WITH-SELF is non-nil, the path also
  9928. includes the current headline.
  9929. When optional argument USE-CACHE is non-nil, cache outline paths
  9930. between calls to this function so as to avoid backtracking. This
  9931. argument is useful when planning to find more than one outline
  9932. path in the same document. In that case, there are two
  9933. conditions to satisfy:
  9934. - `org-outline-path-cache' is set to nil before starting the
  9935. process;
  9936. - outline paths are computed by increasing buffer positions."
  9937. (org-with-wide-buffer
  9938. (and (or (and with-self (org-back-to-heading t))
  9939. (org-up-heading-safe))
  9940. (reverse (org--get-outline-path-1 use-cache)))))
  9941. (defun org-format-outline-path (path &optional width prefix separator)
  9942. "Format the outline path PATH for display.
  9943. WIDTH is the maximum number of characters that is available.
  9944. PREFIX is a prefix to be included in the returned string,
  9945. such as the file name.
  9946. SEPARATOR is inserted between the different parts of the path,
  9947. the default is \"/\"."
  9948. (setq width (or width 79))
  9949. (setq path (delq nil path))
  9950. (unless (> width 0)
  9951. (user-error "Argument `width' must be positive"))
  9952. (setq separator (or separator "/"))
  9953. (let* ((org-odd-levels-only nil)
  9954. (fpath (concat
  9955. prefix (and prefix path separator)
  9956. (mapconcat
  9957. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  9958. (cl-loop for head in path
  9959. for n from 0
  9960. collect (org-add-props
  9961. head nil 'face
  9962. (nth (% n org-n-level-faces) org-level-faces)))
  9963. separator))))
  9964. (when (> (length fpath) width)
  9965. (if (< width 7)
  9966. ;; It's unlikely that `width' will be this small, but don't
  9967. ;; waste characters by adding ".." if it is.
  9968. (setq fpath (substring fpath 0 width))
  9969. (setf (substring fpath (- width 2)) "..")))
  9970. fpath))
  9971. (defun org-display-outline-path (&optional file current separator just-return-string)
  9972. "Display the current outline path in the echo area.
  9973. If FILE is non-nil, prepend the output with the file name.
  9974. If CURRENT is non-nil, append the current heading to the output.
  9975. SEPARATOR is passed through to `org-format-outline-path'. It separates
  9976. the different parts of the path and defaults to \"/\".
  9977. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  9978. (interactive "P")
  9979. (let* (case-fold-search
  9980. (bfn (buffer-file-name (buffer-base-buffer)))
  9981. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  9982. res)
  9983. (when current (setq path (append path
  9984. (save-excursion
  9985. (org-back-to-heading t)
  9986. (when (looking-at org-complex-heading-regexp)
  9987. (list (match-string 4)))))))
  9988. (setq res
  9989. (org-format-outline-path
  9990. path
  9991. (1- (frame-width))
  9992. (and file bfn (concat (file-name-nondirectory bfn) separator))
  9993. separator))
  9994. (if just-return-string
  9995. (org-no-properties res)
  9996. (org-unlogged-message "%s" res))))
  9997. (defvar org-refile-history nil
  9998. "History for refiling operations.")
  9999. (defvar org-after-refile-insert-hook nil
  10000. "Hook run after `org-refile' has inserted its stuff at the new location.
  10001. Note that this is still *before* the stuff will be removed from
  10002. the *old* location.")
  10003. (defvar org-capture-last-stored-marker)
  10004. (defvar org-refile-keep nil
  10005. "Non-nil means `org-refile' will copy instead of refile.")
  10006. (defun org-copy ()
  10007. "Like `org-refile', but copy."
  10008. (interactive)
  10009. (let ((org-refile-keep t))
  10010. (funcall 'org-refile nil nil nil "Copy")))
  10011. (defun org-refile (&optional arg default-buffer rfloc msg)
  10012. "Move the entry or entries at point to another heading.
  10013. The list of target headings is compiled using the information in
  10014. `org-refile-targets', which see.
  10015. At the target location, the entry is filed as a subitem of the
  10016. target heading. Depending on `org-reverse-note-order', the new
  10017. subitem will either be the first or the last subitem.
  10018. If there is an active region, all entries in that region will be
  10019. refiled. However, the region must fulfill the requirement that
  10020. the first heading sets the top-level of the moved text.
  10021. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10022. location
  10023. and not actually move anything.
  10024. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10025. location where the last
  10026. refiling operation has put the subtree.
  10027. With a numeric prefix argument of `2', refile to the running clock.
  10028. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10029. being set to t and copy to the target location, don't move it.
  10030. Beware that keeping refiled entries may result in duplicated ID
  10031. properties.
  10032. RFLOC can be a refile location obtained in a different way.
  10033. MSG is a string to replace \"Refile\" in the default prompt with
  10034. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10035. See also `org-refile-use-outline-path'.
  10036. If you are using target caching (see `org-refile-use-cache'), you
  10037. have to clear the target cache in order to find new targets.
  10038. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10039. prefix argument (`C-u C-u C-u C-c C-w')."
  10040. (interactive "P")
  10041. (if (member arg '(0 (64)))
  10042. (org-refile-cache-clear)
  10043. (let* ((actionmsg (cond (msg msg)
  10044. ((equal arg 3) "Refile (and keep)")
  10045. (t "Refile")))
  10046. (regionp (org-region-active-p))
  10047. (region-start (and regionp (region-beginning)))
  10048. (region-end (and regionp (region-end)))
  10049. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10050. pos it nbuf file level reversed)
  10051. (setq last-command nil)
  10052. (when regionp
  10053. (goto-char region-start)
  10054. (or (bolp) (goto-char (point-at-bol)))
  10055. (setq region-start (point))
  10056. (unless (or (org-kill-is-subtree-p
  10057. (buffer-substring region-start region-end))
  10058. (prog1 org-refile-active-region-within-subtree
  10059. (let ((s (point-at-eol)))
  10060. (org-toggle-heading)
  10061. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10062. (user-error "The region is not a (sequence of) subtree(s)")))
  10063. (if (equal arg '(16))
  10064. (org-refile-goto-last-stored)
  10065. (when (or
  10066. (and (equal arg 2)
  10067. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10068. (prog1
  10069. (setq it (list (or org-clock-heading "running clock")
  10070. (buffer-file-name
  10071. (marker-buffer org-clock-hd-marker))
  10072. ""
  10073. (marker-position org-clock-hd-marker)))
  10074. (setq arg nil)))
  10075. (setq it
  10076. (or rfloc
  10077. (let (heading-text)
  10078. (save-excursion
  10079. (unless (and arg (listp arg))
  10080. (org-back-to-heading t)
  10081. (setq heading-text
  10082. (replace-regexp-in-string
  10083. org-bracket-link-regexp
  10084. "\\3"
  10085. (or (nth 4 (org-heading-components))
  10086. ""))))
  10087. (org-refile-get-location
  10088. (cond ((and arg (listp arg)) "Goto")
  10089. (regionp (concat actionmsg " region to"))
  10090. (t (concat actionmsg " subtree \""
  10091. heading-text "\" to")))
  10092. default-buffer
  10093. (and (not (equal '(4) arg))
  10094. org-refile-allow-creating-parent-nodes)))))))
  10095. (setq file (nth 1 it)
  10096. pos (nth 3 it))
  10097. (when (and (not arg)
  10098. pos
  10099. (equal (buffer-file-name) file)
  10100. (if regionp
  10101. (and (>= pos region-start)
  10102. (<= pos region-end))
  10103. (and (>= pos (point))
  10104. (< pos (save-excursion
  10105. (org-end-of-subtree t t))))))
  10106. (error "Cannot refile to position inside the tree or region"))
  10107. (setq nbuf (or (find-buffer-visiting file)
  10108. (find-file-noselect file)))
  10109. (if (and arg (not (equal arg 3)))
  10110. (progn
  10111. (pop-to-buffer-same-window nbuf)
  10112. (goto-char (cond (pos)
  10113. ((org-notes-order-reversed-p) (point-min))
  10114. (t (point-max))))
  10115. (org-show-context 'org-goto))
  10116. (if regionp
  10117. (progn
  10118. (org-kill-new (buffer-substring region-start region-end))
  10119. (org-save-markers-in-region region-start region-end))
  10120. (org-copy-subtree 1 nil t))
  10121. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10122. (find-file-noselect file)))
  10123. (setq reversed (org-notes-order-reversed-p))
  10124. (org-with-wide-buffer
  10125. (if pos
  10126. (progn
  10127. (goto-char pos)
  10128. (setq level (org-get-valid-level (funcall outline-level) 1))
  10129. (goto-char
  10130. (if reversed
  10131. (or (outline-next-heading) (point-max))
  10132. (or (save-excursion (org-get-next-sibling))
  10133. (org-end-of-subtree t t)
  10134. (point-max)))))
  10135. (setq level 1)
  10136. (if (not reversed)
  10137. (goto-char (point-max))
  10138. (goto-char (point-min))
  10139. (or (outline-next-heading) (goto-char (point-max)))))
  10140. (unless (bolp) (newline))
  10141. (org-paste-subtree level nil nil t)
  10142. (when org-log-refile
  10143. (org-add-log-setup 'refile nil nil org-log-refile)
  10144. (unless (eq org-log-refile 'note)
  10145. (save-excursion (org-add-log-note))))
  10146. (and org-auto-align-tags
  10147. (let ((org-loop-over-headlines-in-active-region nil))
  10148. (org-set-tags nil t)))
  10149. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10150. :last-refile)))
  10151. (when bookmark-name
  10152. (with-demoted-errors
  10153. (bookmark-set bookmark-name))))
  10154. ;; If we are refiling for capture, make sure that the
  10155. ;; last-capture pointers point here
  10156. (when (bound-and-true-p org-capture-is-refiling)
  10157. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10158. :last-capture-marker)))
  10159. (when bookmark-name
  10160. (with-demoted-errors
  10161. (bookmark-set bookmark-name))))
  10162. (move-marker org-capture-last-stored-marker (point)))
  10163. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10164. (run-hooks 'org-after-refile-insert-hook)))
  10165. (unless org-refile-keep
  10166. (if regionp
  10167. (delete-region (point) (+ (point) (- region-end region-start)))
  10168. (org-preserve-local-variables
  10169. (delete-region
  10170. (and (org-back-to-heading t) (point))
  10171. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10172. (when (featurep 'org-inlinetask)
  10173. (org-inlinetask-remove-END-maybe))
  10174. (setq org-markers-to-move nil)
  10175. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10176. (defun org-refile-goto-last-stored ()
  10177. "Go to the location where the last refile was stored."
  10178. (interactive)
  10179. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10180. (message "This is the location of the last refile"))
  10181. (defun org-refile--get-location (refloc tbl)
  10182. "When user refile to REFLOC, find the associated target in TBL.
  10183. Also check `org-refile-target-table'."
  10184. (car (delq
  10185. nil
  10186. (mapcar
  10187. (lambda (r) (or (assoc r tbl)
  10188. (assoc r org-refile-target-table)))
  10189. (list (replace-regexp-in-string "/$" "" refloc)
  10190. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10191. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10192. "Prompt the user for a refile location, using PROMPT.
  10193. PROMPT should not be suffixed with a colon and a space, because
  10194. this function appends the default value from
  10195. `org-refile-history' automatically, if that is not empty."
  10196. (let ((org-refile-targets org-refile-targets)
  10197. (org-refile-use-outline-path org-refile-use-outline-path))
  10198. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10199. (unless org-refile-target-table
  10200. (user-error "No refile targets"))
  10201. (let* ((cbuf (current-buffer))
  10202. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10203. (cfunc (if (and org-refile-use-outline-path
  10204. org-outline-path-complete-in-steps)
  10205. #'org-olpath-completing-read
  10206. #'completing-read))
  10207. (extra (if org-refile-use-outline-path "/" ""))
  10208. (cbnex (concat (buffer-name) extra))
  10209. (filename (and cfn (expand-file-name cfn)))
  10210. (tbl (mapcar
  10211. (lambda (x)
  10212. (if (and (not (member org-refile-use-outline-path
  10213. '(file full-file-path)))
  10214. (not (equal filename (nth 1 x))))
  10215. (cons (concat (car x) extra " ("
  10216. (file-name-nondirectory (nth 1 x)) ")")
  10217. (cdr x))
  10218. (cons (concat (car x) extra) (cdr x))))
  10219. org-refile-target-table))
  10220. (completion-ignore-case t)
  10221. cdef
  10222. (prompt (concat prompt
  10223. (or (and (car org-refile-history)
  10224. (concat " (default " (car org-refile-history) ")"))
  10225. (and (assoc cbnex tbl) (setq cdef cbnex)
  10226. (concat " (default " cbnex ")"))) ": "))
  10227. pa answ parent-target child parent old-hist)
  10228. (setq old-hist org-refile-history)
  10229. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10230. nil 'org-refile-history (or cdef (car org-refile-history))))
  10231. (if (setq pa (org-refile--get-location answ tbl))
  10232. (progn
  10233. (org-refile-check-position pa)
  10234. (when (or (not org-refile-history)
  10235. (not (eq old-hist org-refile-history))
  10236. (not (equal (car pa) (car org-refile-history))))
  10237. (setq org-refile-history
  10238. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10239. org-refile-history
  10240. (cdr org-refile-history))))
  10241. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10242. (pop org-refile-history)))
  10243. pa)
  10244. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10245. (progn
  10246. (setq parent (match-string 1 answ)
  10247. child (match-string 2 answ))
  10248. (setq parent-target (org-refile--get-location parent tbl))
  10249. (when (and parent-target
  10250. (or (eq new-nodes t)
  10251. (and (eq new-nodes 'confirm)
  10252. (y-or-n-p (format "Create new node \"%s\"? "
  10253. child)))))
  10254. (org-refile-new-child parent-target child)))
  10255. (user-error "Invalid target location")))))
  10256. (declare-function org-string-nw-p "org-macs" (s))
  10257. (defun org-refile-check-position (refile-pointer)
  10258. "Check if the refile pointer matches the headline to which it points."
  10259. (let* ((file (nth 1 refile-pointer))
  10260. (re (nth 2 refile-pointer))
  10261. (pos (nth 3 refile-pointer))
  10262. buffer)
  10263. (if (and (not (markerp pos)) (not file))
  10264. (user-error "Please indicate a target file in the refile path")
  10265. (when (org-string-nw-p re)
  10266. (setq buffer (if (markerp pos)
  10267. (marker-buffer pos)
  10268. (or (find-buffer-visiting file)
  10269. (find-file-noselect file))))
  10270. (with-current-buffer buffer
  10271. (org-with-wide-buffer
  10272. (goto-char pos)
  10273. (beginning-of-line 1)
  10274. (unless (looking-at-p re)
  10275. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10276. (defun org-refile-new-child (parent-target child)
  10277. "Use refile target PARENT-TARGET to add new CHILD below it."
  10278. (unless parent-target
  10279. (error "Cannot find parent for new node"))
  10280. (let ((file (nth 1 parent-target))
  10281. (pos (nth 3 parent-target))
  10282. level)
  10283. (with-current-buffer (or (find-buffer-visiting file)
  10284. (find-file-noselect file))
  10285. (org-with-wide-buffer
  10286. (if pos
  10287. (goto-char pos)
  10288. (goto-char (point-max))
  10289. (unless (bolp) (newline)))
  10290. (when (looking-at org-outline-regexp)
  10291. (setq level (funcall outline-level))
  10292. (org-end-of-subtree t t))
  10293. (org-back-over-empty-lines)
  10294. (insert "\n" (make-string
  10295. (if pos (org-get-valid-level level 1) 1) ?*)
  10296. " " child "\n")
  10297. (beginning-of-line 0)
  10298. (list (concat (car parent-target) "/" child) file "" (point))))))
  10299. (defun org-olpath-completing-read (prompt collection &rest args)
  10300. "Read an outline path like a file name."
  10301. (let ((thetable collection))
  10302. (apply #'completing-read
  10303. prompt
  10304. (lambda (string predicate &optional flag)
  10305. (cond
  10306. ((eq flag nil) (try-completion string thetable))
  10307. ((eq flag t)
  10308. (let ((l (length string)))
  10309. (mapcar (lambda (x)
  10310. (let ((r (substring x l))
  10311. (f (if (string-match " ([^)]*)$" x)
  10312. (match-string 0 x)
  10313. "")))
  10314. (if (string-match "/" r)
  10315. (concat string (substring r 0 (match-end 0)) f)
  10316. x)))
  10317. (all-completions string thetable predicate))))
  10318. ;; Exact match?
  10319. ((eq flag 'lambda) (assoc string thetable))))
  10320. args)))
  10321. ;;;; Dynamic blocks
  10322. (defun org-find-dblock (name)
  10323. "Find the first dynamic block with name NAME in the buffer.
  10324. If not found, stay at current position and return nil."
  10325. (let ((case-fold-search t) pos)
  10326. (save-excursion
  10327. (goto-char (point-min))
  10328. (setq pos (and (re-search-forward
  10329. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10330. (match-beginning 0))))
  10331. (when pos (goto-char pos))
  10332. pos))
  10333. (defun org-create-dblock (plist)
  10334. "Create a dynamic block section, with parameters taken from PLIST.
  10335. PLIST must contain a :name entry which is used as the name of the block."
  10336. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10337. (end-of-line 1)
  10338. (newline))
  10339. (let ((col (current-column))
  10340. (name (plist-get plist :name)))
  10341. (insert "#+BEGIN: " name)
  10342. (while plist
  10343. (if (eq (car plist) :name)
  10344. (setq plist (cddr plist))
  10345. (insert " " (prin1-to-string (pop plist)))))
  10346. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10347. (beginning-of-line -2)))
  10348. (defun org-prepare-dblock ()
  10349. "Prepare dynamic block for refresh.
  10350. This empties the block, puts the cursor at the insert position and returns
  10351. the property list including an extra property :name with the block name."
  10352. (unless (looking-at org-dblock-start-re)
  10353. (user-error "Not at a dynamic block"))
  10354. (let* ((begdel (1+ (match-end 0)))
  10355. (name (org-no-properties (match-string 1)))
  10356. (params (append (list :name name)
  10357. (read (concat "(" (match-string 3) ")")))))
  10358. (save-excursion
  10359. (beginning-of-line 1)
  10360. (skip-chars-forward " \t")
  10361. (setq params (plist-put params :indentation-column (current-column))))
  10362. (unless (re-search-forward org-dblock-end-re nil t)
  10363. (error "Dynamic block not terminated"))
  10364. (setq params
  10365. (append params
  10366. (list :content (buffer-substring
  10367. begdel (match-beginning 0)))))
  10368. (delete-region begdel (match-beginning 0))
  10369. (goto-char begdel)
  10370. (open-line 1)
  10371. params))
  10372. (defun org-map-dblocks (&optional command)
  10373. "Apply COMMAND to all dynamic blocks in the current buffer.
  10374. If COMMAND is not given, use `org-update-dblock'."
  10375. (let ((cmd (or command 'org-update-dblock)))
  10376. (save-excursion
  10377. (goto-char (point-min))
  10378. (while (re-search-forward org-dblock-start-re nil t)
  10379. (goto-char (match-beginning 0))
  10380. (save-excursion
  10381. (condition-case nil
  10382. (funcall cmd)
  10383. (error (message "Error during update of dynamic block"))))
  10384. (unless (re-search-forward org-dblock-end-re nil t)
  10385. (error "Dynamic block not terminated"))))))
  10386. (defun org-dblock-update (&optional arg)
  10387. "User command for updating dynamic blocks.
  10388. Update the dynamic block at point. With prefix ARG, update all dynamic
  10389. blocks in the buffer."
  10390. (interactive "P")
  10391. (if arg
  10392. (org-update-all-dblocks)
  10393. (or (looking-at org-dblock-start-re)
  10394. (org-beginning-of-dblock))
  10395. (org-update-dblock)))
  10396. (defun org-update-dblock ()
  10397. "Update the dynamic block at point.
  10398. This means to empty the block, parse for parameters and then call
  10399. the correct writing function."
  10400. (interactive)
  10401. (save-excursion
  10402. (let* ((win (selected-window))
  10403. (pos (point))
  10404. (line (org-current-line))
  10405. (params (org-prepare-dblock))
  10406. (name (plist-get params :name))
  10407. (indent (plist-get params :indentation-column))
  10408. (cmd (intern (concat "org-dblock-write:" name))))
  10409. (message "Updating dynamic block `%s' at line %d..." name line)
  10410. (funcall cmd params)
  10411. (message "Updating dynamic block `%s' at line %d...done" name line)
  10412. (goto-char pos)
  10413. (when (and indent (> indent 0))
  10414. (setq indent (make-string indent ?\ ))
  10415. (save-excursion
  10416. (select-window win)
  10417. (org-beginning-of-dblock)
  10418. (forward-line 1)
  10419. (while (not (looking-at org-dblock-end-re))
  10420. (insert indent)
  10421. (beginning-of-line 2))
  10422. (when (looking-at org-dblock-end-re)
  10423. (and (looking-at "[ \t]+")
  10424. (replace-match ""))
  10425. (insert indent)))))))
  10426. (defun org-beginning-of-dblock ()
  10427. "Find the beginning of the dynamic block at point.
  10428. Error if there is no such block at point."
  10429. (let ((pos (point))
  10430. beg)
  10431. (end-of-line 1)
  10432. (if (and (re-search-backward org-dblock-start-re nil t)
  10433. (setq beg (match-beginning 0))
  10434. (re-search-forward org-dblock-end-re nil t)
  10435. (> (match-end 0) pos))
  10436. (goto-char beg)
  10437. (goto-char pos)
  10438. (error "Not in a dynamic block"))))
  10439. (defun org-update-all-dblocks ()
  10440. "Update all dynamic blocks in the buffer.
  10441. This function can be used in a hook."
  10442. (interactive)
  10443. (when (derived-mode-p 'org-mode)
  10444. (org-map-dblocks 'org-update-dblock)))
  10445. ;;;; Completion
  10446. (declare-function org-export-backend-options "ox" (cl-x) t)
  10447. (defun org-get-export-keywords ()
  10448. "Return a list of all currently understood export keywords.
  10449. Export keywords include options, block names, attributes and
  10450. keywords relative to each registered export back-end."
  10451. (let (keywords)
  10452. (dolist (backend
  10453. (bound-and-true-p org-export-registered-backends)
  10454. (delq nil keywords))
  10455. ;; Back-end name (for keywords, like #+LATEX:)
  10456. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10457. (dolist (option-entry (org-export-backend-options backend))
  10458. ;; Back-end options.
  10459. (push (nth 1 option-entry) keywords)))))
  10460. (defconst org-options-keywords
  10461. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10462. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10463. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10464. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10465. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10466. (defcustom org-structure-template-alist
  10467. '(("a" . "export ascii")
  10468. ("c" . "center")
  10469. ("C" . "comment")
  10470. ("e" . "example")
  10471. ("E" . "export")
  10472. ("h" . "export html")
  10473. ("l" . "export latex")
  10474. ("q" . "quote")
  10475. ("s" . "src")
  10476. ("v" . "verse"))
  10477. "Structure completion elements.
  10478. This is an alist of keys and block types. With
  10479. `org-insert-structure-template' a block can be inserted through a
  10480. menu. The block type is inserted, with \"#+BEGIN_\" and
  10481. \"#+END_\" added automatically. The menukeys are determined
  10482. based on the key elements in the `org-structure-template-alist'.
  10483. If two entries have the keys \"a\" and \"aa\" respectively, the
  10484. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10485. latter will be inserted by typing \"aa\". If an entry with the
  10486. key \"aab\" is later added it would be inserted by typing \"ab\".
  10487. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10488. block can be inserted by pressing TAB after the string \"<KEY\".
  10489. "
  10490. :group 'org-edit-structure
  10491. :type '(repeat
  10492. (cons (string :tag "Key")
  10493. (string :tag "Template")))
  10494. :package-version '(Org . "9.2"))
  10495. (defun org--insert-structure-template-mks ()
  10496. "Present `org-structure-template-alist' with `org-mks'.
  10497. Menus are added if keys require more than one keystroke.
  10498. Tabs are added to single key entires when needing more than one stroke.
  10499. Keys longer than two characters are reduced to two characters."
  10500. (let* (case-fold-search
  10501. (templates (append org-structure-template-alist
  10502. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10503. (keys (mapcar #'car templates))
  10504. (start-letters (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10505. ;; Sort each element of `org-structure-template-alist' into
  10506. ;; sublists according to the first letter.
  10507. (superlist (mapcar (lambda (letter)
  10508. (list letter
  10509. (cl-remove-if-not
  10510. (apply-partially #'string-match-p (concat "^" letter))
  10511. templates :key #'car)))
  10512. start-letters)))
  10513. (org-mks
  10514. (apply #'append
  10515. ;; Make an `org-mks' table. If only one element is
  10516. ;; present in a sublist, make it part of the top-menu,
  10517. ;; otherwise make a submenu according to the starting
  10518. ;; letter and populate it.
  10519. (mapcar (lambda (sublist)
  10520. (if (eq 1 (length (cadr sublist)))
  10521. (mapcar (lambda (elm)
  10522. (list (substring (car elm) 0 1)
  10523. (cdr elm) ""))
  10524. (cadr sublist))
  10525. ;; Create submenu.
  10526. (let* ((topkey (car sublist))
  10527. (elms (cadr sublist))
  10528. (keys (mapcar #'car elms))
  10529. (long (> (length elms) 3)))
  10530. (append
  10531. (list
  10532. ;; Make a description of the submenu.
  10533. (list topkey
  10534. (concat
  10535. (mapconcat #'cdr
  10536. (cl-subseq elms 0 (if long 3 (length elms)))
  10537. ", ")
  10538. (when long ", ..."))))
  10539. ;; List of entries in submenu.
  10540. (cl-mapcar #'list
  10541. (org--insert-structure-template-unique-keys keys)
  10542. (mapcar #'cdr elms)
  10543. (make-list (length elms) ""))))))
  10544. superlist))
  10545. "Select a key\n============"
  10546. "Key: ")))
  10547. (defun org--insert-structure-template-unique-keys (keys)
  10548. "Make list of unique, two character long elements from KEYS.
  10549. Elements of length one have a tab appended. Elements of length
  10550. two are kept as is. Longer elements are truncated to length two.
  10551. If an element cannot be made unique an error is raised."
  10552. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10553. menu-keys)
  10554. (dolist (key orderd-keys)
  10555. (let ((potential-key
  10556. (cl-case (length key)
  10557. (1 (concat key "\t"))
  10558. (2 key)
  10559. (otherwise
  10560. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10561. (mapcar (apply-partially #'concat (substring key 0 1))
  10562. (split-string (substring key 1) "" t)))))))
  10563. (if (or (not potential-key) (assoc potential-key menu-keys))
  10564. (user-error "Could not make unique key for %s." key)
  10565. (push (cons potential-key key) menu-keys))))
  10566. (mapcar #'car
  10567. (cl-sort menu-keys #'<
  10568. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10569. (defun org-insert-structure-template (type)
  10570. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10571. First choose a block based on `org-structure-template-alist'.
  10572. Alternatively, type RET, TAB or SPC to write the block type.
  10573. With an active region, wrap the region in the block. Otherwise,
  10574. insert an empty block."
  10575. (interactive
  10576. (list (pcase (org--insert-structure-template-mks)
  10577. (`("\t" . ,_) (read-string "Structure type: "))
  10578. (`(,_ ,choice . ,_) choice))))
  10579. (let* ((region? (use-region-p))
  10580. (col (current-indentation))
  10581. (indent (make-string col ?\s))
  10582. (special? (string-match-p "\\(src\\|export\\)\\'" type))
  10583. (region-string (and region?
  10584. (buffer-substring (region-beginning)
  10585. (region-end))))
  10586. (region-end-blank (and region?
  10587. (save-excursion
  10588. (goto-char (region-end))
  10589. (when (looking-at "[ \t]*$")
  10590. (replace-match "")
  10591. t))))
  10592. s)
  10593. (when region? (delete-region (region-beginning) (region-end)))
  10594. (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
  10595. (insert "\n"))
  10596. (beginning-of-line)
  10597. (save-excursion
  10598. (insert
  10599. (with-temp-buffer
  10600. (when region?
  10601. (insert region-string "\n")
  10602. (when (string-match-p
  10603. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10604. type)
  10605. (org-escape-code-in-region (point-min) (point-max))))
  10606. (goto-char (point-min))
  10607. ;; Delete trailing white-lines.
  10608. (when region?
  10609. (while (looking-at-p "^[ \t]*$")
  10610. (delete-region (line-beginning-position)
  10611. (line-beginning-position 2))))
  10612. (save-excursion
  10613. (while (not (eobp))
  10614. (unless (looking-at-p indent)
  10615. (insert indent))
  10616. (forward-line)))
  10617. (insert
  10618. indent
  10619. (format "#+begin_%s%s\n" type (if special? " " "")))
  10620. (unless region? (indent-to col))
  10621. (setq s (point))
  10622. (goto-char (point-max))
  10623. (skip-chars-backward "[ \t\n]" s)
  10624. (delete-region (line-end-position) (point-max))
  10625. (insert "\n" indent
  10626. (format "#+end_%s" (car (split-string type)))
  10627. (if region-end-blank "" "\n"))
  10628. (buffer-substring (point-min) (point))))
  10629. (when (and (eobp) (not (bolp))) (insert "\n")))
  10630. (cond (special?
  10631. (end-of-line))
  10632. (t
  10633. (forward-line)
  10634. (skip-chars-forward "[ \t]*")))))
  10635. ;;;; TODO, DEADLINE, Comments
  10636. (defun org-toggle-comment ()
  10637. "Change the COMMENT state of an entry."
  10638. (interactive)
  10639. (save-excursion
  10640. (org-back-to-heading)
  10641. (let ((case-fold-search nil))
  10642. (looking-at org-complex-heading-regexp))
  10643. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10644. (skip-chars-forward " \t")
  10645. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10646. (if (org-in-commented-heading-p t)
  10647. (delete-region (point)
  10648. (progn (search-forward " " (line-end-position) 'move)
  10649. (skip-chars-forward " \t")
  10650. (point)))
  10651. (insert org-comment-string)
  10652. (unless (eolp) (insert " ")))))
  10653. (defvar org-last-todo-state-is-todo nil
  10654. "This is non-nil when the last TODO state change led to a TODO state.
  10655. If the last change removed the TODO tag or switched to DONE, then
  10656. this is nil.")
  10657. (defvar org-setting-tags nil) ; dynamically scoped
  10658. (defvar org-todo-setup-filter-hook nil
  10659. "Hook for functions that pre-filter todo specs.
  10660. Each function takes a todo spec and returns either nil or the spec
  10661. transformed into canonical form." )
  10662. (defvar org-todo-get-default-hook nil
  10663. "Hook for functions that get a default item for todo.
  10664. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10665. nil or a string to be used for the todo mark." )
  10666. (defvar org-agenda-headline-snapshot-before-repeat)
  10667. (defun org-current-effective-time ()
  10668. "Return current time adjusted for `org-extend-today-until' variable."
  10669. (let* ((ct (org-current-time))
  10670. (dct (decode-time ct))
  10671. (ct1
  10672. (cond
  10673. (org-use-last-clock-out-time-as-effective-time
  10674. (or (org-clock-get-last-clock-out-time) ct))
  10675. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10676. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10677. (t ct))))
  10678. ct1))
  10679. (defun org-todo-yesterday (&optional arg)
  10680. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10681. (interactive "P")
  10682. (if (eq major-mode 'org-agenda-mode)
  10683. (apply 'org-agenda-todo-yesterday arg)
  10684. (let* ((org-use-effective-time t)
  10685. (hour (nth 2 (decode-time (org-current-time))))
  10686. (org-extend-today-until (1+ hour)))
  10687. (org-todo arg))))
  10688. (defvar org-block-entry-blocking ""
  10689. "First entry preventing the TODO state change.")
  10690. (defun org-cancel-repeater ()
  10691. "Cancel a repeater by setting its numeric value to zero."
  10692. (interactive)
  10693. (save-excursion
  10694. (org-back-to-heading t)
  10695. (let ((bound1 (point))
  10696. (bound0 (save-excursion (outline-next-heading) (point))))
  10697. (when (and (re-search-forward
  10698. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10699. org-deadline-time-regexp "\\)\\|\\("
  10700. org-ts-regexp "\\)")
  10701. bound0 t)
  10702. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10703. bound1 t))
  10704. (replace-match "0" t nil nil 1)))))
  10705. (defvar org-state)
  10706. (defvar org-blocked-by-checkboxes)
  10707. (defun org-todo (&optional arg)
  10708. "Change the TODO state of an item.
  10709. The state of an item is given by a keyword at the start of the heading,
  10710. like
  10711. *** TODO Write paper
  10712. *** DONE Call mom
  10713. The different keywords are specified in the variable `org-todo-keywords'.
  10714. By default the available states are \"TODO\" and \"DONE\". So, for this
  10715. example: when the item starts with TODO, it is changed to DONE.
  10716. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10717. DONE are present, add TODO at the beginning of the heading.
  10718. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10719. state.
  10720. With numeric prefix ARG, switch to that state.
  10721. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10722. next set of TODO \
  10723. keywords (nextset).
  10724. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10725. prefix, circumvent any state blocking.
  10726. With a numeric prefix arg of 0, inhibit note taking for the change.
  10727. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10728. When called through ELisp, arg is also interpreted in the following way:
  10729. `none' -> empty state
  10730. \"\" -> switch to empty state
  10731. `done' -> switch to DONE
  10732. `nextset' -> switch to the next set of keywords
  10733. `previousset' -> switch to the previous set of keywords
  10734. \"WAITING\" -> switch to the specified keyword, but only if it
  10735. really is a member of `org-todo-keywords'."
  10736. (interactive "P")
  10737. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10738. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10739. 'region-start-level 'region))
  10740. org-loop-over-headlines-in-active-region)
  10741. (org-map-entries
  10742. `(org-todo ,arg)
  10743. org-loop-over-headlines-in-active-region
  10744. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10745. (when (equal arg '(16)) (setq arg 'nextset))
  10746. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10747. (let ((org-blocker-hook org-blocker-hook)
  10748. commentp
  10749. case-fold-search)
  10750. (when (equal arg '(64))
  10751. (setq arg nil org-blocker-hook nil))
  10752. (when (and org-blocker-hook
  10753. (or org-inhibit-blocking
  10754. (org-entry-get nil "NOBLOCKING")))
  10755. (setq org-blocker-hook nil))
  10756. (save-excursion
  10757. (catch 'exit
  10758. (org-back-to-heading t)
  10759. (when (org-in-commented-heading-p t)
  10760. (org-toggle-comment)
  10761. (setq commentp t))
  10762. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10763. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10764. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10765. (let* ((match-data (match-data))
  10766. (startpos (copy-marker (line-beginning-position)))
  10767. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10768. (org-log-done org-log-done)
  10769. (org-log-repeat org-log-repeat)
  10770. (org-todo-log-states org-todo-log-states)
  10771. (org-inhibit-logging
  10772. (if (equal arg 0)
  10773. (progn (setq arg nil) 'note) org-inhibit-logging))
  10774. (this (match-string 1))
  10775. (hl-pos (match-beginning 0))
  10776. (head (org-get-todo-sequence-head this))
  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. (org-last-state (or this ""))
  10782. (completion-ignore-case t)
  10783. (member (member this org-todo-keywords-1))
  10784. (tail (cdr member))
  10785. (org-state (cond
  10786. ((and org-todo-key-trigger
  10787. (or (and (equal arg '(4))
  10788. (eq org-use-fast-todo-selection 'prefix))
  10789. (and (not arg) org-use-fast-todo-selection
  10790. (not (eq org-use-fast-todo-selection
  10791. 'prefix)))))
  10792. ;; Use fast selection.
  10793. (org-fast-todo-selection))
  10794. ((and (equal arg '(4))
  10795. (or (not org-use-fast-todo-selection)
  10796. (not org-todo-key-trigger)))
  10797. ;; Read a state with completion.
  10798. (completing-read
  10799. "State: " (mapcar #'list org-todo-keywords-1)
  10800. nil t))
  10801. ((eq arg 'right)
  10802. (if this
  10803. (if tail (car tail) nil)
  10804. (car org-todo-keywords-1)))
  10805. ((eq arg 'left)
  10806. (unless (equal member org-todo-keywords-1)
  10807. (if this
  10808. (nth (- (length org-todo-keywords-1)
  10809. (length tail) 2)
  10810. org-todo-keywords-1)
  10811. (org-last org-todo-keywords-1))))
  10812. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10813. (setq arg nil))) ;hack to fall back to cycling
  10814. (arg
  10815. ;; User or caller requests a specific state.
  10816. (cond
  10817. ((equal arg "") nil)
  10818. ((eq arg 'none) nil)
  10819. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10820. ((eq arg 'nextset)
  10821. (or (car (cdr (member head org-todo-heads)))
  10822. (car org-todo-heads)))
  10823. ((eq arg 'previousset)
  10824. (let ((org-todo-heads (reverse org-todo-heads)))
  10825. (or (car (cdr (member head org-todo-heads)))
  10826. (car org-todo-heads))))
  10827. ((car (member arg org-todo-keywords-1)))
  10828. ((stringp arg)
  10829. (user-error "State `%s' not valid in this file" arg))
  10830. ((nth (1- (prefix-numeric-value arg))
  10831. org-todo-keywords-1))))
  10832. ((null member) (or head (car org-todo-keywords-1)))
  10833. ((equal this final-done-word) nil) ;-> make empty
  10834. ((null tail) nil) ;-> first entry
  10835. ((memq interpret '(type priority))
  10836. (if (eq this-command last-command)
  10837. (car tail)
  10838. (if (> (length tail) 0)
  10839. (or done-word (car org-done-keywords))
  10840. nil)))
  10841. (t
  10842. (car tail))))
  10843. (org-state (or
  10844. (run-hook-with-args-until-success
  10845. 'org-todo-get-default-hook org-state org-last-state)
  10846. org-state))
  10847. (next (if org-state (concat " " org-state " ") " "))
  10848. (change-plist (list :type 'todo-state-change :from this :to org-state
  10849. :position startpos))
  10850. dolog now-done-p)
  10851. (when org-blocker-hook
  10852. (let (org-blocked-by-checkboxes block-reason)
  10853. (setq org-last-todo-state-is-todo
  10854. (not (member this org-done-keywords)))
  10855. (unless (save-excursion
  10856. (save-match-data
  10857. (org-with-wide-buffer
  10858. (run-hook-with-args-until-failure
  10859. 'org-blocker-hook change-plist))))
  10860. (setq block-reason (if org-blocked-by-checkboxes
  10861. "contained checkboxes"
  10862. (format "\"%s\"" org-block-entry-blocking)))
  10863. (if (called-interactively-p 'interactive)
  10864. (user-error "TODO state change from %s to %s blocked (by %s)"
  10865. this org-state block-reason)
  10866. ;; Fail silently.
  10867. (message "TODO state change from %s to %s blocked (by %s)"
  10868. this org-state block-reason)
  10869. (throw 'exit nil)))))
  10870. (store-match-data match-data)
  10871. (replace-match next t t)
  10872. (cond ((equal this org-state)
  10873. (message "TODO state was already %s" (org-trim next)))
  10874. ((not (pos-visible-in-window-p hl-pos))
  10875. (message "TODO state changed to %s" (org-trim next))))
  10876. (unless head
  10877. (setq head (org-get-todo-sequence-head org-state)
  10878. ass (assoc head org-todo-kwd-alist)
  10879. interpret (nth 1 ass)
  10880. done-word (nth 3 ass)
  10881. final-done-word (nth 4 ass)))
  10882. (when (memq arg '(nextset previousset))
  10883. (message "Keyword-Set %d/%d: %s"
  10884. (- (length org-todo-sets) -1
  10885. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10886. (length org-todo-sets)
  10887. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10888. (setq org-last-todo-state-is-todo
  10889. (not (member org-state org-done-keywords)))
  10890. (setq now-done-p (and (member org-state org-done-keywords)
  10891. (not (member this org-done-keywords))))
  10892. (and logging (org-local-logging logging))
  10893. (when (and (or org-todo-log-states org-log-done)
  10894. (not (eq org-inhibit-logging t))
  10895. (not (memq arg '(nextset previousset))))
  10896. ;; We need to look at recording a time and note.
  10897. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10898. (nth 2 (assoc this org-todo-log-states))))
  10899. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10900. (setq dolog 'time))
  10901. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10902. (and org-state
  10903. (member org-state org-not-done-keywords)
  10904. (not (member this org-not-done-keywords))))
  10905. ;; This is now a todo state and was not one before
  10906. ;; If there was a CLOSED time stamp, get rid of it.
  10907. (org-add-planning-info nil nil 'closed))
  10908. (when (and now-done-p org-log-done)
  10909. ;; It is now done, and it was not done before.
  10910. (org-add-planning-info 'closed (org-current-effective-time))
  10911. (when (and (not dolog) (eq 'note org-log-done))
  10912. (org-add-log-setup 'done org-state this 'note)))
  10913. (when (and org-state dolog)
  10914. ;; This is a non-nil state, and we need to log it.
  10915. (org-add-log-setup 'state org-state this dolog)))
  10916. ;; Fixup tag positioning.
  10917. (org-todo-trigger-tag-changes org-state)
  10918. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  10919. (when org-provide-todo-statistics
  10920. (org-update-parent-todo-statistics))
  10921. (run-hooks 'org-after-todo-state-change-hook)
  10922. (when (and arg (not (member org-state org-done-keywords)))
  10923. (setq head (org-get-todo-sequence-head org-state)))
  10924. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10925. ;; Do we need to trigger a repeat?
  10926. (when now-done-p
  10927. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10928. ;; This is for the agenda, take a snapshot of the headline.
  10929. (save-match-data
  10930. (setq org-agenda-headline-snapshot-before-repeat
  10931. (org-get-heading))))
  10932. (org-auto-repeat-maybe org-state))
  10933. ;; Fixup cursor location if close to the keyword.
  10934. (when (and (outline-on-heading-p)
  10935. (not (bolp))
  10936. (save-excursion (beginning-of-line 1)
  10937. (looking-at org-todo-line-regexp))
  10938. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10939. (goto-char (or (match-end 2) (match-end 1)))
  10940. (and (looking-at " ") (just-one-space)))
  10941. (when org-trigger-hook
  10942. (save-excursion
  10943. (run-hook-with-args 'org-trigger-hook change-plist)))
  10944. (when commentp (org-toggle-comment))))))))
  10945. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10946. "Block turning an entry into a TODO, using the hierarchy.
  10947. This checks whether the current task should be blocked from state
  10948. changes. Such blocking occurs when:
  10949. 1. The task has children which are not all in a completed state.
  10950. 2. A task has a parent with the property :ORDERED:, and there
  10951. are siblings prior to the current task with incomplete
  10952. status.
  10953. 3. The parent of the task is blocked because it has siblings that should
  10954. be done first, or is child of a block grandparent TODO entry."
  10955. (if (not org-enforce-todo-dependencies)
  10956. t ; if locally turned off don't block
  10957. (catch 'dont-block
  10958. ;; If this is not a todo state change, or if this entry is already DONE,
  10959. ;; do not block
  10960. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10961. (member (plist-get change-plist :from)
  10962. (cons 'done org-done-keywords))
  10963. (member (plist-get change-plist :to)
  10964. (cons 'todo org-not-done-keywords))
  10965. (not (plist-get change-plist :to)))
  10966. (throw 'dont-block t))
  10967. ;; If this task has children, and any are undone, it's blocked
  10968. (save-excursion
  10969. (org-back-to-heading t)
  10970. (let ((this-level (funcall outline-level)))
  10971. (outline-next-heading)
  10972. (let ((child-level (funcall outline-level)))
  10973. (while (and (not (eobp))
  10974. (> child-level this-level))
  10975. ;; this todo has children, check whether they are all
  10976. ;; completed
  10977. (when (and (not (org-entry-is-done-p))
  10978. (org-entry-is-todo-p))
  10979. (setq org-block-entry-blocking (org-get-heading))
  10980. (throw 'dont-block nil))
  10981. (outline-next-heading)
  10982. (setq child-level (funcall outline-level))))))
  10983. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  10984. ;; any previous siblings are undone, it's blocked
  10985. (save-excursion
  10986. (org-back-to-heading t)
  10987. (let* ((pos (point))
  10988. (parent-pos (and (org-up-heading-safe) (point)))
  10989. (case-fold-search nil))
  10990. (unless parent-pos (throw 'dont-block t)) ; no parent
  10991. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10992. (forward-line 1)
  10993. (re-search-forward org-not-done-heading-regexp pos t))
  10994. (setq org-block-entry-blocking (match-string 0))
  10995. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  10996. ;; Search further up the hierarchy, to see if an ancestor is blocked
  10997. (while t
  10998. (goto-char parent-pos)
  10999. (unless (looking-at org-not-done-heading-regexp)
  11000. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11001. (setq pos (point))
  11002. (setq parent-pos (and (org-up-heading-safe) (point)))
  11003. (unless parent-pos (throw 'dont-block t)) ; no parent
  11004. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11005. (forward-line 1)
  11006. (re-search-forward org-not-done-heading-regexp pos t)
  11007. (setq org-block-entry-blocking (org-get-heading)))
  11008. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11009. (defcustom org-track-ordered-property-with-tag nil
  11010. "Should the ORDERED property also be shown as a tag?
  11011. The ORDERED property decides if an entry should require subtasks to be
  11012. completed in sequence. Since a property is not very visible, setting
  11013. this option means that toggling the ORDERED property with the command
  11014. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11015. not relevant for the behavior, but it makes things more visible.
  11016. Note that toggling the tag with tags commands will not change the property
  11017. and therefore not influence behavior!
  11018. This can be t, meaning the tag ORDERED should be used, It can also be a
  11019. string to select a different tag for this task."
  11020. :group 'org-todo
  11021. :type '(choice
  11022. (const :tag "No tracking" nil)
  11023. (const :tag "Track with ORDERED tag" t)
  11024. (string :tag "Use other tag")))
  11025. (defun org-toggle-ordered-property ()
  11026. "Toggle the ORDERED property of the current entry.
  11027. For better visibility, you can track the value of this property with a tag.
  11028. See variable `org-track-ordered-property-with-tag'."
  11029. (interactive)
  11030. (let* ((t1 org-track-ordered-property-with-tag)
  11031. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11032. (save-excursion
  11033. (org-back-to-heading)
  11034. (if (org-entry-get nil "ORDERED")
  11035. (progn
  11036. (org-delete-property "ORDERED")
  11037. (and tag (org-toggle-tag tag 'off))
  11038. (message "Subtasks can be completed in arbitrary order"))
  11039. (org-entry-put nil "ORDERED" "t")
  11040. (and tag (org-toggle-tag tag 'on))
  11041. (message "Subtasks must be completed in sequence")))))
  11042. (defun org-block-todo-from-checkboxes (change-plist)
  11043. "Block turning an entry into a TODO, using checkboxes.
  11044. This checks whether the current task should be blocked from state
  11045. changes because there are unchecked boxes in this entry."
  11046. (if (not org-enforce-todo-checkbox-dependencies)
  11047. t ; if locally turned off don't block
  11048. (catch 'dont-block
  11049. ;; If this is not a todo state change, or if this entry is already DONE,
  11050. ;; do not block
  11051. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11052. (member (plist-get change-plist :from)
  11053. (cons 'done org-done-keywords))
  11054. (member (plist-get change-plist :to)
  11055. (cons 'todo org-not-done-keywords))
  11056. (not (plist-get change-plist :to)))
  11057. (throw 'dont-block t))
  11058. ;; If this task has checkboxes that are not checked, it's blocked
  11059. (save-excursion
  11060. (org-back-to-heading t)
  11061. (let ((beg (point)) end)
  11062. (outline-next-heading)
  11063. (setq end (point))
  11064. (goto-char beg)
  11065. (when (org-list-search-forward
  11066. (concat (org-item-beginning-re)
  11067. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11068. "\\[[- ]\\]")
  11069. end t)
  11070. (when (boundp 'org-blocked-by-checkboxes)
  11071. (setq org-blocked-by-checkboxes t))
  11072. (throw 'dont-block nil))))
  11073. t))) ; do not block
  11074. (defun org-entry-blocked-p ()
  11075. "Non-nil if entry at point is blocked."
  11076. (and (not (org-entry-get nil "NOBLOCKING"))
  11077. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11078. (not (run-hook-with-args-until-failure
  11079. 'org-blocker-hook
  11080. (list :type 'todo-state-change
  11081. :position (point)
  11082. :from 'todo
  11083. :to 'done)))))
  11084. (defun org-update-statistics-cookies (all)
  11085. "Update the statistics cookie, either from TODO or from checkboxes.
  11086. This should be called with the cursor in a line with a statistics
  11087. cookie. When called with a \\[universal-argument] prefix, update
  11088. all statistics cookies in the buffer."
  11089. (interactive "P")
  11090. (if all
  11091. (progn
  11092. (org-update-checkbox-count 'all)
  11093. (org-map-entries 'org-update-parent-todo-statistics))
  11094. (if (not (org-at-heading-p))
  11095. (org-update-checkbox-count)
  11096. (let ((pos (point-marker))
  11097. end l1 l2)
  11098. (ignore-errors (org-back-to-heading t))
  11099. (if (not (org-at-heading-p))
  11100. (org-update-checkbox-count)
  11101. (setq l1 (org-outline-level))
  11102. (setq end (save-excursion
  11103. (outline-next-heading)
  11104. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11105. (point)))
  11106. (if (and (save-excursion
  11107. (re-search-forward
  11108. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11109. (not (save-excursion (re-search-forward
  11110. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11111. (org-update-checkbox-count)
  11112. (if (and l2 (> l2 l1))
  11113. (progn
  11114. (goto-char end)
  11115. (org-update-parent-todo-statistics))
  11116. (goto-char pos)
  11117. (beginning-of-line 1)
  11118. (while (re-search-forward
  11119. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11120. (point-at-eol) t)
  11121. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11122. (goto-char pos)
  11123. (move-marker pos nil)))))
  11124. (defvar org-entry-property-inherited-from) ;; defined below
  11125. (defun org-update-parent-todo-statistics ()
  11126. "Update any statistics cookie in the parent of the current headline.
  11127. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11128. the entire subtree and this will travel up the hierarchy and update
  11129. statistics everywhere."
  11130. (let* ((prop (save-excursion (org-up-heading-safe)
  11131. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11132. (recursive (or (not org-hierarchical-todo-statistics)
  11133. (and prop (string-match "\\<recursive\\>" prop))))
  11134. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11135. 0))
  11136. (first t)
  11137. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11138. level ltoggle l1 new ndel
  11139. (cnt-all 0) (cnt-done 0) is-percent kwd
  11140. checkbox-beg cookie-present)
  11141. (catch 'exit
  11142. (save-excursion
  11143. (beginning-of-line 1)
  11144. (setq ltoggle (funcall outline-level))
  11145. ;; Three situations are to consider:
  11146. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11147. ;; to the top-level ancestor on the headline;
  11148. ;; 2. If parent has "recursive" property, repeat up to the
  11149. ;; headline setting that property, taking inheritance into
  11150. ;; account;
  11151. ;; 3. Else, move up to direct parent and proceed only once.
  11152. (while (and (setq level (org-up-heading-safe))
  11153. (or recursive first)
  11154. (>= (point) lim))
  11155. (setq first nil cookie-present nil)
  11156. (unless (and level
  11157. (not (string-match
  11158. "\\<checkbox\\>"
  11159. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11160. "")))))
  11161. (throw 'exit nil))
  11162. (while (re-search-forward box-re (point-at-eol) t)
  11163. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11164. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11165. (save-match-data
  11166. (unless (outline-next-heading) (throw 'exit nil))
  11167. (while (and (looking-at org-complex-heading-regexp)
  11168. (> (setq l1 (length (match-string 1))) level))
  11169. (setq kwd (and (or recursive (= l1 ltoggle))
  11170. (match-string 2)))
  11171. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11172. (and (eq org-provide-todo-statistics t)
  11173. (or (member kwd org-done-keywords)))
  11174. (and (listp org-provide-todo-statistics)
  11175. (stringp (car org-provide-todo-statistics))
  11176. (or (member kwd org-provide-todo-statistics)
  11177. (member kwd org-done-keywords)))
  11178. (and (listp org-provide-todo-statistics)
  11179. (listp (car org-provide-todo-statistics))
  11180. (or (member kwd (car org-provide-todo-statistics))
  11181. (and (member kwd org-done-keywords)
  11182. (member kwd (cadr org-provide-todo-statistics))))))
  11183. (setq cnt-all (1+ cnt-all))
  11184. (and (eq org-provide-todo-statistics t)
  11185. kwd
  11186. (setq cnt-all (1+ cnt-all))))
  11187. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11188. (member kwd org-done-keywords))
  11189. (and (listp org-provide-todo-statistics)
  11190. (listp (car org-provide-todo-statistics))
  11191. (member kwd org-done-keywords)
  11192. (member kwd (cadr org-provide-todo-statistics)))
  11193. (and (listp org-provide-todo-statistics)
  11194. (stringp (car org-provide-todo-statistics))
  11195. (member kwd org-done-keywords)))
  11196. (setq cnt-done (1+ cnt-done)))
  11197. (outline-next-heading)))
  11198. (setq new
  11199. (if is-percent
  11200. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11201. (max 1 cnt-all)))
  11202. (format "[%d/%d]" cnt-done cnt-all))
  11203. ndel (- (match-end 0) checkbox-beg))
  11204. (goto-char checkbox-beg)
  11205. (insert new)
  11206. (delete-region (point) (+ (point) ndel))
  11207. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11208. (when cookie-present
  11209. (run-hook-with-args 'org-after-todo-statistics-hook
  11210. cnt-done (- cnt-all cnt-done))))))
  11211. (run-hooks 'org-todo-statistics-hook)))
  11212. (defvar org-after-todo-statistics-hook nil
  11213. "Hook that is called after a TODO statistics cookie has been updated.
  11214. Each function is called with two arguments: the number of not-done entries
  11215. and the number of done entries.
  11216. For example, the following function, when added to this hook, will switch
  11217. an entry to DONE when all children are done, and back to TODO when new
  11218. entries are set to a TODO status. Note that this hook is only called
  11219. when there is a statistics cookie in the headline!
  11220. (defun org-summary-todo (n-done n-not-done)
  11221. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11222. (let (org-log-done org-log-states) ; turn off logging
  11223. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11224. ")
  11225. (defvar org-todo-statistics-hook nil
  11226. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11227. This hook runs even if there is no statistics cookie present, in which case
  11228. `org-after-todo-statistics-hook' would not run.")
  11229. (defun org-todo-trigger-tag-changes (state)
  11230. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11231. (let ((l org-todo-state-tags-triggers)
  11232. changes)
  11233. (when (or (not state) (equal state ""))
  11234. (setq changes (append changes (cdr (assoc "" l)))))
  11235. (when (and (stringp state) (> (length state) 0))
  11236. (setq changes (append changes (cdr (assoc state l)))))
  11237. (when (member state org-not-done-keywords)
  11238. (setq changes (append changes (cdr (assq 'todo l)))))
  11239. (when (member state org-done-keywords)
  11240. (setq changes (append changes (cdr (assq 'done l)))))
  11241. (dolist (c changes)
  11242. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11243. (defun org-local-logging (value)
  11244. "Get logging settings from a property VALUE."
  11245. ;; Directly set the variables, they are already local.
  11246. (setq org-log-done nil
  11247. org-log-repeat nil
  11248. org-todo-log-states nil)
  11249. (dolist (w (split-string value))
  11250. (let (a)
  11251. (cond
  11252. ((setq a (assoc w org-startup-options))
  11253. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11254. (set (nth 1 a) (nth 2 a))))
  11255. ((setq a (org-extract-log-state-settings w))
  11256. (and (member (car a) org-todo-keywords-1)
  11257. (push a org-todo-log-states)))))))
  11258. (defun org-get-todo-sequence-head (kwd)
  11259. "Return the head of the TODO sequence to which KWD belongs.
  11260. If KWD is not set, check if there is a text property remembering the
  11261. right sequence."
  11262. (let (p)
  11263. (cond
  11264. ((not kwd)
  11265. (or (get-text-property (point-at-bol) 'org-todo-head)
  11266. (progn
  11267. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11268. nil (point-at-eol)))
  11269. (get-text-property p 'org-todo-head))))
  11270. ((not (member kwd org-todo-keywords-1))
  11271. (car org-todo-keywords-1))
  11272. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11273. (defun org-fast-todo-selection ()
  11274. "Fast TODO keyword selection with single keys.
  11275. Returns the new TODO keyword, or nil if no state change should occur."
  11276. (let* ((fulltable org-todo-key-alist)
  11277. (done-keywords org-done-keywords) ;; needed for the faces.
  11278. (maxlen (apply 'max (mapcar
  11279. (lambda (x)
  11280. (if (stringp (car x)) (string-width (car x)) 0))
  11281. fulltable)))
  11282. (expert nil)
  11283. (fwidth (+ maxlen 3 1 3))
  11284. (ncol (/ (- (window-width) 4) fwidth))
  11285. tg cnt e c tbl
  11286. groups ingroup)
  11287. (save-excursion
  11288. (save-window-excursion
  11289. (if expert
  11290. (set-buffer (get-buffer-create " *Org todo*"))
  11291. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11292. (erase-buffer)
  11293. (setq-local org-done-keywords done-keywords)
  11294. (setq tbl fulltable cnt 0)
  11295. (while (setq e (pop tbl))
  11296. (cond
  11297. ((equal e '(:startgroup))
  11298. (push '() groups) (setq ingroup t)
  11299. (unless (= cnt 0)
  11300. (setq cnt 0)
  11301. (insert "\n"))
  11302. (insert "{ "))
  11303. ((equal e '(:endgroup))
  11304. (setq ingroup nil cnt 0)
  11305. (insert "}\n"))
  11306. ((equal e '(:newline))
  11307. (unless (= cnt 0)
  11308. (setq cnt 0)
  11309. (insert "\n")
  11310. (setq e (car tbl))
  11311. (while (equal (car tbl) '(:newline))
  11312. (insert "\n")
  11313. (setq tbl (cdr tbl)))))
  11314. (t
  11315. (setq tg (car e) c (cdr e))
  11316. (when ingroup (push tg (car groups)))
  11317. (setq tg (org-add-props tg nil 'face
  11318. (org-get-todo-face tg)))
  11319. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11320. (insert "[" c "] " tg (make-string
  11321. (- fwidth 4 (length tg)) ?\ ))
  11322. (when (= (setq cnt (1+ cnt)) ncol)
  11323. (insert "\n")
  11324. (when ingroup (insert " "))
  11325. (setq cnt 0)))))
  11326. (insert "\n")
  11327. (goto-char (point-min))
  11328. (unless expert (org-fit-window-to-buffer))
  11329. (message "[a-z..]:Set [SPC]:clear")
  11330. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11331. (cond
  11332. ((or (= c ?\C-g)
  11333. (and (= c ?q) (not (rassoc c fulltable))))
  11334. (setq quit-flag t))
  11335. ((= c ?\ ) nil)
  11336. ((setq e (rassoc c fulltable) tg (car e))
  11337. tg)
  11338. (t (setq quit-flag t)))))))
  11339. (defun org-entry-is-todo-p ()
  11340. (member (org-get-todo-state) org-not-done-keywords))
  11341. (defun org-entry-is-done-p ()
  11342. (member (org-get-todo-state) org-done-keywords))
  11343. (defun org-get-todo-state ()
  11344. "Return the TODO keyword of the current subtree."
  11345. (save-excursion
  11346. (org-back-to-heading t)
  11347. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11348. (match-end 2)
  11349. (match-string 2))))
  11350. (defun org-at-date-range-p (&optional inactive-ok)
  11351. "Non-nil if point is inside a date range.
  11352. When optional argument INACTIVE-OK is non-nil, also consider
  11353. inactive time ranges.
  11354. When this function returns a non-nil value, match data is set
  11355. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11356. on INACTIVE-OK."
  11357. (interactive)
  11358. (save-excursion
  11359. (catch 'exit
  11360. (let ((pos (point)))
  11361. (skip-chars-backward "^[<\r\n")
  11362. (skip-chars-backward "<[")
  11363. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11364. (>= (match-end 0) pos)
  11365. (throw 'exit t))
  11366. (skip-chars-backward "^<[\r\n")
  11367. (skip-chars-backward "<[")
  11368. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11369. (>= (match-end 0) pos)
  11370. (throw 'exit t)))
  11371. nil)))
  11372. (defun org-get-repeat (&optional timestamp)
  11373. "Check if there is a time-stamp with repeater in this entry.
  11374. Return the repeater, as a string, or nil. Also return nil when
  11375. this function is called before first heading.
  11376. When optional argument TIMESTAMP is a string, extract the
  11377. repeater from there instead."
  11378. (save-match-data
  11379. (cond (timestamp
  11380. (and (string-match org-repeat-re timestamp)
  11381. (match-string-no-properties 1 timestamp)))
  11382. ((org-before-first-heading-p) nil)
  11383. (t
  11384. (save-excursion
  11385. (org-back-to-heading t)
  11386. (let ((end (org-entry-end-position)))
  11387. (catch :repeat
  11388. (while (re-search-forward org-repeat-re end t)
  11389. (when (save-match-data (org-at-timestamp-p 'agenda))
  11390. (throw :repeat (match-string-no-properties 1)))))))))))
  11391. (defvar org-last-changed-timestamp)
  11392. (defvar org-last-inserted-timestamp)
  11393. (defvar org-log-post-message)
  11394. (defvar org-log-note-purpose)
  11395. (defvar org-log-note-how nil)
  11396. (defvar org-log-note-extra)
  11397. (defun org-auto-repeat-maybe (done-word)
  11398. "Check if the current headline contains a repeated time-stamp.
  11399. If yes, set TODO state back to what it was and change the base date
  11400. of repeating deadline/scheduled time stamps to new date.
  11401. This function is run automatically after each state change to a DONE state."
  11402. (let* ((repeat (org-get-repeat))
  11403. (aa (assoc org-last-state org-todo-kwd-alist))
  11404. (interpret (nth 1 aa))
  11405. (head (nth 2 aa))
  11406. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11407. (msg "Entry repeats: ")
  11408. (org-log-done nil)
  11409. (org-todo-log-states nil)
  11410. (end (copy-marker (org-entry-end-position))))
  11411. (unwind-protect
  11412. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11413. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11414. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11415. (and (stringp org-todo-repeat-to-state)
  11416. org-todo-repeat-to-state)
  11417. (and org-todo-repeat-to-state org-last-state))))
  11418. (org-todo (cond
  11419. ((and to-state (member to-state org-todo-keywords-1))
  11420. to-state)
  11421. ((eq interpret 'type) org-last-state)
  11422. (head)
  11423. (t 'none))))
  11424. (org-back-to-heading t)
  11425. (org-add-planning-info nil nil 'closed)
  11426. ;; When `org-log-repeat' is non-nil or entry contains
  11427. ;; a clock, set LAST_REPEAT property.
  11428. (when (or org-log-repeat
  11429. (catch :clock
  11430. (save-excursion
  11431. (while (re-search-forward org-clock-line-re end t)
  11432. (when (org-at-clock-log-p) (throw :clock t))))))
  11433. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11434. (org-time-stamp-format t t)
  11435. (current-time))))
  11436. (when org-log-repeat
  11437. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11438. (memq 'org-add-log-note post-command-hook))
  11439. ;; We are already setup for some record.
  11440. (when (eq org-log-repeat 'note)
  11441. ;; Make sure we take a note, not only a time stamp.
  11442. (setq org-log-note-how 'note))
  11443. ;; Set up for taking a record.
  11444. (org-add-log-setup 'state
  11445. (or done-word (car org-done-keywords))
  11446. org-last-state
  11447. org-log-repeat)))
  11448. (let ((planning-re (regexp-opt
  11449. (list org-scheduled-string org-deadline-string))))
  11450. (while (re-search-forward org-ts-regexp end t)
  11451. (let* ((ts (match-string 0))
  11452. (planning? (org-at-planning-p))
  11453. (type (if (not planning?) "Plain:"
  11454. (save-excursion
  11455. (re-search-backward
  11456. planning-re (line-beginning-position) t)
  11457. (match-string 0)))))
  11458. (cond
  11459. ;; Ignore fake time-stamps (e.g., within comments).
  11460. ((not (org-at-timestamp-p 'agenda)))
  11461. ;; Time-stamps without a repeater are usually
  11462. ;; skipped. However, a SCHEDULED time-stamp without
  11463. ;; one is removed, as they are no longer relevant.
  11464. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11465. ts))
  11466. (when (equal type org-scheduled-string)
  11467. (org-remove-timestamp-with-keyword type)))
  11468. (t
  11469. (let ((n (string-to-number (match-string 2 ts)))
  11470. (what (match-string 3 ts)))
  11471. (when (equal what "w") (setq n (* n 7) what "d"))
  11472. (when (and (equal what "h")
  11473. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11474. ts)))
  11475. (user-error
  11476. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11477. has been set"
  11478. n))
  11479. ;; Preparation, see if we need to modify the start
  11480. ;; date for the change.
  11481. (when (match-end 1)
  11482. (let ((time (save-match-data
  11483. (org-time-string-to-time ts))))
  11484. (cond
  11485. ((equal (match-string 1 ts) ".")
  11486. ;; Shift starting date to today
  11487. (org-timestamp-change
  11488. (- (org-today) (time-to-days time))
  11489. 'day))
  11490. ((equal (match-string 1 ts) "+")
  11491. (let ((nshiftmax 10)
  11492. (nshift 0))
  11493. (while (or (= nshift 0)
  11494. (not (time-less-p (current-time) time)))
  11495. (when (= (cl-incf nshift) nshiftmax)
  11496. (or (y-or-n-p
  11497. (format "%d repeater intervals were not \
  11498. enough to shift date past today. Continue? "
  11499. nshift))
  11500. (user-error "Abort")))
  11501. (org-timestamp-change n (cdr (assoc what whata)))
  11502. (org-in-regexp org-ts-regexp3)
  11503. (setq ts (match-string 1))
  11504. (setq time
  11505. (save-match-data
  11506. (org-time-string-to-time ts)))))
  11507. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11508. ;; Rematch, so that we have everything in place
  11509. ;; for the real shift.
  11510. (org-in-regexp org-ts-regexp3)
  11511. (setq ts (match-string 1))
  11512. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11513. ts)))))
  11514. (save-excursion
  11515. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11516. (setq msg
  11517. (concat
  11518. msg type " " org-last-changed-timestamp " "))))))))
  11519. (setq org-log-post-message msg)
  11520. (message "%s" msg))
  11521. (set-marker end nil))))
  11522. (defun org-show-todo-tree (arg)
  11523. "Make a compact tree which shows all headlines marked with TODO.
  11524. The tree will show the lines where the regexp matches, and all higher
  11525. headlines above the match.
  11526. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11527. With a numeric prefix N, construct a sparse tree for the Nth element
  11528. of `org-todo-keywords-1'."
  11529. (interactive "P")
  11530. (let ((case-fold-search nil)
  11531. (kwd-re
  11532. (cond ((null arg) org-not-done-regexp)
  11533. ((equal arg '(4))
  11534. (let ((kwd
  11535. (completing-read "Keyword (or KWD1|KWD2|...): "
  11536. (mapcar #'list org-todo-keywords-1))))
  11537. (concat "\\("
  11538. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11539. "\\)\\>")))
  11540. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11541. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11542. org-todo-keywords-1)))
  11543. (t (user-error "Invalid prefix argument: %s" arg)))))
  11544. (message "%d TODO entries found"
  11545. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11546. (defun org--deadline-or-schedule (arg type time)
  11547. "Insert DEADLINE or SCHEDULE information in current entry.
  11548. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11549. `org-schedule' for information about ARG and TIME arguments."
  11550. (let* ((deadline? (eq type 'deadline))
  11551. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11552. (log (if deadline? org-log-redeadline org-log-reschedule))
  11553. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11554. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11555. ;; Save repeater cookie from either TIME or current scheduled
  11556. ;; time stamp. We are going to insert it back at the end of
  11557. ;; the process.
  11558. (repeater (or (and (org-string-nw-p time)
  11559. ;; We use `org-repeat-re' because we need
  11560. ;; to tell the difference between a real
  11561. ;; repeater and a time delta, e.g. "+2d".
  11562. (string-match org-repeat-re time)
  11563. (match-string 1 time))
  11564. (and (org-string-nw-p old-date)
  11565. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11566. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11567. old-date)
  11568. (match-string 1 old-date)))))
  11569. (pcase arg
  11570. (`(4)
  11571. (when (and old-date log)
  11572. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11573. nil old-date log))
  11574. (org-remove-timestamp-with-keyword keyword)
  11575. (message (if deadline? "Item no longer has a deadline."
  11576. "Item is no longer scheduled.")))
  11577. (`(16)
  11578. (save-excursion
  11579. (org-back-to-heading t)
  11580. (let ((regexp (if deadline? org-deadline-time-regexp
  11581. org-scheduled-time-regexp)))
  11582. (if (not (re-search-forward regexp (line-end-position 2) t))
  11583. (user-error (if deadline? "No deadline information to update"
  11584. "No scheduled information to update"))
  11585. (let* ((rpl0 (match-string 1))
  11586. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11587. (msg (if deadline? "Warn starting from" "Delay until")))
  11588. (replace-match
  11589. (concat keyword
  11590. " <" rpl
  11591. (format " -%dd"
  11592. (abs (- (time-to-days
  11593. (save-match-data
  11594. (org-read-date
  11595. nil t nil msg old-date-time)))
  11596. (time-to-days old-date-time))))
  11597. ">") t t))))))
  11598. (_
  11599. (org-add-planning-info type time 'closed)
  11600. (when (and old-date
  11601. log
  11602. (not (equal old-date org-last-inserted-timestamp)))
  11603. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11604. org-last-inserted-timestamp
  11605. old-date
  11606. log))
  11607. (when repeater
  11608. (save-excursion
  11609. (org-back-to-heading t)
  11610. (when (re-search-forward
  11611. (concat keyword " " org-last-inserted-timestamp)
  11612. (line-end-position 2)
  11613. t)
  11614. (goto-char (1- (match-end 0)))
  11615. (insert " " repeater)
  11616. (setq org-last-inserted-timestamp
  11617. (concat (substring org-last-inserted-timestamp 0 -1)
  11618. " " repeater
  11619. (substring org-last-inserted-timestamp -1))))))
  11620. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11621. org-last-inserted-timestamp)))))
  11622. (defun org-deadline (arg &optional time)
  11623. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11624. With one universal prefix argument, remove any deadline from the item.
  11625. With two universal prefix arguments, prompt for a warning delay.
  11626. With argument TIME, set the deadline at the corresponding date. TIME
  11627. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11628. (interactive "P")
  11629. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11630. (org-map-entries
  11631. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11632. nil
  11633. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11634. 'region-start-level
  11635. 'region)
  11636. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11637. (org--deadline-or-schedule arg 'deadline time)))
  11638. (defun org-schedule (arg &optional time)
  11639. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11640. With one universal prefix argument, remove any scheduling date from the item.
  11641. With two universal prefix arguments, prompt for a delay cookie.
  11642. With argument TIME, scheduled at the corresponding date. TIME can
  11643. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11644. (interactive "P")
  11645. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11646. (org-map-entries
  11647. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11648. nil
  11649. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11650. 'region-start-level
  11651. 'region)
  11652. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11653. (org--deadline-or-schedule arg 'scheduled time)))
  11654. (defun org-get-scheduled-time (pom &optional inherit)
  11655. "Get the scheduled time as a time tuple, of a format suitable
  11656. for calling org-schedule with, or if there is no scheduling,
  11657. returns nil."
  11658. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11659. (when time
  11660. (apply 'encode-time (org-parse-time-string time)))))
  11661. (defun org-get-deadline-time (pom &optional inherit)
  11662. "Get the deadline as a time tuple, of a format suitable for
  11663. calling org-deadline with, or if there is no scheduling, returns
  11664. nil."
  11665. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11666. (when time
  11667. (apply 'encode-time (org-parse-time-string time)))))
  11668. (defun org-remove-timestamp-with-keyword (keyword)
  11669. "Remove all time stamps with KEYWORD in the current entry."
  11670. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11671. beg)
  11672. (save-excursion
  11673. (org-back-to-heading t)
  11674. (setq beg (point))
  11675. (outline-next-heading)
  11676. (while (re-search-backward re beg t)
  11677. (replace-match "")
  11678. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11679. (equal (char-before) ?\ ))
  11680. (backward-delete-char 1)
  11681. (when (string-match "^[ \t]*$" (buffer-substring
  11682. (point-at-bol) (point-at-eol)))
  11683. (delete-region (point-at-bol)
  11684. (min (point-max) (1+ (point-at-eol))))))))))
  11685. (defvar org-time-was-given) ; dynamically scoped parameter
  11686. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11687. (defun org-at-planning-p ()
  11688. "Non-nil when point is on a planning info line."
  11689. ;; This is as accurate and faster than `org-element-at-point' since
  11690. ;; planning info location is fixed in the section.
  11691. (org-with-wide-buffer
  11692. (beginning-of-line)
  11693. (and (looking-at-p org-planning-line-re)
  11694. (eq (point)
  11695. (ignore-errors
  11696. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11697. (org-back-to-heading t)
  11698. (org-with-limited-levels (org-back-to-heading t)))
  11699. (line-beginning-position 2))))))
  11700. (defun org-add-planning-info (what &optional time &rest remove)
  11701. "Insert new timestamp with keyword in the planning line.
  11702. WHAT indicates what kind of time stamp to add. It is a symbol
  11703. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11704. the time to use. If none is given, the user is prompted for
  11705. a date. REMOVE indicates what kind of entries to remove. An old
  11706. WHAT entry will also be removed."
  11707. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11708. (catch 'exit
  11709. (when (and (memq what '(scheduled deadline))
  11710. (or (not time)
  11711. (and (stringp time)
  11712. (string-match "^[-+]+[0-9]" time))))
  11713. ;; Try to get a default date/time from existing timestamp
  11714. (save-excursion
  11715. (org-back-to-heading t)
  11716. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11717. (when (re-search-forward (if (eq what 'scheduled)
  11718. org-scheduled-time-regexp
  11719. org-deadline-time-regexp)
  11720. end t)
  11721. (setq ts (match-string 1)
  11722. default-time (apply 'encode-time (org-parse-time-string ts))
  11723. default-input (and ts (org-get-compact-tod ts)))))))
  11724. (when what
  11725. (setq time
  11726. (if (stringp time)
  11727. ;; This is a string (relative or absolute), set
  11728. ;; proper date.
  11729. (apply #'encode-time
  11730. (org-read-date-analyze
  11731. time default-time (decode-time default-time)))
  11732. ;; If necessary, get the time from the user
  11733. (or time (org-read-date nil 'to-time nil nil
  11734. default-time default-input)))))
  11735. (org-with-wide-buffer
  11736. (org-back-to-heading t)
  11737. (forward-line)
  11738. (unless (bolp) (insert "\n"))
  11739. (cond ((looking-at-p org-planning-line-re)
  11740. ;; Move to current indentation.
  11741. (skip-chars-forward " \t")
  11742. ;; Check if we have to remove something.
  11743. (dolist (type (if what (cons what remove) remove))
  11744. (save-excursion
  11745. (when (re-search-forward
  11746. (cl-case type
  11747. (closed org-closed-time-regexp)
  11748. (deadline org-deadline-time-regexp)
  11749. (scheduled org-scheduled-time-regexp)
  11750. (otherwise
  11751. (error "Invalid planning type: %s" type)))
  11752. (line-end-position) t)
  11753. ;; Delete until next keyword or end of line.
  11754. (delete-region
  11755. (match-beginning 0)
  11756. (if (re-search-forward org-keyword-time-not-clock-regexp
  11757. (line-end-position)
  11758. t)
  11759. (match-beginning 0)
  11760. (line-end-position))))))
  11761. ;; If there is nothing more to add and no more keyword
  11762. ;; is left, remove the line completely.
  11763. (if (and (looking-at-p "[ \t]*$") (not what))
  11764. (delete-region (line-beginning-position)
  11765. (line-beginning-position 2))
  11766. ;; If we removed last keyword, do not leave trailing
  11767. ;; white space at the end of line.
  11768. (let ((p (point)))
  11769. (save-excursion
  11770. (end-of-line)
  11771. (unless (= (skip-chars-backward " \t" p) 0)
  11772. (delete-region (point) (line-end-position)))))))
  11773. ((not what) (throw 'exit nil)) ; Nothing to do.
  11774. (t (insert-before-markers "\n")
  11775. (backward-char 1)
  11776. (when org-adapt-indentation
  11777. (indent-to-column (1+ (org-outline-level))))))
  11778. (when what
  11779. ;; Insert planning keyword.
  11780. (insert (cl-case what
  11781. (closed org-closed-string)
  11782. (deadline org-deadline-string)
  11783. (scheduled org-scheduled-string)
  11784. (otherwise (error "Invalid planning type: %s" what)))
  11785. " ")
  11786. ;; Insert associated timestamp.
  11787. (let ((ts (org-insert-time-stamp
  11788. time
  11789. (or org-time-was-given
  11790. (and (eq what 'closed) org-log-done-with-time))
  11791. (eq what 'closed)
  11792. nil nil (list org-end-time-was-given))))
  11793. (unless (eolp) (insert " "))
  11794. ts))))))
  11795. (defvar org-log-note-marker (make-marker)
  11796. "Marker pointing at the entry where the note is to be inserted.")
  11797. (defvar org-log-note-purpose nil)
  11798. (defvar org-log-note-state nil)
  11799. (defvar org-log-note-previous-state nil)
  11800. (defvar org-log-note-extra nil)
  11801. (defvar org-log-note-window-configuration nil)
  11802. (defvar org-log-note-return-to (make-marker))
  11803. (defvar org-log-note-effective-time nil
  11804. "Remembered current time so that dynamically scoped
  11805. `org-extend-today-until' affects timestamps in state change log")
  11806. (defvar org-log-post-message nil
  11807. "Message to be displayed after a log note has been stored.
  11808. The auto-repeater uses this.")
  11809. (defun org-add-note ()
  11810. "Add a note to the current entry.
  11811. This is done in the same way as adding a state change note."
  11812. (interactive)
  11813. (org-add-log-setup 'note))
  11814. (defun org-log-beginning (&optional create)
  11815. "Return expected start of log notes in current entry.
  11816. When optional argument CREATE is non-nil, the function creates
  11817. a drawer to store notes, if necessary. Returned position ignores
  11818. narrowing."
  11819. (org-with-wide-buffer
  11820. (let ((drawer (org-log-into-drawer)))
  11821. (cond
  11822. (drawer
  11823. (org-end-of-meta-data)
  11824. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11825. (end (if (org-at-heading-p) (point)
  11826. (save-excursion (outline-next-heading) (point))))
  11827. (case-fold-search t))
  11828. (catch 'exit
  11829. ;; Try to find existing drawer.
  11830. (while (re-search-forward regexp end t)
  11831. (let ((element (org-element-at-point)))
  11832. (when (eq (org-element-type element) 'drawer)
  11833. (let ((cend (org-element-property :contents-end element)))
  11834. (when (and (not org-log-states-order-reversed) cend)
  11835. (goto-char cend)))
  11836. (throw 'exit nil))))
  11837. ;; No drawer found. Create one, if permitted.
  11838. (when create
  11839. (unless (bolp) (insert "\n"))
  11840. (let ((beg (point)))
  11841. (insert ":" drawer ":\n:END:\n")
  11842. (org-indent-region beg (point))
  11843. (org-flag-region
  11844. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11845. (end-of-line -1)))))
  11846. (t
  11847. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11848. (skip-chars-forward " \t\n")
  11849. (beginning-of-line)
  11850. (unless org-log-states-order-reversed
  11851. (org-skip-over-state-notes)
  11852. (skip-chars-backward " \t\n")
  11853. (forward-line)))))
  11854. (if (bolp) (point) (line-beginning-position 2))))
  11855. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11856. "Set up the post command hook to take a note.
  11857. If this is about to TODO state change, the new state is expected in STATE.
  11858. HOW is an indicator what kind of note should be created.
  11859. EXTRA is additional text that will be inserted into the notes buffer."
  11860. (move-marker org-log-note-marker (point))
  11861. (setq org-log-note-purpose purpose
  11862. org-log-note-state state
  11863. org-log-note-previous-state prev-state
  11864. org-log-note-how how
  11865. org-log-note-extra extra
  11866. org-log-note-effective-time (org-current-effective-time))
  11867. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11868. (defun org-skip-over-state-notes ()
  11869. "Skip past the list of State notes in an entry."
  11870. (when (ignore-errors (goto-char (org-in-item-p)))
  11871. (let* ((struct (org-list-struct))
  11872. (prevs (org-list-prevs-alist struct))
  11873. (regexp
  11874. (concat "[ \t]*- +"
  11875. (replace-regexp-in-string
  11876. " +" " +"
  11877. (org-replace-escapes
  11878. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11879. `(("%d" . ,org-ts-regexp-inactive)
  11880. ("%D" . ,org-ts-regexp)
  11881. ("%s" . "\"\\S-+\"")
  11882. ("%S" . "\"\\S-+\"")
  11883. ("%t" . ,org-ts-regexp-inactive)
  11884. ("%T" . ,org-ts-regexp)
  11885. ("%u" . ".*?")
  11886. ("%U" . ".*?")))))))
  11887. (while (looking-at-p regexp)
  11888. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11889. (org-list-get-item-end (point) struct)))))))
  11890. (defun org-add-log-note (&optional _purpose)
  11891. "Pop up a window for taking a note, and add this note later."
  11892. (remove-hook 'post-command-hook 'org-add-log-note)
  11893. (setq org-log-note-window-configuration (current-window-configuration))
  11894. (delete-other-windows)
  11895. (move-marker org-log-note-return-to (point))
  11896. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11897. (goto-char org-log-note-marker)
  11898. (org-switch-to-buffer-other-window "*Org Note*")
  11899. (erase-buffer)
  11900. (if (memq org-log-note-how '(time state))
  11901. (org-store-log-note)
  11902. (let ((org-inhibit-startup t)) (org-mode))
  11903. (insert (format "# Insert note for %s.
  11904. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11905. (cond
  11906. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  11907. ((eq org-log-note-purpose 'done) "closed todo item")
  11908. ((eq org-log-note-purpose 'state)
  11909. (format "state change from \"%s\" to \"%s\""
  11910. (or org-log-note-previous-state "")
  11911. (or org-log-note-state "")))
  11912. ((eq org-log-note-purpose 'reschedule)
  11913. "rescheduling")
  11914. ((eq org-log-note-purpose 'delschedule)
  11915. "no longer scheduled")
  11916. ((eq org-log-note-purpose 'redeadline)
  11917. "changing deadline")
  11918. ((eq org-log-note-purpose 'deldeadline)
  11919. "removing deadline")
  11920. ((eq org-log-note-purpose 'refile)
  11921. "refiling")
  11922. ((eq org-log-note-purpose 'note)
  11923. "this entry")
  11924. (t (error "This should not happen")))))
  11925. (when org-log-note-extra (insert org-log-note-extra))
  11926. (setq-local org-finish-function 'org-store-log-note)
  11927. (run-hooks 'org-log-buffer-setup-hook)))
  11928. (defvar org-note-abort nil) ; dynamically scoped
  11929. (defun org-store-log-note ()
  11930. "Finish taking a log note, and insert it to where it belongs."
  11931. (let ((txt (prog1 (buffer-string)
  11932. (kill-buffer)))
  11933. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11934. lines)
  11935. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11936. (setq txt (replace-match "" t t txt)))
  11937. (when (string-match "\\s-+\\'" txt)
  11938. (setq txt (replace-match "" t t txt)))
  11939. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11940. (when (org-string-nw-p note)
  11941. (setq note
  11942. (org-replace-escapes
  11943. note
  11944. (list (cons "%u" (user-login-name))
  11945. (cons "%U" user-full-name)
  11946. (cons "%t" (format-time-string
  11947. (org-time-stamp-format 'long 'inactive)
  11948. org-log-note-effective-time))
  11949. (cons "%T" (format-time-string
  11950. (org-time-stamp-format 'long nil)
  11951. org-log-note-effective-time))
  11952. (cons "%d" (format-time-string
  11953. (org-time-stamp-format nil 'inactive)
  11954. org-log-note-effective-time))
  11955. (cons "%D" (format-time-string
  11956. (org-time-stamp-format nil nil)
  11957. org-log-note-effective-time))
  11958. (cons "%s" (cond
  11959. ((not org-log-note-state) "")
  11960. ((string-match-p org-ts-regexp
  11961. org-log-note-state)
  11962. (format "\"[%s]\""
  11963. (substring org-log-note-state 1 -1)))
  11964. (t (format "\"%s\"" org-log-note-state))))
  11965. (cons "%S"
  11966. (cond
  11967. ((not org-log-note-previous-state) "")
  11968. ((string-match-p org-ts-regexp
  11969. org-log-note-previous-state)
  11970. (format "\"[%s]\""
  11971. (substring
  11972. org-log-note-previous-state 1 -1)))
  11973. (t (format "\"%s\""
  11974. org-log-note-previous-state)))))))
  11975. (when lines (setq note (concat note " \\\\")))
  11976. (push note lines))
  11977. (when (and lines (not org-note-abort))
  11978. (with-current-buffer (marker-buffer org-log-note-marker)
  11979. (org-with-wide-buffer
  11980. ;; Find location for the new note.
  11981. (goto-char org-log-note-marker)
  11982. (set-marker org-log-note-marker nil)
  11983. ;; Note associated to a clock is to be located right after
  11984. ;; the clock. Do not move point.
  11985. (unless (eq org-log-note-purpose 'clock-out)
  11986. (goto-char (org-log-beginning t)))
  11987. ;; Make sure point is at the beginning of an empty line.
  11988. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  11989. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  11990. ;; In an existing list, add a new item at the top level.
  11991. ;; Otherwise, indent line like a regular one.
  11992. (let ((itemp (org-in-item-p)))
  11993. (if itemp
  11994. (indent-line-to
  11995. (let ((struct (save-excursion
  11996. (goto-char itemp) (org-list-struct))))
  11997. (org-list-get-ind (org-list-get-top-point struct) struct)))
  11998. (org-indent-line)))
  11999. (insert (org-list-bullet-string "-") (pop lines))
  12000. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12001. (dolist (line lines)
  12002. (insert "\n")
  12003. (indent-line-to ind)
  12004. (insert line)))
  12005. (message "Note stored")
  12006. (org-back-to-heading t))
  12007. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12008. ;; from within `org-add-log-note' because `buffer-undo-list'
  12009. ;; is then modified outside of `org-with-remote-undo'.
  12010. (when (eq this-command 'org-agenda-todo)
  12011. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12012. ;; Don't add undo information when called from `org-agenda-todo'.
  12013. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12014. (set-window-configuration org-log-note-window-configuration)
  12015. (with-current-buffer (marker-buffer org-log-note-return-to)
  12016. (goto-char org-log-note-return-to))
  12017. (move-marker org-log-note-return-to nil)
  12018. (when org-log-post-message (message "%s" org-log-post-message))))
  12019. (defun org-remove-empty-drawer-at (pos)
  12020. "Remove an empty drawer at position POS.
  12021. POS may also be a marker."
  12022. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12023. (org-with-wide-buffer
  12024. (goto-char pos)
  12025. (let ((drawer (org-element-at-point)))
  12026. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12027. (not (org-element-property :contents-begin drawer)))
  12028. (delete-region (org-element-property :begin drawer)
  12029. (progn (goto-char (org-element-property :end drawer))
  12030. (skip-chars-backward " \r\t\n")
  12031. (forward-line)
  12032. (point))))))))
  12033. (defvar org-ts-type nil)
  12034. (defun org-sparse-tree (&optional arg type)
  12035. "Create a sparse tree, prompt for the details.
  12036. This command can create sparse trees. You first need to select the type
  12037. of match used to create the tree:
  12038. t Show all TODO entries.
  12039. T Show entries with a specific TODO keyword.
  12040. m Show entries selected by a tags/property match.
  12041. p Enter a property name and its value (both with completion on existing
  12042. names/values) and show entries with that property.
  12043. r Show entries matching a regular expression (`/' can be used as well).
  12044. b Show deadlines and scheduled items before a date.
  12045. a Show deadlines and scheduled items after a date.
  12046. d Show deadlines due within `org-deadline-warning-days'.
  12047. D Show deadlines and scheduled items between a date range."
  12048. (interactive "P")
  12049. (setq type (or type org-sparse-tree-default-date-type))
  12050. (setq org-ts-type type)
  12051. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12052. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12053. \[c]ycle through date types: %s"
  12054. (cl-case type
  12055. (all "all timestamps")
  12056. (scheduled "only scheduled")
  12057. (deadline "only deadline")
  12058. (active "only active timestamps")
  12059. (inactive "only inactive timestamps")
  12060. (closed "with a closed time-stamp")
  12061. (otherwise "scheduled/deadline")))
  12062. (let ((answer (read-char-exclusive)))
  12063. (cl-case answer
  12064. (?c
  12065. (org-sparse-tree
  12066. arg
  12067. (cadr
  12068. (memq type '(nil all scheduled deadline active inactive closed)))))
  12069. (?d (call-interactively 'org-check-deadlines))
  12070. (?b (call-interactively 'org-check-before-date))
  12071. (?a (call-interactively 'org-check-after-date))
  12072. (?D (call-interactively 'org-check-dates-range))
  12073. (?t (call-interactively 'org-show-todo-tree))
  12074. (?T (org-show-todo-tree '(4)))
  12075. (?m (call-interactively 'org-match-sparse-tree))
  12076. ((?p ?P)
  12077. (let* ((kwd (completing-read
  12078. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12079. (value (completing-read
  12080. "Value: " (mapcar #'list (org-property-values kwd)))))
  12081. (unless (string-match "\\`{.*}\\'" value)
  12082. (setq value (concat "\"" value "\"")))
  12083. (org-match-sparse-tree arg (concat kwd "=" value))))
  12084. ((?r ?R ?/) (call-interactively 'org-occur))
  12085. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12086. (defvar-local org-occur-highlights nil
  12087. "List of overlays used for occur matches.")
  12088. (defvar-local org-occur-parameters nil
  12089. "Parameters of the active org-occur calls.
  12090. This is a list, each call to org-occur pushes as cons cell,
  12091. containing the regular expression and the callback, onto the list.
  12092. The list can contain several entries if `org-occur' has been called
  12093. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12094. will only contain one set of parameters. When the highlights are
  12095. removed (for example with `C-c C-c', or with the next edit (depending
  12096. on `org-remove-highlights-with-change'), this variable is emptied
  12097. as well.")
  12098. (defun org-occur (regexp &optional keep-previous callback)
  12099. "Make a compact tree which shows all matches of REGEXP.
  12100. The tree will show the lines where the regexp matches, and any other context
  12101. defined in `org-show-context-detail', which see.
  12102. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12103. done by a previous call to `org-occur' will be kept, to allow stacking of
  12104. calls to this command.
  12105. Optional argument CALLBACK can be a function of no argument. In this case,
  12106. it is called with point at the end of the match, match data being set
  12107. accordingly. Current match is shown only if the return value is non-nil.
  12108. The function must neither move point nor alter narrowing."
  12109. (interactive "sRegexp: \nP")
  12110. (when (equal regexp "")
  12111. (user-error "Regexp cannot be empty"))
  12112. (unless keep-previous
  12113. (org-remove-occur-highlights nil nil t))
  12114. (push (cons regexp callback) org-occur-parameters)
  12115. (let ((cnt 0))
  12116. (save-excursion
  12117. (goto-char (point-min))
  12118. (when (or (not keep-previous) ; do not want to keep
  12119. (not org-occur-highlights)) ; no previous matches
  12120. ;; hide everything
  12121. (org-overview))
  12122. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12123. (isearch-no-upper-case-p regexp t)
  12124. org-occur-case-fold-search)))
  12125. (while (re-search-forward regexp nil t)
  12126. (when (or (not callback)
  12127. (save-match-data (funcall callback)))
  12128. (setq cnt (1+ cnt))
  12129. (when org-highlight-sparse-tree-matches
  12130. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12131. (org-show-context 'occur-tree)))))
  12132. (when org-remove-highlights-with-change
  12133. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12134. nil 'local))
  12135. (unless org-sparse-tree-open-archived-trees
  12136. (org-hide-archived-subtrees (point-min) (point-max)))
  12137. (run-hooks 'org-occur-hook)
  12138. (when (called-interactively-p 'interactive)
  12139. (message "%d match(es) for regexp %s" cnt regexp))
  12140. cnt))
  12141. (defun org-occur-next-match (&optional n _reset)
  12142. "Function for `next-error-function' to find sparse tree matches.
  12143. N is the number of matches to move, when negative move backwards.
  12144. This function always goes back to the starting point when no
  12145. match is found."
  12146. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12147. (search-func (if (< n 0)
  12148. 'previous-single-char-property-change
  12149. 'next-single-char-property-change))
  12150. (n (abs n))
  12151. (pos (point))
  12152. p1)
  12153. (catch 'exit
  12154. (while (setq p1 (funcall search-func (point) 'org-type))
  12155. (when (equal p1 limit)
  12156. (goto-char pos)
  12157. (user-error "No more matches"))
  12158. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12159. (setq n (1- n))
  12160. (when (= n 0)
  12161. (goto-char p1)
  12162. (throw 'exit (point))))
  12163. (goto-char p1))
  12164. (goto-char p1)
  12165. (user-error "No more matches"))))
  12166. (defun org-highlight-new-match (beg end)
  12167. "Highlight from BEG to END and mark the highlight is an occur headline."
  12168. (let ((ov (make-overlay beg end)))
  12169. (overlay-put ov 'face 'secondary-selection)
  12170. (overlay-put ov 'org-type 'org-occur)
  12171. (push ov org-occur-highlights)))
  12172. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12173. "Remove the occur highlights from the buffer.
  12174. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12175. from the `before-change-functions' in the current buffer."
  12176. (interactive)
  12177. (unless org-inhibit-highlight-removal
  12178. (mapc #'delete-overlay org-occur-highlights)
  12179. (setq org-occur-highlights nil)
  12180. (setq org-occur-parameters nil)
  12181. (unless noremove
  12182. (remove-hook 'before-change-functions
  12183. 'org-remove-occur-highlights 'local))))
  12184. ;;;; Priorities
  12185. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12186. "Regular expression matching the priority indicator.")
  12187. (defvar org-remove-priority-next-time nil)
  12188. (defun org-priority-up ()
  12189. "Increase the priority of the current item."
  12190. (interactive)
  12191. (org-priority 'up))
  12192. (defun org-priority-down ()
  12193. "Decrease the priority of the current item."
  12194. (interactive)
  12195. (org-priority 'down))
  12196. (defun org-priority (&optional action _show)
  12197. "Change the priority of an item.
  12198. ACTION can be `set', `up', `down', or a character."
  12199. (interactive "P")
  12200. (if (equal action '(4))
  12201. (org-show-priority)
  12202. (unless org-enable-priority-commands
  12203. (user-error "Priority commands are disabled"))
  12204. (setq action (or action 'set))
  12205. (let (current new news have remove)
  12206. (save-excursion
  12207. (org-back-to-heading t)
  12208. (when (looking-at org-priority-regexp)
  12209. (setq current (string-to-char (match-string 2))
  12210. have t))
  12211. (cond
  12212. ((eq action 'remove)
  12213. (setq remove t new ?\ ))
  12214. ((or (eq action 'set)
  12215. (integerp action))
  12216. (if (not (eq action 'set))
  12217. (setq new action)
  12218. (message "Priority %c-%c, SPC to remove: "
  12219. org-highest-priority org-lowest-priority)
  12220. (save-match-data
  12221. (setq new (read-char-exclusive))))
  12222. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12223. (= (upcase org-lowest-priority) org-lowest-priority))
  12224. (setq new (upcase new)))
  12225. (cond ((equal new ?\ ) (setq remove t))
  12226. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12227. (user-error "Priority must be between `%c' and `%c'"
  12228. org-highest-priority org-lowest-priority))))
  12229. ((eq action 'up)
  12230. (setq new (if have
  12231. (1- current) ; normal cycling
  12232. ;; last priority was empty
  12233. (if (eq last-command this-command)
  12234. org-lowest-priority ; wrap around empty to lowest
  12235. ;; default
  12236. (if org-priority-start-cycle-with-default
  12237. org-default-priority
  12238. (1- org-default-priority))))))
  12239. ((eq action 'down)
  12240. (setq new (if have
  12241. (1+ current) ; normal cycling
  12242. ;; last priority was empty
  12243. (if (eq last-command this-command)
  12244. org-highest-priority ; wrap around empty to highest
  12245. ;; default
  12246. (if org-priority-start-cycle-with-default
  12247. org-default-priority
  12248. (1+ org-default-priority))))))
  12249. (t (user-error "Invalid action")))
  12250. (when (or (< (upcase new) org-highest-priority)
  12251. (> (upcase new) org-lowest-priority))
  12252. (if (and (memq action '(up down))
  12253. (not have) (not (eq last-command this-command)))
  12254. ;; `new' is from default priority
  12255. (error
  12256. "The default can not be set, see `org-default-priority' why")
  12257. ;; normal cycling: `new' is beyond highest/lowest priority
  12258. ;; and is wrapped around to the empty priority
  12259. (setq remove t)))
  12260. (setq news (format "%c" new))
  12261. (if have
  12262. (if remove
  12263. (replace-match "" t t nil 1)
  12264. (replace-match news t t nil 2))
  12265. (if remove
  12266. (user-error "No priority cookie found in line")
  12267. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12268. (if (match-end 2)
  12269. (progn
  12270. (goto-char (match-end 2))
  12271. (insert " [#" news "]"))
  12272. (goto-char (match-beginning 3))
  12273. (insert "[#" news "] "))))
  12274. (org-set-tags nil 'align))
  12275. (if remove
  12276. (message "Priority removed")
  12277. (message "Priority of current item set to %s" news)))))
  12278. (defun org-show-priority ()
  12279. "Show the priority of the current item.
  12280. This priority is composed of the main priority given with the [#A] cookies,
  12281. and by additional input from the age of a schedules or deadline entry."
  12282. (interactive)
  12283. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12284. (org-get-at-bol 'priority)
  12285. (save-excursion
  12286. (save-match-data
  12287. (beginning-of-line)
  12288. (and (looking-at org-heading-regexp)
  12289. (org-get-priority (match-string 0))))))))
  12290. (message "Priority is %d" (if pri pri -1000))))
  12291. (defun org-get-priority (s)
  12292. "Find priority cookie and return priority."
  12293. (save-match-data
  12294. (if (functionp org-get-priority-function)
  12295. (funcall org-get-priority-function)
  12296. (if (not (string-match org-priority-regexp s))
  12297. (* 1000 (- org-lowest-priority org-default-priority))
  12298. (* 1000 (- org-lowest-priority
  12299. (string-to-char (match-string 2 s))))))))
  12300. ;;;; Tags
  12301. (defvar org-agenda-archives-mode)
  12302. (defvar org-map-continue-from nil
  12303. "Position from where mapping should continue.
  12304. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12305. (defvar org-scanner-tags nil
  12306. "The current tag list while the tags scanner is running.")
  12307. (defvar org-trust-scanner-tags nil
  12308. "Should `org-get-tags' use the tags for the scanner.
  12309. This is for internal dynamical scoping only.
  12310. When this is non-nil, the function `org-get-tags' will return the value
  12311. of `org-scanner-tags' instead of building the list by itself. This
  12312. can lead to large speed-ups when the tags scanner is used in a file with
  12313. many entries, and when the list of tags is retrieved, for example to
  12314. obtain a list of properties. Building the tags list for each entry in such
  12315. a file becomes an N^2 operation - but with this variable set, it scales
  12316. as N.")
  12317. (defvar org--matcher-tags-todo-only nil)
  12318. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12319. "Scan headline tags with inheritance and produce output ACTION.
  12320. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12321. or `agenda' to produce an entry list for an agenda view. It can also be
  12322. a Lisp form or a function that should be called at each matched headline, in
  12323. this case the return value is a list of all return values from these calls.
  12324. MATCHER is a function accepting three arguments, returning
  12325. a non-nil value whenever a given set of tags qualifies a headline
  12326. for inclusion. See `org-make-tags-matcher' for more information.
  12327. As a special case, it can also be set to t (respectively nil) in
  12328. order to match all (respectively none) headline.
  12329. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12330. included in the output.
  12331. START-LEVEL can be a string with asterisks, reducing the scope to
  12332. headlines matching this string."
  12333. (require 'org-agenda)
  12334. (let* ((re (concat "^"
  12335. (if start-level
  12336. ;; Get the correct level to match
  12337. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12338. org-outline-regexp)
  12339. " *\\(\\<\\("
  12340. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12341. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12342. (props (list 'face 'default
  12343. 'done-face 'org-agenda-done
  12344. 'undone-face 'default
  12345. 'mouse-face 'highlight
  12346. 'org-not-done-regexp org-not-done-regexp
  12347. 'org-todo-regexp org-todo-regexp
  12348. 'org-complex-heading-regexp org-complex-heading-regexp
  12349. 'help-echo
  12350. (format "mouse-2 or RET jump to Org file %S"
  12351. (abbreviate-file-name
  12352. (or (buffer-file-name (buffer-base-buffer))
  12353. (buffer-name (buffer-base-buffer)))))))
  12354. (org-map-continue-from nil)
  12355. lspos tags tags-list
  12356. (tags-alist (list (cons 0 org-file-tags)))
  12357. (llast 0) rtn rtn1 level category i txt
  12358. todo marker entry priority
  12359. ts-date ts-date-type ts-date-pair)
  12360. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12361. (setq action (list 'lambda nil action)))
  12362. (save-excursion
  12363. (goto-char (point-min))
  12364. (when (eq action 'sparse-tree)
  12365. (org-overview)
  12366. (org-remove-occur-highlights))
  12367. (while (let (case-fold-search)
  12368. (re-search-forward re nil t))
  12369. (setq org-map-continue-from nil)
  12370. (catch :skip
  12371. ;; Ignore closing parts of inline tasks.
  12372. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12373. (throw :skip t))
  12374. (setq todo
  12375. ;; TODO: is the 1-2 difference a bug?
  12376. (when (match-end 1) (match-string-no-properties 2))
  12377. tags (when (match-end 4) (match-string-no-properties 4)))
  12378. (goto-char (setq lspos (match-beginning 0)))
  12379. (setq level (org-reduced-level (org-outline-level))
  12380. category (org-get-category))
  12381. (when (eq action 'agenda)
  12382. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12383. ts-date (car ts-date-pair)
  12384. ts-date-type (cdr ts-date-pair)))
  12385. (setq i llast llast level)
  12386. ;; remove tag lists from same and sublevels
  12387. (while (>= i level)
  12388. (when (setq entry (assoc i tags-alist))
  12389. (setq tags-alist (delete entry tags-alist)))
  12390. (setq i (1- i)))
  12391. ;; add the next tags
  12392. (when tags
  12393. (setq tags (org-split-string tags ":")
  12394. tags-alist
  12395. (cons (cons level tags) tags-alist)))
  12396. ;; compile tags for current headline
  12397. (setq tags-list
  12398. (if org-use-tag-inheritance
  12399. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12400. tags)
  12401. org-scanner-tags tags-list)
  12402. (when org-use-tag-inheritance
  12403. (setcdr (car tags-alist)
  12404. (mapcar (lambda (x)
  12405. (setq x (copy-sequence x))
  12406. (org-add-prop-inherited x))
  12407. (cdar tags-alist))))
  12408. (when (and tags org-use-tag-inheritance
  12409. (or (not (eq t org-use-tag-inheritance))
  12410. org-tags-exclude-from-inheritance))
  12411. ;; Selective inheritance, remove uninherited ones.
  12412. (setcdr (car tags-alist)
  12413. (org-remove-uninherited-tags (cdar tags-alist))))
  12414. (when (and
  12415. ;; eval matcher only when the todo condition is OK
  12416. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12417. (if (functionp matcher)
  12418. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12419. (funcall matcher todo tags-list level))
  12420. matcher))
  12421. ;; Call the skipper, but return t if it does not
  12422. ;; skip, so that the `and' form continues evaluating.
  12423. (progn
  12424. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12425. t)
  12426. ;; Check if timestamps are deselecting this entry
  12427. (or (not todo-only)
  12428. (and (member todo org-todo-keywords-1)
  12429. (or (not org-agenda-tags-todo-honor-ignore-options)
  12430. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12431. ;; select this headline
  12432. (cond
  12433. ((eq action 'sparse-tree)
  12434. (and org-highlight-sparse-tree-matches
  12435. (org-get-heading) (match-end 0)
  12436. (org-highlight-new-match
  12437. (match-beginning 1) (match-end 1)))
  12438. (org-show-context 'tags-tree))
  12439. ((eq action 'agenda)
  12440. (setq txt (org-agenda-format-item
  12441. ""
  12442. (concat
  12443. (if (eq org-tags-match-list-sublevels 'indented)
  12444. (make-string (1- level) ?.) "")
  12445. (org-get-heading))
  12446. (make-string level ?\s)
  12447. category
  12448. tags-list)
  12449. priority (org-get-priority txt))
  12450. (goto-char lspos)
  12451. (setq marker (org-agenda-new-marker))
  12452. (org-add-props txt props
  12453. 'org-marker marker 'org-hd-marker marker 'org-category category
  12454. 'todo-state todo
  12455. 'ts-date ts-date
  12456. 'priority priority
  12457. 'type (concat "tagsmatch" ts-date-type))
  12458. (push txt rtn))
  12459. ((functionp action)
  12460. (setq org-map-continue-from nil)
  12461. (save-excursion
  12462. (setq rtn1 (funcall action))
  12463. (push rtn1 rtn)))
  12464. (t (user-error "Invalid action")))
  12465. ;; if we are to skip sublevels, jump to end of subtree
  12466. (unless org-tags-match-list-sublevels
  12467. (org-end-of-subtree t)
  12468. (backward-char 1))))
  12469. ;; Get the correct position from where to continue
  12470. (if org-map-continue-from
  12471. (goto-char org-map-continue-from)
  12472. (and (= (point) lspos) (end-of-line 1)))))
  12473. (when (and (eq action 'sparse-tree)
  12474. (not org-sparse-tree-open-archived-trees))
  12475. (org-hide-archived-subtrees (point-min) (point-max)))
  12476. (nreverse rtn)))
  12477. (defun org-remove-uninherited-tags (tags)
  12478. "Remove all tags that are not inherited from the list TAGS."
  12479. (cond
  12480. ((eq org-use-tag-inheritance t)
  12481. (if org-tags-exclude-from-inheritance
  12482. (org-delete-all org-tags-exclude-from-inheritance tags)
  12483. tags))
  12484. ((not org-use-tag-inheritance) nil)
  12485. ((stringp org-use-tag-inheritance)
  12486. (delq nil (mapcar
  12487. (lambda (x)
  12488. (if (and (string-match org-use-tag-inheritance x)
  12489. (not (member x org-tags-exclude-from-inheritance)))
  12490. x nil))
  12491. tags)))
  12492. ((listp org-use-tag-inheritance)
  12493. (delq nil (mapcar
  12494. (lambda (x)
  12495. (if (member x org-use-tag-inheritance) x nil))
  12496. tags)))))
  12497. (defun org-match-sparse-tree (&optional todo-only match)
  12498. "Create a sparse tree according to tags string MATCH.
  12499. MATCH is a string with match syntax. It can contain a selection
  12500. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12501. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12502. those. See the manual for details.
  12503. If optional argument TODO-ONLY is non-nil, only select lines that
  12504. are also TODO tasks."
  12505. (interactive "P")
  12506. (org-agenda-prepare-buffers (list (current-buffer)))
  12507. (let ((org--matcher-tags-todo-only todo-only))
  12508. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12509. org--matcher-tags-todo-only)))
  12510. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12511. (defvar org-cached-props nil)
  12512. (defun org-cached-entry-get (pom property)
  12513. (if (or (eq t org-use-property-inheritance)
  12514. (and (stringp org-use-property-inheritance)
  12515. (let ((case-fold-search t))
  12516. (string-match-p org-use-property-inheritance property)))
  12517. (and (listp org-use-property-inheritance)
  12518. (member-ignore-case property org-use-property-inheritance)))
  12519. ;; Caching is not possible, check it directly.
  12520. (org-entry-get pom property 'inherit)
  12521. ;; Get all properties, so we can do complicated checks easily.
  12522. (cdr (assoc-string property
  12523. (or org-cached-props
  12524. (setq org-cached-props (org-entry-properties pom)))
  12525. t))))
  12526. (defun org-global-tags-completion-table (&optional files)
  12527. "Return the list of all tags in all agenda buffer/files.
  12528. Optional FILES argument is a list of files which can be used
  12529. instead of the agenda files."
  12530. (save-excursion
  12531. (org-uniquify
  12532. (delq nil
  12533. (apply #'append
  12534. (mapcar
  12535. (lambda (file)
  12536. (set-buffer (find-file-noselect file))
  12537. (org-tag-add-to-alist
  12538. (org-get-buffer-tags)
  12539. (mapcar (lambda (x)
  12540. (and (stringp (car-safe x))
  12541. (list (car-safe x))))
  12542. org-current-tag-alist)))
  12543. (if (car-safe files) files
  12544. (org-agenda-files))))))))
  12545. (defun org-make-tags-matcher (match)
  12546. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12547. Returns a cons of the selection string MATCH and a function
  12548. implementing the matcher.
  12549. The matcher is to be called at an Org entry, with point on the
  12550. headline, and returns non-nil if the entry matches the selection
  12551. string MATCH. It must be called with three arguments: the TODO
  12552. keyword at the entry (or nil if none), the list of all tags at
  12553. the entry including inherited ones and the reduced level of the
  12554. headline. Additionally, the category of the entry, if any, must
  12555. be specified as the text property `org-category' on the headline.
  12556. This function sets the variable `org--matcher-tags-todo-only' to
  12557. a non-nil value if the matcher restricts matching to TODO
  12558. entries, otherwise it is not touched.
  12559. See also `org-scan-tags'."
  12560. (unless match
  12561. ;; Get a new match request, with completion against the global
  12562. ;; tags table and the local tags in current buffer.
  12563. (let ((org-last-tags-completion-table
  12564. (org-tag-add-to-alist
  12565. (org-get-buffer-tags)
  12566. (org-global-tags-completion-table))))
  12567. (setq match
  12568. (completing-read
  12569. "Match: "
  12570. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12571. (let ((match0 match)
  12572. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12573. (start 0)
  12574. tagsmatch todomatch tagsmatcher todomatcher)
  12575. ;; Expand group tags.
  12576. (setq match (org-tags-expand match))
  12577. ;; Check if there is a TODO part of this match, which would be the
  12578. ;; part after a "/". To make sure that this slash is not part of
  12579. ;; a property value to be matched against, we also check that
  12580. ;; there is no / after that slash. First, find the last slash.
  12581. (let ((s 0))
  12582. (while (string-match "/+" match s)
  12583. (setq start (match-beginning 0))
  12584. (setq s (match-end 0))))
  12585. (if (and (string-match "/+" match start)
  12586. (not (string-match-p "\"" match start)))
  12587. ;; Match contains also a TODO-matching request.
  12588. (progn
  12589. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12590. (setq todomatch (substring match (match-end 0)))
  12591. (when (string-prefix-p "!" todomatch)
  12592. (setq org--matcher-tags-todo-only t)
  12593. (setq todomatch (substring todomatch 1)))
  12594. (when (string-match "\\`\\s-*\\'" todomatch)
  12595. (setq todomatch nil)))
  12596. ;; Only matching tags.
  12597. (setq tagsmatch match)
  12598. (setq todomatch nil))
  12599. ;; Make the tags matcher.
  12600. (when (org-string-nw-p tagsmatch)
  12601. (let ((orlist nil)
  12602. (orterms (org-split-string tagsmatch "|"))
  12603. term)
  12604. (while (setq term (pop orterms))
  12605. (while (and (equal (substring term -1) "\\") orterms)
  12606. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12607. (while (string-match re term)
  12608. (let* ((rest (substring term (match-end 0)))
  12609. (minus (and (match-end 1)
  12610. (equal (match-string 1 term) "-")))
  12611. (tag (save-match-data
  12612. (replace-regexp-in-string
  12613. "\\\\-" "-" (match-string 2 term))))
  12614. (regexp (eq (string-to-char tag) ?{))
  12615. (levelp (match-end 4))
  12616. (propp (match-end 5))
  12617. (mm
  12618. (cond
  12619. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12620. (levelp
  12621. `(,(org-op-to-function (match-string 3 term))
  12622. level
  12623. ,(string-to-number (match-string 4 term))))
  12624. (propp
  12625. (let* ((gv (pcase (upcase (match-string 5 term))
  12626. ("CATEGORY"
  12627. '(get-text-property (point) 'org-category))
  12628. ("TODO" 'todo)
  12629. (p `(org-cached-entry-get nil ,p))))
  12630. (pv (match-string 7 term))
  12631. (regexp (eq (string-to-char pv) ?{))
  12632. (strp (eq (string-to-char pv) ?\"))
  12633. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12634. (po (org-op-to-function (match-string 6 term)
  12635. (if timep 'time strp))))
  12636. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12637. (when timep (setq pv (org-matcher-time pv)))
  12638. (cond ((and regexp (eq po '/=))
  12639. `(not (string-match ,pv (or ,gv ""))))
  12640. (regexp `(string-match ,pv (or ,gv "")))
  12641. (strp `(,po (or ,gv "") ,pv))
  12642. (t
  12643. `(,po
  12644. (string-to-number (or ,gv ""))
  12645. ,(string-to-number pv))))))
  12646. (t `(member ,tag tags-list)))))
  12647. (push (if minus `(not ,mm) mm) tagsmatcher)
  12648. (setq term rest)))
  12649. (push `(and ,@tagsmatcher) orlist)
  12650. (setq tagsmatcher nil))
  12651. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12652. ;; Make the TODO matcher.
  12653. (when (org-string-nw-p todomatch)
  12654. (let ((orlist nil))
  12655. (dolist (term (org-split-string todomatch "|"))
  12656. (while (string-match re term)
  12657. (let* ((minus (and (match-end 1)
  12658. (equal (match-string 1 term) "-")))
  12659. (kwd (match-string 2 term))
  12660. (regexp (eq (string-to-char kwd) ?{))
  12661. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12662. `(equal todo ,kwd))))
  12663. (push (if minus `(not ,mm) mm) todomatcher))
  12664. (setq term (substring term (match-end 0))))
  12665. (push (if (> (length todomatcher) 1)
  12666. (cons 'and todomatcher)
  12667. (car todomatcher))
  12668. orlist)
  12669. (setq todomatcher nil))
  12670. (setq todomatcher (cons 'or orlist))))
  12671. ;; Return the string and function of the matcher. If no
  12672. ;; tags-specific or todo-specific matcher exists, match
  12673. ;; everything.
  12674. (let ((matcher (if (and tagsmatcher todomatcher)
  12675. `(and ,tagsmatcher ,todomatcher)
  12676. (or tagsmatcher todomatcher t))))
  12677. (when org--matcher-tags-todo-only
  12678. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12679. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12680. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12681. "Expand group tags in MATCH.
  12682. This replaces every group tag in MATCH with a regexp tag search.
  12683. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12684. will be replaced like this:
  12685. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12686. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12687. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12688. Replacing by a regexp preserves the structure of the match.
  12689. E.g., this expansion
  12690. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12691. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12692. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12693. A group tag in MATCH can contain regular expressions of its own.
  12694. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12695. will be replaced like this:
  12696. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12697. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12698. assumed to be a single group tag, and the function will return
  12699. the list of tags in this group.
  12700. When DOWNCASE is non-nil, expand downcased TAGS."
  12701. (if org-group-tags
  12702. (let* ((case-fold-search t)
  12703. (stable org-mode-syntax-table)
  12704. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12705. (taggroups (if downcased
  12706. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12707. taggroups)
  12708. taggroups))
  12709. (taggroups-keys (mapcar #'car taggroups))
  12710. (return-match (if downcased (downcase match) match))
  12711. (count 0)
  12712. (work-already-expanded tags-already-expanded)
  12713. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12714. ;; @ and _ are allowed as word-components in tags.
  12715. (modify-syntax-entry ?@ "w" stable)
  12716. (modify-syntax-entry ?_ "w" stable)
  12717. ;; Temporarily replace regexp-expressions in the match-expression.
  12718. (while (string-match "{.+?}" return-match)
  12719. (cl-incf count)
  12720. (push (match-string 0 return-match) regexps-in-match)
  12721. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12722. (while (and taggroups-keys
  12723. (with-syntax-table stable
  12724. (string-match
  12725. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12726. (regexp-opt taggroups-keys) "\\>\\)")
  12727. return-match)))
  12728. (let* ((dir (match-string 1 return-match))
  12729. (tag (match-string 2 return-match))
  12730. (tag (if downcased (downcase tag) tag)))
  12731. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12732. (member tag tags-already-expanded))
  12733. (setq tags-in-group (assoc tag taggroups))
  12734. (push tag work-already-expanded)
  12735. ;; Recursively expand each tag in the group, if the tag hasn't
  12736. ;; already been expanded. Restore the match-data after all recursive calls.
  12737. (save-match-data
  12738. (let (tags-expanded)
  12739. (dolist (x (cdr tags-in-group))
  12740. (if (and (member x taggroups-keys)
  12741. (not (member x work-already-expanded)))
  12742. (setq tags-expanded
  12743. (delete-dups
  12744. (append
  12745. (org-tags-expand x t downcased
  12746. work-already-expanded)
  12747. tags-expanded)))
  12748. (setq tags-expanded
  12749. (append (list x) tags-expanded)))
  12750. (setq work-already-expanded
  12751. (delete-dups
  12752. (append tags-expanded
  12753. work-already-expanded))))
  12754. (setq tags-in-group
  12755. (delete-dups (cons (car tags-in-group)
  12756. tags-expanded)))))
  12757. ;; Filter tag-regexps from tags.
  12758. (setq regexp-in-group-escaped
  12759. (delq nil (mapcar (lambda (x)
  12760. (if (stringp x)
  12761. (and (equal "{" (substring x 0 1))
  12762. (equal "}" (substring x -1))
  12763. x)
  12764. x))
  12765. tags-in-group))
  12766. regexp-in-group
  12767. (mapcar (lambda (x)
  12768. (substring x 1 -1))
  12769. regexp-in-group-escaped)
  12770. tags-in-group
  12771. (delq nil (mapcar (lambda (x)
  12772. (if (stringp x)
  12773. (and (not (equal "{" (substring x 0 1)))
  12774. (not (equal "}" (substring x -1)))
  12775. x)
  12776. x))
  12777. tags-in-group)))
  12778. ;; If single-as-list, do no more in the while-loop.
  12779. (if (not single-as-list)
  12780. (progn
  12781. (when regexp-in-group
  12782. (setq regexp-in-group
  12783. (concat "\\|"
  12784. (mapconcat 'identity regexp-in-group
  12785. "\\|"))))
  12786. (setq tags-in-group
  12787. (concat dir
  12788. "{\\<"
  12789. (regexp-opt tags-in-group)
  12790. "\\>"
  12791. regexp-in-group
  12792. "}"))
  12793. (when (stringp tags-in-group)
  12794. (org-add-props tags-in-group '(grouptag t)))
  12795. (setq return-match
  12796. (replace-match tags-in-group t t return-match)))
  12797. (setq tags-in-group
  12798. (append regexp-in-group-escaped tags-in-group))))
  12799. (setq taggroups-keys (delete tag taggroups-keys))))
  12800. ;; Add the regular expressions back into the match-expression again.
  12801. (while regexps-in-match
  12802. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12803. (pop regexps-in-match)
  12804. return-match t t))
  12805. (cl-decf count))
  12806. (if single-as-list
  12807. (if tags-in-group tags-in-group (list return-match))
  12808. return-match))
  12809. (if single-as-list
  12810. (list (if downcased (downcase match) match))
  12811. match)))
  12812. (defun org-op-to-function (op &optional stringp)
  12813. "Turn an operator into the appropriate function."
  12814. (setq op
  12815. (cond
  12816. ((equal op "<" ) '(< org-string< org-time<))
  12817. ((equal op ">" ) '(> org-string> org-time>))
  12818. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12819. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12820. ((member op '("=" "==")) '(= string= org-time=))
  12821. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12822. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12823. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12824. (defvar org-tags-overlay (make-overlay 1 1))
  12825. (delete-overlay org-tags-overlay)
  12826. (defun org-get-local-tags-at (&optional pos)
  12827. "Get a list of tags defined in the current headline."
  12828. (org-get-tags pos 'local))
  12829. (defun org-get-local-tags ()
  12830. "Get a list of tags defined in the current headline."
  12831. (org-get-tags nil 'local))
  12832. (defun org-add-prop-inherited (s)
  12833. (add-text-properties 0 (length s) '(inherited t) s)
  12834. s)
  12835. (defun org-toggle-tag (tag &optional onoff)
  12836. "Toggle the tag TAG for the current line.
  12837. If ONOFF is `on' or `off', don't toggle but set to this state."
  12838. (save-excursion
  12839. (org-back-to-heading t)
  12840. (let ((current
  12841. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  12842. (line-end-position) t)
  12843. (let ((tags (match-string 1)))
  12844. ;; Clear current tags.
  12845. (replace-match "")
  12846. ;; Reverse the tags list so any new tag is appended to
  12847. ;; the current list of tags.
  12848. (nreverse (org-split-string tags ":")))))
  12849. res)
  12850. (pcase onoff
  12851. (`off (setq current (delete tag current)))
  12852. ((or `on (guard (not (member tag current))))
  12853. (setq res t)
  12854. (cl-pushnew tag current :test #'equal))
  12855. (_ (setq current (delete tag current))))
  12856. (end-of-line)
  12857. (if current
  12858. (progn
  12859. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  12860. (org-set-tags nil t))
  12861. (delete-horizontal-space))
  12862. (run-hooks 'org-after-tags-change-hook)
  12863. res)))
  12864. (defun org--align-tags-here (to-col)
  12865. "Align tags on the current headline to TO-COL.
  12866. Assume point is on a headline."
  12867. (let ((pos (point)))
  12868. (beginning-of-line)
  12869. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  12870. (>= pos (match-beginning 2)))
  12871. ;; No tags or point within tags: do not align.
  12872. (goto-char pos)
  12873. (goto-char (match-beginning 1))
  12874. (let ((shift (max (- (if (>= to-col 0) to-col
  12875. (- (abs to-col) (string-width (match-string 2))))
  12876. (current-column))
  12877. 1)))
  12878. (replace-match (make-string shift ?\s) nil nil nil 1)
  12879. ;; Preserve initial position, if possible. In any case, stop
  12880. ;; before tags.
  12881. (when (< pos (point)) (goto-char pos))))))
  12882. (defun org-set-tags-command (&optional arg just-align)
  12883. "Call the set-tags command for the current entry."
  12884. (interactive "P")
  12885. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  12886. (org-set-tags arg just-align)
  12887. (save-excursion
  12888. (unless (and (org-region-active-p)
  12889. org-loop-over-headlines-in-active-region)
  12890. (org-back-to-heading t))
  12891. (org-set-tags arg just-align))))
  12892. (defun org-set-tags-to (data)
  12893. "Set the tags of the current entry to DATA, replacing current tags.
  12894. DATA may be a tags string like \":aa:bb:cc:\", or a list of tags.
  12895. If DATA is nil or the empty string, all tags are removed."
  12896. (interactive "sTags: ")
  12897. (let ((data
  12898. (pcase (if (stringp data) (org-trim data) data)
  12899. ((or `nil "") nil)
  12900. ((pred listp) (format ":%s:" (mapconcat #'identity data ":")))
  12901. ((pred stringp)
  12902. (format ":%s:"
  12903. (mapconcat #'identity (org-split-string data ":+") ":")))
  12904. (_ (error "Invalid tag specification: %S" data)))))
  12905. (org-with-wide-buffer
  12906. (org-back-to-heading t)
  12907. (let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  12908. (when (or (match-end 5) data)
  12909. (goto-char (or (match-beginning 5) (line-end-position)))
  12910. (skip-chars-backward " \t")
  12911. (delete-region (point) (line-end-position))
  12912. (when data
  12913. (insert " " data)
  12914. (org-set-tags nil 'align))))))
  12915. (defun org-align-all-tags ()
  12916. "Align the tags in all headings."
  12917. (interactive)
  12918. (save-excursion
  12919. (or (ignore-errors (org-back-to-heading t))
  12920. (outline-next-heading))
  12921. (if (org-at-heading-p)
  12922. (org-set-tags t)
  12923. (message "No headings"))))
  12924. (defvar org-indent-indentation-per-level)
  12925. (defun org-set-tags (&optional arg just-align)
  12926. "Set the tags for the current headline.
  12927. With prefix ARG, realign all tags in headings in the current buffer.
  12928. When JUST-ALIGN is non-nil, only align tags."
  12929. (interactive "P")
  12930. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12931. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12932. 'region-start-level
  12933. 'region))
  12934. org-loop-over-headlines-in-active-region)
  12935. (org-map-entries
  12936. ;; We don't use ARG and JUST-ALIGN here because these args
  12937. ;; are not useful when looping over headlines.
  12938. #'org-set-tags
  12939. org-loop-over-headlines-in-active-region
  12940. cl
  12941. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  12942. (let ((org-setting-tags t))
  12943. (if arg
  12944. (save-excursion
  12945. (goto-char (point-min))
  12946. (while (re-search-forward org-outline-regexp-bol nil t)
  12947. (org-set-tags nil t)
  12948. (end-of-line))
  12949. (message "All tags realigned to column %d" org-tags-column))
  12950. (let* ((current (org-get-tags-string))
  12951. (tags
  12952. (if just-align current
  12953. ;; Get a new set of tags from the user.
  12954. (save-excursion
  12955. (let* ((table
  12956. (setq
  12957. org-last-tags-completion-table
  12958. (org-tag-add-to-alist
  12959. (and
  12960. org-complete-tags-always-offer-all-agenda-tags
  12961. (org-global-tags-completion-table
  12962. (org-agenda-files)))
  12963. (or org-current-tag-alist
  12964. (org-get-buffer-tags)))))
  12965. (current-tags (org-split-string current ":"))
  12966. (inherited-tags
  12967. (nreverse (nthcdr (length current-tags)
  12968. (nreverse (org-get-tags))))))
  12969. (replace-regexp-in-string
  12970. "\\([-+&]+\\|,\\)"
  12971. ":"
  12972. (if (or (eq t org-use-fast-tag-selection)
  12973. (and org-use-fast-tag-selection
  12974. (delq nil (mapcar #'cdr table))))
  12975. (org-fast-tag-selection
  12976. current-tags inherited-tags table
  12977. (and org-fast-tag-selection-include-todo
  12978. org-todo-key-alist))
  12979. (let ((org-add-colon-after-tag-completion
  12980. (< 1 (length table))))
  12981. (org-trim
  12982. (completing-read
  12983. "Tags: "
  12984. #'org-tags-completion-function
  12985. nil nil current 'org-tags-history))))))))))
  12986. (when org-tags-sort-function
  12987. (setq tags
  12988. (mapconcat
  12989. #'identity
  12990. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  12991. org-tags-sort-function)
  12992. ":")))
  12993. (if (or (string= ":" tags)
  12994. (string= "::" tags))
  12995. (setq tags ""))
  12996. (if (not (org-string-nw-p tags)) (setq tags "")
  12997. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  12998. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  12999. ;; Insert new tags at the correct column.
  13000. (unless (equal current tags)
  13001. (save-excursion
  13002. (beginning-of-line)
  13003. (let ((case-fold-search nil))
  13004. (looking-at org-complex-heading-regexp))
  13005. ;; Remove current tags, if any.
  13006. (when (match-end 5) (replace-match "" nil nil nil 5))
  13007. ;; Insert new tags, if any. Otherwise, remove trailing
  13008. ;; white spaces.
  13009. (end-of-line)
  13010. (if (not (equal tags ""))
  13011. ;; When text is being inserted on an invisible
  13012. ;; region boundary, it can be inadvertently sucked
  13013. ;; into invisibility.
  13014. (org-flag-region (point) (progn (insert " " tags) (point))
  13015. nil
  13016. 'outline)
  13017. (skip-chars-backward " \t")
  13018. (delete-region (point) (line-end-position)))))
  13019. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13020. ;; is on.
  13021. (unless (equal tags "")
  13022. (let* ((level (save-excursion
  13023. (beginning-of-line)
  13024. (skip-chars-forward "\\*")))
  13025. (offset (if (bound-and-true-p org-indent-mode)
  13026. (* (1- org-indent-indentation-per-level)
  13027. (1- level))
  13028. 0))
  13029. (tags-column
  13030. (+ org-tags-column
  13031. (if (> org-tags-column 0) (- offset) offset))))
  13032. (org--align-tags-here tags-column))))
  13033. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13034. (defun org-change-tag-in-region (beg end tag off)
  13035. "Add or remove TAG for each entry in the region.
  13036. This works in the agenda, and also in an Org buffer."
  13037. (interactive
  13038. (list (region-beginning) (region-end)
  13039. (let ((org-last-tags-completion-table
  13040. (if (derived-mode-p 'org-mode)
  13041. (org-tag-add-to-alist
  13042. (org-get-buffer-tags)
  13043. (org-global-tags-completion-table))
  13044. (org-global-tags-completion-table))))
  13045. (completing-read
  13046. "Tag: " 'org-tags-completion-function nil nil nil
  13047. 'org-tags-history))
  13048. (progn
  13049. (message "[s]et or [r]emove? ")
  13050. (equal (read-char-exclusive) ?r))))
  13051. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13052. (let ((agendap (equal major-mode 'org-agenda-mode))
  13053. l1 l2 m buf pos newhead (cnt 0))
  13054. (goto-char end)
  13055. (setq l2 (1- (org-current-line)))
  13056. (goto-char beg)
  13057. (setq l1 (org-current-line))
  13058. (cl-loop for l from l1 to l2 do
  13059. (org-goto-line l)
  13060. (setq m (get-text-property (point) 'org-hd-marker))
  13061. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13062. (and agendap m))
  13063. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13064. pos (if agendap m (point)))
  13065. (with-current-buffer buf
  13066. (save-excursion
  13067. (save-restriction
  13068. (goto-char pos)
  13069. (setq cnt (1+ cnt))
  13070. (org-toggle-tag tag (if off 'off 'on))
  13071. (setq newhead (org-get-heading)))))
  13072. (and agendap (org-agenda-change-all-lines newhead m))))
  13073. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13074. (defun org-tags-completion-function (string _predicate &optional flag)
  13075. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13076. (confirm (lambda (x) (stringp (car x)))))
  13077. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13078. (setq s1 (match-string 1 string)
  13079. s2 (match-string 2 string))
  13080. (setq s1 "" s2 string))
  13081. (cond
  13082. ((eq flag nil)
  13083. ;; try completion
  13084. (setq rtn (try-completion s2 ctable confirm))
  13085. (when (stringp rtn)
  13086. (setq rtn
  13087. (concat s1 s2 (substring rtn (length s2))
  13088. (if (and org-add-colon-after-tag-completion
  13089. (assoc rtn ctable))
  13090. ":" ""))))
  13091. rtn)
  13092. ((eq flag t)
  13093. ;; all-completions
  13094. (all-completions s2 ctable confirm))
  13095. ((eq flag 'lambda)
  13096. ;; exact match?
  13097. (assoc s2 ctable)))))
  13098. (defun org-fast-tag-insert (kwd tags face &optional end)
  13099. "Insert KDW, and the TAGS, the latter with face FACE.
  13100. Also insert END."
  13101. (insert (format "%-12s" (concat kwd ":"))
  13102. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13103. (or end "")))
  13104. (defun org-fast-tag-show-exit (flag)
  13105. (save-excursion
  13106. (org-goto-line 3)
  13107. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13108. (replace-match ""))
  13109. (when flag
  13110. (end-of-line 1)
  13111. (org-move-to-column (- (window-width) 19) t)
  13112. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13113. (defun org-set-current-tags-overlay (current prefix)
  13114. "Add an overlay to CURRENT tag with PREFIX."
  13115. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13116. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13117. (org-overlay-display org-tags-overlay (concat prefix s))))
  13118. (defvar org-last-tag-selection-key nil)
  13119. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13120. "Fast tag selection with single keys.
  13121. CURRENT is the current list of tags in the headline, INHERITED is the
  13122. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13123. possibly with grouping information. TODO-TABLE is a similar table with
  13124. TODO keywords, should these have keys assigned to them.
  13125. If the keys are nil, a-z are automatically assigned.
  13126. Returns the new tags string, or nil to not change the current settings."
  13127. (let* ((fulltable (append table todo-table))
  13128. (maxlen (apply 'max (mapcar
  13129. (lambda (x)
  13130. (if (stringp (car x)) (string-width (car x)) 0))
  13131. fulltable)))
  13132. (buf (current-buffer))
  13133. (expert (eq org-fast-tag-selection-single-key 'expert))
  13134. (buffer-tags nil)
  13135. (fwidth (+ maxlen 3 1 3))
  13136. (ncol (/ (- (window-width) 4) fwidth))
  13137. (i-face 'org-done)
  13138. (c-face 'org-todo)
  13139. tg cnt e c char c1 c2 ntable tbl rtn
  13140. ov-start ov-end ov-prefix
  13141. (exit-after-next org-fast-tag-selection-single-key)
  13142. (done-keywords org-done-keywords)
  13143. groups ingroup intaggroup)
  13144. (save-excursion
  13145. (beginning-of-line 1)
  13146. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13147. (setq ov-start (match-beginning 1)
  13148. ov-end (match-end 1)
  13149. ov-prefix "")
  13150. (setq ov-start (1- (point-at-eol))
  13151. ov-end (1+ ov-start))
  13152. (skip-chars-forward "^\n\r")
  13153. (setq ov-prefix
  13154. (concat
  13155. (buffer-substring (1- (point)) (point))
  13156. (if (> (current-column) org-tags-column)
  13157. " "
  13158. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13159. (move-overlay org-tags-overlay ov-start ov-end)
  13160. (save-window-excursion
  13161. (if expert
  13162. (set-buffer (get-buffer-create " *Org tags*"))
  13163. (delete-other-windows)
  13164. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13165. (org-switch-to-buffer-other-window " *Org tags*"))
  13166. (erase-buffer)
  13167. (setq-local org-done-keywords done-keywords)
  13168. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13169. (org-fast-tag-insert "Current" current c-face "\n\n")
  13170. (org-fast-tag-show-exit exit-after-next)
  13171. (org-set-current-tags-overlay current ov-prefix)
  13172. (setq tbl fulltable char ?a cnt 0)
  13173. (while (setq e (pop tbl))
  13174. (cond
  13175. ((eq (car e) :startgroup)
  13176. (push '() groups) (setq ingroup t)
  13177. (unless (zerop cnt)
  13178. (setq cnt 0)
  13179. (insert "\n"))
  13180. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13181. ((eq (car e) :endgroup)
  13182. (setq ingroup nil cnt 0)
  13183. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13184. ((eq (car e) :startgrouptag)
  13185. (setq intaggroup t)
  13186. (unless (zerop cnt)
  13187. (setq cnt 0)
  13188. (insert "\n"))
  13189. (insert "[ "))
  13190. ((eq (car e) :endgrouptag)
  13191. (setq intaggroup nil cnt 0)
  13192. (insert "]\n"))
  13193. ((equal e '(:newline))
  13194. (unless (zerop cnt)
  13195. (setq cnt 0)
  13196. (insert "\n")
  13197. (setq e (car tbl))
  13198. (while (equal (car tbl) '(:newline))
  13199. (insert "\n")
  13200. (setq tbl (cdr tbl)))))
  13201. ((equal e '(:grouptags)) (insert " : "))
  13202. (t
  13203. (setq tg (copy-sequence (car e)) c2 nil)
  13204. (if (cdr e)
  13205. (setq c (cdr e))
  13206. ;; automatically assign a character.
  13207. (setq c1 (string-to-char
  13208. (downcase (substring
  13209. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13210. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13211. (while (or (rassoc char ntable) (rassoc char table))
  13212. (setq char (1+ char)))
  13213. (setq c2 c1))
  13214. (setq c (or c2 char)))
  13215. (when ingroup (push tg (car groups)))
  13216. (setq tg (org-add-props tg nil 'face
  13217. (cond
  13218. ((not (assoc tg table))
  13219. (org-get-todo-face tg))
  13220. ((member tg current) c-face)
  13221. ((member tg inherited) i-face))))
  13222. (when (equal (caar tbl) :grouptags)
  13223. (org-add-props tg nil 'face 'org-tag-group))
  13224. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13225. (insert "[" c "] " tg (make-string
  13226. (- fwidth 4 (length tg)) ?\ ))
  13227. (push (cons tg c) ntable)
  13228. (when (= (cl-incf cnt) ncol)
  13229. (insert "\n")
  13230. (when (or ingroup intaggroup) (insert " "))
  13231. (setq cnt 0)))))
  13232. (setq ntable (nreverse ntable))
  13233. (insert "\n")
  13234. (goto-char (point-min))
  13235. (unless expert (org-fit-window-to-buffer))
  13236. (setq rtn
  13237. (catch 'exit
  13238. (while t
  13239. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13240. (if (not groups) "no " "")
  13241. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13242. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13243. (setq org-last-tag-selection-key c)
  13244. (cond
  13245. ((= c ?\r) (throw 'exit t))
  13246. ((= c ?!)
  13247. (setq groups (not groups))
  13248. (goto-char (point-min))
  13249. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13250. ((= c ?\C-c)
  13251. (if (not expert)
  13252. (org-fast-tag-show-exit
  13253. (setq exit-after-next (not exit-after-next)))
  13254. (setq expert nil)
  13255. (delete-other-windows)
  13256. (set-window-buffer (split-window-vertically) " *Org tags*")
  13257. (org-switch-to-buffer-other-window " *Org tags*")
  13258. (org-fit-window-to-buffer)))
  13259. ((or (= c ?\C-g)
  13260. (and (= c ?q) (not (rassoc c ntable))))
  13261. (delete-overlay org-tags-overlay)
  13262. (setq quit-flag t))
  13263. ((= c ?\ )
  13264. (setq current nil)
  13265. (when exit-after-next (setq exit-after-next 'now)))
  13266. ((= c ?\t)
  13267. (condition-case nil
  13268. (setq tg (completing-read
  13269. "Tag: "
  13270. (or buffer-tags
  13271. (with-current-buffer buf
  13272. (setq buffer-tags
  13273. (org-get-buffer-tags))))))
  13274. (quit (setq tg "")))
  13275. (when (string-match "\\S-" tg)
  13276. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13277. (if (member tg current)
  13278. (setq current (delete tg current))
  13279. (push tg current)))
  13280. (when exit-after-next (setq exit-after-next 'now)))
  13281. ((setq e (rassoc c todo-table) tg (car e))
  13282. (with-current-buffer buf
  13283. (save-excursion (org-todo tg)))
  13284. (when exit-after-next (setq exit-after-next 'now)))
  13285. ((setq e (rassoc c ntable) tg (car e))
  13286. (if (member tg current)
  13287. (setq current (delete tg current))
  13288. (cl-loop for g in groups do
  13289. (when (member tg g)
  13290. (dolist (x g) (setq current (delete x current)))))
  13291. (push tg current))
  13292. (when exit-after-next (setq exit-after-next 'now))))
  13293. ;; Create a sorted list
  13294. (setq current
  13295. (sort current
  13296. (lambda (a b)
  13297. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13298. (when (eq exit-after-next 'now) (throw 'exit t))
  13299. (goto-char (point-min))
  13300. (beginning-of-line 2)
  13301. (delete-region (point) (point-at-eol))
  13302. (org-fast-tag-insert "Current" current c-face)
  13303. (org-set-current-tags-overlay current ov-prefix)
  13304. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13305. (setq tg (match-string 1))
  13306. (add-text-properties
  13307. (match-beginning 1) (match-end 1)
  13308. (list 'face
  13309. (cond
  13310. ((member tg current) c-face)
  13311. ((member tg inherited) i-face)
  13312. (t (get-text-property (match-beginning 1) 'face))))))
  13313. (goto-char (point-min)))))
  13314. (delete-overlay org-tags-overlay)
  13315. (if rtn
  13316. (mapconcat 'identity current ":")
  13317. nil))))
  13318. (defun org-get-tags-string ()
  13319. "Get the TAGS string in the current headline."
  13320. (unless (org-at-heading-p t)
  13321. (user-error "Not on a heading"))
  13322. (save-excursion
  13323. (beginning-of-line 1)
  13324. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13325. (match-string-no-properties 1)
  13326. "")))
  13327. (defun org--get-local-tags ()
  13328. "Return list of tags for the current headline.
  13329. Assume point is at the beginning of the headline."
  13330. (and (looking-at org-tag-line-re)
  13331. (split-string (match-string-no-properties 2) ":" t)))
  13332. (defun org-get-tags (&optional pos local)
  13333. "Get the list of tags specified in the current headline.
  13334. When argument POS is non-nil, retrieve tags for headline at POS.
  13335. Accoring to `org-use-tags-inheritance', tags may be inherited
  13336. from parent headlines, and from the whole document, through
  13337. `org-file-tags'. However, when optional argument LOCAL is
  13338. non-nil, only return tags really specified in the considered
  13339. headline.
  13340. Inherited tags have the `inherited' text property."
  13341. (if (and org-trust-scanner-tags
  13342. (or (not pos) (eq pos (point)))
  13343. (not local))
  13344. org-scanner-tags
  13345. (org-with-point-at (or pos (point))
  13346. (unless (org-before-first-heading-p)
  13347. (org-back-to-heading t)
  13348. (let ((tags (org--get-local-tags)))
  13349. (if (or local (not org-use-tag-inheritance)) tags
  13350. (while (org-up-heading-safe)
  13351. (setq tags (append (mapcar #'org-add-prop-inherited
  13352. (org--get-local-tags))
  13353. tags)))
  13354. (org-remove-uninherited-tags
  13355. (delete-dups (append org-file-tags tags)))))))))
  13356. (defun org-get-buffer-tags ()
  13357. "Get a table of all tags used in the buffer, for completion."
  13358. (org-with-point-at 1
  13359. (let (tags)
  13360. (while (re-search-forward org-tag-line-re nil t)
  13361. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13362. tags)))
  13363. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13364. ;;;; The mapping API
  13365. (defvar org-agenda-skip-comment-trees)
  13366. (defvar org-agenda-skip-function)
  13367. (defun org-map-entries (func &optional match scope &rest skip)
  13368. "Call FUNC at each headline selected by MATCH in SCOPE.
  13369. FUNC is a function or a lisp form. The function will be called without
  13370. arguments, with the cursor positioned at the beginning of the headline.
  13371. The return values of all calls to the function will be collected and
  13372. returned as a list.
  13373. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13374. does not need to preserve point. After evaluation, the cursor will be
  13375. moved to the end of the line (presumably of the headline of the
  13376. processed entry) and search continues from there. Under some
  13377. circumstances, this may not produce the wanted results. For example,
  13378. if you have removed (e.g. archived) the current (sub)tree it could
  13379. mean that the next entry will be skipped entirely. In such cases, you
  13380. can specify the position from where search should continue by making
  13381. FUNC set the variable `org-map-continue-from' to the desired buffer
  13382. position.
  13383. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13384. Only headlines that are matched by this query will be considered during
  13385. the iteration. When MATCH is nil or t, all headlines will be
  13386. visited by the iteration.
  13387. SCOPE determines the scope of this command. It can be any of:
  13388. nil The current buffer, respecting the restriction if any
  13389. tree The subtree started with the entry at point
  13390. region The entries within the active region, if any
  13391. region-start-level
  13392. The entries within the active region, but only those at
  13393. the same level than the first one.
  13394. file The current buffer, without restriction
  13395. file-with-archives
  13396. The current buffer, and any archives associated with it
  13397. agenda All agenda files
  13398. agenda-with-archives
  13399. All agenda files with any archive files associated with them
  13400. \(file1 file2 ...)
  13401. If this is a list, all files in the list will be scanned
  13402. The remaining args are treated as settings for the skipping facilities of
  13403. the scanner. The following items can be given here:
  13404. archive skip trees with the archive tag
  13405. comment skip trees with the COMMENT keyword
  13406. function or Emacs Lisp form:
  13407. will be used as value for `org-agenda-skip-function', so
  13408. whenever the function returns a position, FUNC will not be
  13409. called for that entry and search will continue from the
  13410. position returned
  13411. If your function needs to retrieve the tags including inherited tags
  13412. at the *current* entry, you can use the value of the variable
  13413. `org-scanner-tags' which will be much faster than getting the value
  13414. with `org-get-tags'. If your function gets properties with
  13415. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13416. to t around the call to `org-entry-properties' to get the same speedup.
  13417. Note that if your function moves around to retrieve tags and properties at
  13418. a *different* entry, you cannot use these techniques."
  13419. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13420. (not (org-region-active-p)))
  13421. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13422. (org-agenda-skip-archived-trees (memq 'archive skip))
  13423. (org-agenda-skip-comment-trees (memq 'comment skip))
  13424. (org-agenda-skip-function
  13425. (car (org-delete-all '(comment archive) skip)))
  13426. (org-tags-match-list-sublevels t)
  13427. (start-level (eq scope 'region-start-level))
  13428. matcher res
  13429. org-todo-keywords-for-agenda
  13430. org-done-keywords-for-agenda
  13431. org-todo-keyword-alist-for-agenda
  13432. org-tag-alist-for-agenda
  13433. org--matcher-tags-todo-only)
  13434. (cond
  13435. ((eq match t) (setq matcher t))
  13436. ((eq match nil) (setq matcher t))
  13437. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13438. (save-excursion
  13439. (save-restriction
  13440. (cond ((eq scope 'tree)
  13441. (org-back-to-heading t)
  13442. (org-narrow-to-subtree)
  13443. (setq scope nil))
  13444. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13445. (org-region-active-p))
  13446. ;; If needed, set start-level to a string like "2"
  13447. (when start-level
  13448. (save-excursion
  13449. (goto-char (region-beginning))
  13450. (unless (org-at-heading-p) (outline-next-heading))
  13451. (setq start-level (org-current-level))))
  13452. (narrow-to-region (region-beginning)
  13453. (save-excursion
  13454. (goto-char (region-end))
  13455. (unless (and (bolp) (org-at-heading-p))
  13456. (outline-next-heading))
  13457. (point)))
  13458. (setq scope nil)))
  13459. (if (not scope)
  13460. (progn
  13461. (org-agenda-prepare-buffers
  13462. (and buffer-file-name (list buffer-file-name)))
  13463. (setq res
  13464. (org-scan-tags
  13465. func matcher org--matcher-tags-todo-only start-level)))
  13466. ;; Get the right scope
  13467. (cond
  13468. ((and scope (listp scope) (symbolp (car scope)))
  13469. (setq scope (eval scope)))
  13470. ((eq scope 'agenda)
  13471. (setq scope (org-agenda-files t)))
  13472. ((eq scope 'agenda-with-archives)
  13473. (setq scope (org-agenda-files t))
  13474. (setq scope (org-add-archive-files scope)))
  13475. ((eq scope 'file)
  13476. (setq scope (and buffer-file-name (list buffer-file-name))))
  13477. ((eq scope 'file-with-archives)
  13478. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13479. (org-agenda-prepare-buffers scope)
  13480. (dolist (file scope)
  13481. (with-current-buffer (org-find-base-buffer-visiting file)
  13482. (org-with-wide-buffer
  13483. (goto-char (point-min))
  13484. (setq res
  13485. (append
  13486. res
  13487. (org-scan-tags
  13488. func matcher org--matcher-tags-todo-only)))))))))
  13489. res)))
  13490. ;;; Properties API
  13491. (defconst org-special-properties
  13492. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13493. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13494. "The special properties valid in Org mode.
  13495. These are properties that are not defined in the property drawer,
  13496. but in some other way.")
  13497. (defconst org-default-properties
  13498. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13499. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13500. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13501. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13502. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13503. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13504. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13505. "Some properties that are used by Org mode for various purposes.
  13506. Being in this list makes sure that they are offered for completion.")
  13507. (defun org--valid-property-p (property)
  13508. "Non nil when string PROPERTY is a valid property name."
  13509. (not
  13510. (or (equal property "")
  13511. (string-match-p "\\s-" property))))
  13512. (defun org--update-property-plist (key val props)
  13513. "Associate KEY to VAL in alist PROPS.
  13514. Modifications are made by side-effect. Return new alist."
  13515. (let* ((appending (string= (substring key -1) "+"))
  13516. (key (if appending (substring key 0 -1) key))
  13517. (old (assoc-string key props t)))
  13518. (if (not old) (cons (cons key val) props)
  13519. (setcdr old (if appending (concat (cdr old) " " val) val))
  13520. props)))
  13521. (defun org-get-property-block (&optional beg force)
  13522. "Return the (beg . end) range of the body of the property drawer.
  13523. BEG is the beginning of the current subtree, or of the part
  13524. before the first headline. If it is not given, it will be found.
  13525. If the drawer does not exist, create it if FORCE is non-nil, or
  13526. return nil."
  13527. (org-with-wide-buffer
  13528. (when beg (goto-char beg))
  13529. (unless (org-before-first-heading-p)
  13530. (let ((beg (cond (beg)
  13531. ((or (not (featurep 'org-inlinetask))
  13532. (org-inlinetask-in-task-p))
  13533. (org-back-to-heading t))
  13534. (t (org-with-limited-levels (org-back-to-heading t))))))
  13535. (forward-line)
  13536. (when (looking-at-p org-planning-line-re) (forward-line))
  13537. (cond ((looking-at org-property-drawer-re)
  13538. (forward-line)
  13539. (cons (point) (progn (goto-char (match-end 0))
  13540. (line-beginning-position))))
  13541. (force
  13542. (goto-char beg)
  13543. (org-insert-property-drawer)
  13544. (let ((pos (save-excursion (search-forward ":END:")
  13545. (line-beginning-position))))
  13546. (cons pos pos))))))))
  13547. (defun org-at-property-p ()
  13548. "Non-nil when point is inside a property drawer.
  13549. See `org-property-re' for match data, if applicable."
  13550. (save-excursion
  13551. (beginning-of-line)
  13552. (and (looking-at org-property-re)
  13553. (let ((property-drawer (save-match-data (org-get-property-block))))
  13554. (and property-drawer
  13555. (>= (point) (car property-drawer))
  13556. (< (point) (cdr property-drawer)))))))
  13557. (defun org-property-action ()
  13558. "Do an action on properties."
  13559. (interactive)
  13560. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13561. (let ((c (read-char-exclusive)))
  13562. (cl-case c
  13563. (?s (call-interactively #'org-set-property))
  13564. (?d (call-interactively #'org-delete-property))
  13565. (?D (call-interactively #'org-delete-property-globally))
  13566. (?c (call-interactively #'org-compute-property-at-point))
  13567. (otherwise (user-error "No such property action %c" c)))))
  13568. (defun org-inc-effort ()
  13569. "Increment the value of the effort property in the current entry."
  13570. (interactive)
  13571. (org-set-effort t))
  13572. (defvar org-clock-effort) ; Defined in org-clock.el.
  13573. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13574. (defun org-set-effort (&optional increment value)
  13575. "Set the effort property of the current entry.
  13576. If INCREMENT is non-nil, set the property to the next allowed
  13577. value. Otherwise, if optional argument VALUE is provided, use
  13578. it. Eventually, prompt for the new value if none of the previous
  13579. variables is set."
  13580. (interactive "P")
  13581. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13582. (current (org-entry-get nil org-effort-property))
  13583. (value
  13584. (cond
  13585. (increment
  13586. (unless allowed (user-error "Allowed effort values are not set"))
  13587. (or (cl-caadr (member (list current) allowed))
  13588. (user-error "Unknown value %S among allowed values" current)))
  13589. (value
  13590. (if (stringp value) value
  13591. (error "Invalid effort value: %S" value)))
  13592. (t
  13593. (let ((must-match
  13594. (and allowed
  13595. (not (get-text-property 0 'org-unrestricted
  13596. (caar allowed))))))
  13597. (completing-read "Effort: " allowed nil must-match))))))
  13598. (unless (equal current value)
  13599. (org-entry-put nil org-effort-property value))
  13600. (org-refresh-property '((effort . identity)
  13601. (effort-minutes . org-duration-to-minutes))
  13602. value)
  13603. (when (equal (org-get-heading t t t t)
  13604. (bound-and-true-p org-clock-current-task))
  13605. (setq org-clock-effort (org-get-at-bol 'effort))
  13606. (org-clock-update-mode-line))
  13607. (message "%s is now %s" org-effort-property value)))
  13608. (defun org-entry-properties (&optional pom which)
  13609. "Get all properties of the current entry.
  13610. When POM is a buffer position, get all properties from the entry
  13611. there instead.
  13612. This includes the TODO keyword, the tags, time strings for
  13613. deadline, scheduled, and clocking, and any additional properties
  13614. defined in the entry.
  13615. If WHICH is nil or `all', get all properties. If WHICH is
  13616. `special' or `standard', only get that subclass. If WHICH is
  13617. a string, only get that property.
  13618. Return value is an alist. Keys are properties, as upcased
  13619. strings."
  13620. (org-with-point-at pom
  13621. (when (and (derived-mode-p 'org-mode)
  13622. (ignore-errors (org-back-to-heading t)))
  13623. (catch 'exit
  13624. (let* ((beg (point))
  13625. (specific (and (stringp which) (upcase which)))
  13626. (which (cond ((not specific) which)
  13627. ((member specific org-special-properties) 'special)
  13628. (t 'standard)))
  13629. props)
  13630. ;; Get the special properties, like TODO and TAGS.
  13631. (when (memq which '(nil all special))
  13632. (when (or (not specific) (string= specific "CLOCKSUM"))
  13633. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13634. (when clocksum
  13635. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13636. props)))
  13637. (when specific (throw 'exit props)))
  13638. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13639. (let ((clocksumt (get-text-property (point)
  13640. :org-clock-minutes-today)))
  13641. (when clocksumt
  13642. (push (cons "CLOCKSUM_T"
  13643. (org-duration-from-minutes clocksumt))
  13644. props)))
  13645. (when specific (throw 'exit props)))
  13646. (when (or (not specific) (string= specific "ITEM"))
  13647. (let ((case-fold-search nil))
  13648. (when (looking-at org-complex-heading-regexp)
  13649. (push (cons "ITEM"
  13650. (let ((title (match-string-no-properties 4)))
  13651. (if (org-string-nw-p title)
  13652. (org-remove-tabs title)
  13653. "")))
  13654. props)))
  13655. (when specific (throw 'exit props)))
  13656. (when (or (not specific) (string= specific "TODO"))
  13657. (let ((case-fold-search nil))
  13658. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13659. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13660. (when specific (throw 'exit props)))
  13661. (when (or (not specific) (string= specific "PRIORITY"))
  13662. (push (cons "PRIORITY"
  13663. (if (looking-at org-priority-regexp)
  13664. (match-string-no-properties 2)
  13665. (char-to-string org-default-priority)))
  13666. props)
  13667. (when specific (throw 'exit props)))
  13668. (when (or (not specific) (string= specific "FILE"))
  13669. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13670. props)
  13671. (when specific (throw 'exit props)))
  13672. (when (or (not specific) (string= specific "TAGS"))
  13673. (let ((value (org-string-nw-p (org-get-tags-string))))
  13674. (when value (push (cons "TAGS" value) props)))
  13675. (when specific (throw 'exit props)))
  13676. (when (or (not specific) (string= specific "ALLTAGS"))
  13677. (let ((value (org-get-tags)))
  13678. (when value
  13679. (push (cons "ALLTAGS"
  13680. (format ":%s:" (mapconcat #'identity value ":")))
  13681. props)))
  13682. (when specific (throw 'exit props)))
  13683. (when (or (not specific) (string= specific "BLOCKED"))
  13684. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13685. (when specific (throw 'exit props)))
  13686. (when (or (not specific)
  13687. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13688. (forward-line)
  13689. (when (looking-at-p org-planning-line-re)
  13690. (end-of-line)
  13691. (let ((bol (line-beginning-position))
  13692. ;; Backward compatibility: time keywords used to
  13693. ;; be configurable (before 8.3). Make sure we
  13694. ;; get the correct keyword.
  13695. (key-assoc `(("CLOSED" . ,org-closed-string)
  13696. ("DEADLINE" . ,org-deadline-string)
  13697. ("SCHEDULED" . ,org-scheduled-string))))
  13698. (dolist (pair (if specific (list (assoc specific key-assoc))
  13699. key-assoc))
  13700. (save-excursion
  13701. (when (search-backward (cdr pair) bol t)
  13702. (goto-char (match-end 0))
  13703. (skip-chars-forward " \t")
  13704. (and (looking-at org-ts-regexp-both)
  13705. (push (cons (car pair)
  13706. (match-string-no-properties 0))
  13707. props)))))))
  13708. (when specific (throw 'exit props)))
  13709. (when (or (not specific)
  13710. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13711. (let ((find-ts
  13712. (lambda (end ts)
  13713. ;; Fix next time-stamp before END. TS is the
  13714. ;; list of time-stamps found so far.
  13715. (let ((ts ts)
  13716. (regexp (cond
  13717. ((string= specific "TIMESTAMP")
  13718. org-ts-regexp)
  13719. ((string= specific "TIMESTAMP_IA")
  13720. org-ts-regexp-inactive)
  13721. ((assoc "TIMESTAMP_IA" ts)
  13722. org-ts-regexp)
  13723. ((assoc "TIMESTAMP" ts)
  13724. org-ts-regexp-inactive)
  13725. (t org-ts-regexp-both))))
  13726. (catch 'next
  13727. (while (re-search-forward regexp end t)
  13728. (backward-char)
  13729. (let ((object (org-element-context)))
  13730. ;; Accept to match timestamps in node
  13731. ;; properties, too.
  13732. (when (memq (org-element-type object)
  13733. '(node-property timestamp))
  13734. (let ((type
  13735. (org-element-property :type object)))
  13736. (cond
  13737. ((and (memq type '(active active-range))
  13738. (not (equal specific "TIMESTAMP_IA")))
  13739. (unless (assoc "TIMESTAMP" ts)
  13740. (push (cons "TIMESTAMP"
  13741. (org-element-property
  13742. :raw-value object))
  13743. ts)
  13744. (when specific (throw 'exit ts))))
  13745. ((and (memq type '(inactive inactive-range))
  13746. (not (string= specific "TIMESTAMP")))
  13747. (unless (assoc "TIMESTAMP_IA" ts)
  13748. (push (cons "TIMESTAMP_IA"
  13749. (org-element-property
  13750. :raw-value object))
  13751. ts)
  13752. (when specific (throw 'exit ts))))))
  13753. ;; Both timestamp types are found,
  13754. ;; move to next part.
  13755. (when (= (length ts) 2) (throw 'next ts)))))
  13756. ts)))))
  13757. (goto-char beg)
  13758. ;; First look for timestamps within headline.
  13759. (let ((ts (funcall find-ts (line-end-position) nil)))
  13760. (if (= (length ts) 2) (setq props (nconc ts props))
  13761. ;; Then find timestamps in the section, skipping
  13762. ;; planning line.
  13763. (let ((end (save-excursion (outline-next-heading))))
  13764. (forward-line)
  13765. (when (looking-at-p org-planning-line-re) (forward-line))
  13766. (setq props (nconc (funcall find-ts end ts) props))))))))
  13767. ;; Get the standard properties, like :PROP:.
  13768. (when (memq which '(nil all standard))
  13769. ;; If we are looking after a specific property, delegate
  13770. ;; to `org-entry-get', which is faster. However, make an
  13771. ;; exception for "CATEGORY", since it can be also set
  13772. ;; through keywords (i.e. #+CATEGORY).
  13773. (if (and specific (not (equal specific "CATEGORY")))
  13774. (let ((value (org-entry-get beg specific nil t)))
  13775. (throw 'exit (and value (list (cons specific value)))))
  13776. (let ((range (org-get-property-block beg)))
  13777. (when range
  13778. (let ((end (cdr range)) seen-base)
  13779. (goto-char (car range))
  13780. ;; Unlike to `org--update-property-plist', we
  13781. ;; handle the case where base values is found
  13782. ;; after its extension. We also forbid standard
  13783. ;; properties to be named as special properties.
  13784. (while (re-search-forward org-property-re end t)
  13785. (let* ((key (upcase (match-string-no-properties 2)))
  13786. (extendp (string-match-p "\\+\\'" key))
  13787. (key-base (if extendp (substring key 0 -1) key))
  13788. (value (match-string-no-properties 3)))
  13789. (cond
  13790. ((member-ignore-case key-base org-special-properties))
  13791. (extendp
  13792. (setq props
  13793. (org--update-property-plist key value props)))
  13794. ((member key seen-base))
  13795. (t (push key seen-base)
  13796. (let ((p (assoc-string key props t)))
  13797. (if p (setcdr p (concat value " " (cdr p)))
  13798. (push (cons key value) props))))))))))))
  13799. (unless (assoc "CATEGORY" props)
  13800. (push (cons "CATEGORY" (org-get-category beg)) props)
  13801. (when (string= specific "CATEGORY") (throw 'exit props)))
  13802. ;; Return value.
  13803. props)))))
  13804. (defun org--property-local-values (property literal-nil)
  13805. "Return value for PROPERTY in current entry.
  13806. Value is a list whose car is the base value for PROPERTY and cdr
  13807. a list of accumulated values. Return nil if neither is found in
  13808. the entry. Also return nil when PROPERTY is set to \"nil\",
  13809. unless LITERAL-NIL is non-nil."
  13810. (let ((range (org-get-property-block)))
  13811. (when range
  13812. (goto-char (car range))
  13813. (let* ((case-fold-search t)
  13814. (end (cdr range))
  13815. (value
  13816. ;; Base value.
  13817. (save-excursion
  13818. (let ((v (and (re-search-forward
  13819. (org-re-property property nil t) end t)
  13820. (match-string-no-properties 3))))
  13821. (list (if literal-nil v (org-not-nil v)))))))
  13822. ;; Find additional values.
  13823. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13824. (while (re-search-forward property+ end t)
  13825. (push (match-string-no-properties 3) value)))
  13826. ;; Return final values.
  13827. (and (not (equal value '(nil))) (nreverse value))))))
  13828. (defun org--property-global-value (property literal-nil)
  13829. "Return value for PROPERTY in current buffer.
  13830. Return value is a string. Return nil if property is not set
  13831. globally. Also return nil when PROPERTY is set to \"nil\",
  13832. unless LITERAL-NIL is non-nil."
  13833. (let ((global
  13834. (cdr (or (assoc-string property org-file-properties t)
  13835. (assoc-string property org-global-properties t)
  13836. (assoc-string property org-global-properties-fixed t)))))
  13837. (if literal-nil global (org-not-nil global))))
  13838. (defun org-entry-get (pom property &optional inherit literal-nil)
  13839. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13840. If INHERIT is non-nil and the entry does not have the property,
  13841. then also check higher levels of the hierarchy. If INHERIT is
  13842. the symbol `selective', use inheritance only if the setting in
  13843. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13844. If the property is present but empty, the return value is the
  13845. empty string. If the property is not present at all, nil is
  13846. returned. In any other case, return the value as a string.
  13847. Search is case-insensitive.
  13848. If LITERAL-NIL is set, return the string value \"nil\" as
  13849. a string, do not interpret it as the list atom nil. This is used
  13850. for inheritance when a \"nil\" value can supersede a non-nil
  13851. value higher up the hierarchy."
  13852. (org-with-point-at pom
  13853. (cond
  13854. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13855. ;; We need a special property. Use `org-entry-properties' to
  13856. ;; retrieve it, but specify the wanted property.
  13857. (cdr (assoc-string property (org-entry-properties nil property))))
  13858. ((and inherit
  13859. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13860. (org-entry-get-with-inheritance property literal-nil))
  13861. (t
  13862. (let* ((local (org--property-local-values property literal-nil))
  13863. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13864. (if literal-nil value (org-not-nil value)))))))
  13865. (defun org-property-or-variable-value (var &optional inherit)
  13866. "Check if there is a property fixing the value of VAR.
  13867. If yes, return this value. If not, return the current value of the variable."
  13868. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13869. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13870. (read prop)
  13871. (symbol-value var))))
  13872. (defun org-entry-delete (pom property)
  13873. "Delete PROPERTY from entry at point-or-marker POM.
  13874. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13875. non-nil when a property was removed."
  13876. (org-with-point-at pom
  13877. (pcase (org-get-property-block)
  13878. (`(,begin . ,origin)
  13879. (let* ((end (copy-marker origin))
  13880. (re (org-re-property
  13881. (concat (regexp-quote property) "\\+?") t t)))
  13882. (goto-char begin)
  13883. (while (re-search-forward re end t)
  13884. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13885. ;; If drawer is empty, remove it altogether.
  13886. (when (= begin end)
  13887. (delete-region (line-beginning-position 0)
  13888. (line-beginning-position 2)))
  13889. ;; Return non-nil if some property was removed.
  13890. (prog1 (/= end origin) (set-marker end nil))))
  13891. (_ nil))))
  13892. ;; Multi-values properties are properties that contain multiple values
  13893. ;; These values are assumed to be single words, separated by whitespace.
  13894. (defun org-entry-add-to-multivalued-property (pom property value)
  13895. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13896. (let* ((old (org-entry-get pom property))
  13897. (values (and old (split-string old))))
  13898. (setq value (org-entry-protect-space value))
  13899. (unless (member value values)
  13900. (setq values (append values (list value)))
  13901. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13902. (defun org-entry-remove-from-multivalued-property (pom property value)
  13903. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13904. (let* ((old (org-entry-get pom property))
  13905. (values (and old (split-string old))))
  13906. (setq value (org-entry-protect-space value))
  13907. (when (member value values)
  13908. (setq values (delete value values))
  13909. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13910. (defun org-entry-member-in-multivalued-property (pom property value)
  13911. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13912. (let* ((old (org-entry-get pom property))
  13913. (values (and old (split-string old))))
  13914. (setq value (org-entry-protect-space value))
  13915. (member value values)))
  13916. (defun org-entry-get-multivalued-property (pom property)
  13917. "Return a list of values in a multivalued property."
  13918. (let* ((value (org-entry-get pom property))
  13919. (values (and value (split-string value))))
  13920. (mapcar #'org-entry-restore-space values)))
  13921. (defun org-entry-put-multivalued-property (pom property &rest values)
  13922. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13923. VALUES should be a list of strings. Spaces will be protected."
  13924. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13925. (let* ((value (org-entry-get pom property))
  13926. (values (and value (split-string value))))
  13927. (mapcar #'org-entry-restore-space values)))
  13928. (defun org-entry-protect-space (s)
  13929. "Protect spaces and newline in string S."
  13930. (while (string-match " " s)
  13931. (setq s (replace-match "%20" t t s)))
  13932. (while (string-match "\n" s)
  13933. (setq s (replace-match "%0A" t t s)))
  13934. s)
  13935. (defun org-entry-restore-space (s)
  13936. "Restore spaces and newline in string S."
  13937. (while (string-match "%20" s)
  13938. (setq s (replace-match " " t t s)))
  13939. (while (string-match "%0A" s)
  13940. (setq s (replace-match "\n" t t s)))
  13941. s)
  13942. (defvar org-entry-property-inherited-from (make-marker)
  13943. "Marker pointing to the entry from where a property was inherited.
  13944. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13945. location of the entry where the inheritance search matched. If there was
  13946. no match, the marker will point nowhere.
  13947. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13948. is set.")
  13949. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13950. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13951. The search will stop at the first ancestor which has the property defined.
  13952. If the value found is \"nil\", return nil to show that the property
  13953. should be considered as undefined (this is the meaning of nil here).
  13954. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13955. (move-marker org-entry-property-inherited-from nil)
  13956. (org-with-wide-buffer
  13957. (let (value)
  13958. (catch 'exit
  13959. (while t
  13960. (let ((v (org--property-local-values property literal-nil)))
  13961. (when v
  13962. (setq value
  13963. (concat (mapconcat #'identity (delq nil v) " ")
  13964. (and value " ")
  13965. value)))
  13966. (cond
  13967. ((car v)
  13968. (org-back-to-heading t)
  13969. (move-marker org-entry-property-inherited-from (point))
  13970. (throw 'exit nil))
  13971. ((org-up-heading-safe))
  13972. (t
  13973. (let ((global (org--property-global-value property literal-nil)))
  13974. (cond ((not global))
  13975. (value (setq value (concat global " " value)))
  13976. (t (setq value global))))
  13977. (throw 'exit nil))))))
  13978. (if literal-nil value (org-not-nil value)))))
  13979. (defvar org-property-changed-functions nil
  13980. "Hook called when the value of a property has changed.
  13981. Each hook function should accept two arguments, the name of the property
  13982. and the new value.")
  13983. (defun org-entry-put (pom property value)
  13984. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13985. If the value is nil, it is converted to the empty string. If it
  13986. is not a string, an error is raised. Also raise an error on
  13987. invalid property names.
  13988. PROPERTY can be any regular property (see
  13989. `org-special-properties'). It can also be \"TODO\",
  13990. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13991. For the last two properties, VALUE may have any of the special
  13992. values \"earlier\" and \"later\". The function then increases or
  13993. decreases scheduled or deadline date by one day."
  13994. (cond ((null value) (setq value ""))
  13995. ((not (stringp value)) (error "Properties values should be strings"))
  13996. ((not (org--valid-property-p property))
  13997. (user-error "Invalid property name: \"%s\"" property)))
  13998. (org-with-point-at pom
  13999. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14000. (org-back-to-heading t)
  14001. (org-with-limited-levels (org-back-to-heading t)))
  14002. (let ((beg (point)))
  14003. (cond
  14004. ((equal property "TODO")
  14005. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14006. ((not (member value org-todo-keywords-1))
  14007. (user-error "\"%s\" is not a valid TODO state" value)))
  14008. (org-todo value)
  14009. (org-set-tags nil 'align))
  14010. ((equal property "PRIORITY")
  14011. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14012. (org-set-tags nil 'align))
  14013. ((equal property "SCHEDULED")
  14014. (forward-line)
  14015. (if (and (looking-at-p org-planning-line-re)
  14016. (re-search-forward
  14017. org-scheduled-time-regexp (line-end-position) t))
  14018. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14019. ((string= value "later") (org-timestamp-change 1 'day))
  14020. ((string= value "") (org-schedule '(4)))
  14021. (t (org-schedule nil value)))
  14022. (if (member value '("earlier" "later" ""))
  14023. (call-interactively #'org-schedule)
  14024. (org-schedule nil value))))
  14025. ((equal property "DEADLINE")
  14026. (forward-line)
  14027. (if (and (looking-at-p org-planning-line-re)
  14028. (re-search-forward
  14029. org-deadline-time-regexp (line-end-position) t))
  14030. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14031. ((string= value "later") (org-timestamp-change 1 'day))
  14032. ((string= value "") (org-deadline '(4)))
  14033. (t (org-deadline nil value)))
  14034. (if (member value '("earlier" "later" ""))
  14035. (call-interactively #'org-deadline)
  14036. (org-deadline nil value))))
  14037. ((member property org-special-properties)
  14038. (error "The %s property cannot be set with `org-entry-put'" property))
  14039. (t
  14040. (let* ((range (org-get-property-block beg 'force))
  14041. (end (cdr range))
  14042. (case-fold-search t))
  14043. (goto-char (car range))
  14044. (if (re-search-forward (org-re-property property nil t) end t)
  14045. (progn (delete-region (match-beginning 0) (match-end 0))
  14046. (goto-char (match-beginning 0)))
  14047. (goto-char end)
  14048. (insert "\n")
  14049. (backward-char))
  14050. (insert ":" property ":")
  14051. (when value (insert " " value))
  14052. (org-indent-line)))))
  14053. (run-hook-with-args 'org-property-changed-functions property value)))
  14054. (defun org-buffer-property-keys (&optional specials defaults columns)
  14055. "Get all property keys in the current buffer.
  14056. When SPECIALS is non-nil, also list the special properties that
  14057. reflect things like tags and TODO state.
  14058. When DEFAULTS is non-nil, also include properties that has
  14059. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14060. DESCRIPTION, LOCATION, and LOGGING and others.
  14061. When COLUMNS in non-nil, also include property names given in
  14062. COLUMN formats in the current buffer."
  14063. (let ((case-fold-search t)
  14064. (props (append
  14065. (and specials org-special-properties)
  14066. (and defaults (cons org-effort-property org-default-properties))
  14067. nil)))
  14068. (org-with-wide-buffer
  14069. (goto-char (point-min))
  14070. (while (re-search-forward org-property-start-re nil t)
  14071. (catch :skip
  14072. (let ((range (org-get-property-block)))
  14073. (unless range (throw :skip nil))
  14074. (goto-char (car range))
  14075. (let ((begin (car range))
  14076. (end (cdr range)))
  14077. ;; Make sure that found property block is not located
  14078. ;; before current point, as it would generate an infloop.
  14079. ;; It can happen, for example, in the following
  14080. ;; situation:
  14081. ;;
  14082. ;; * Headline
  14083. ;; :PROPERTIES:
  14084. ;; ...
  14085. ;; :END:
  14086. ;; *************** Inlinetask
  14087. ;; #+BEGIN_EXAMPLE
  14088. ;; :PROPERTIES:
  14089. ;; #+END_EXAMPLE
  14090. ;;
  14091. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14092. (while (< (point) end)
  14093. (let ((p (progn (looking-at org-property-re)
  14094. (match-string-no-properties 2))))
  14095. ;; Only add true property name, not extension symbol.
  14096. (push (if (not (string-match-p "\\+\\'" p)) p
  14097. (substring p 0 -1))
  14098. props))
  14099. (forward-line))))
  14100. (outline-next-heading)))
  14101. (when columns
  14102. (goto-char (point-min))
  14103. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14104. (let ((element (org-element-at-point)))
  14105. (when (memq (org-element-type element) '(keyword node-property))
  14106. (let ((value (org-element-property :value element))
  14107. (start 0))
  14108. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14109. \\(?:{[^}]+}\\)?"
  14110. value start)
  14111. (setq start (match-end 0))
  14112. (let ((p (match-string-no-properties 1 value)))
  14113. (unless (member-ignore-case p org-special-properties)
  14114. (push p props))))))))))
  14115. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14116. (defun org-property-values (key)
  14117. "List all non-nil values of property KEY in current buffer."
  14118. (org-with-wide-buffer
  14119. (goto-char (point-min))
  14120. (let ((case-fold-search t)
  14121. (re (org-re-property key))
  14122. values)
  14123. (while (re-search-forward re nil t)
  14124. (push (org-entry-get (point) key) values))
  14125. (delete-dups values))))
  14126. (defun org-insert-property-drawer ()
  14127. "Insert a property drawer into the current entry."
  14128. (org-with-wide-buffer
  14129. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14130. (org-back-to-heading t)
  14131. (org-with-limited-levels (org-back-to-heading t)))
  14132. (forward-line)
  14133. (when (looking-at-p org-planning-line-re) (forward-line))
  14134. (unless (looking-at-p org-property-drawer-re)
  14135. ;; Make sure we start editing a line from current entry, not from
  14136. ;; next one. It prevents extending text properties or overlays
  14137. ;; belonging to the latter.
  14138. (when (bolp) (backward-char))
  14139. (let ((begin (1+ (point)))
  14140. (inhibit-read-only t))
  14141. (insert "\n:PROPERTIES:\n:END:")
  14142. (when (eobp) (insert "\n"))
  14143. (org-indent-region begin (point))))))
  14144. (defun org-insert-drawer (&optional arg drawer)
  14145. "Insert a drawer at point.
  14146. When optional argument ARG is non-nil, insert a property drawer.
  14147. Optional argument DRAWER, when non-nil, is a string representing
  14148. drawer's name. Otherwise, the user is prompted for a name.
  14149. If a region is active, insert the drawer around that region
  14150. instead.
  14151. Point is left between drawer's boundaries."
  14152. (interactive "P")
  14153. (let* ((drawer (if arg "PROPERTIES"
  14154. (or drawer (read-from-minibuffer "Drawer: ")))))
  14155. (cond
  14156. ;; With C-u, fall back on `org-insert-property-drawer'
  14157. (arg (org-insert-property-drawer))
  14158. ;; Check validity of suggested drawer's name.
  14159. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14160. (user-error "Invalid drawer name"))
  14161. ;; With an active region, insert a drawer at point.
  14162. ((not (org-region-active-p))
  14163. (progn
  14164. (unless (bolp) (insert "\n"))
  14165. (insert (format ":%s:\n\n:END:\n" drawer))
  14166. (forward-line -2)))
  14167. ;; Otherwise, insert the drawer at point
  14168. (t
  14169. (let ((rbeg (region-beginning))
  14170. (rend (copy-marker (region-end))))
  14171. (unwind-protect
  14172. (progn
  14173. (goto-char rbeg)
  14174. (beginning-of-line)
  14175. (when (save-excursion
  14176. (re-search-forward org-outline-regexp-bol rend t))
  14177. (user-error "Drawers cannot contain headlines"))
  14178. ;; Position point at the beginning of the first
  14179. ;; non-blank line in region. Insert drawer's opening
  14180. ;; there, then indent it.
  14181. (org-skip-whitespace)
  14182. (beginning-of-line)
  14183. (insert ":" drawer ":\n")
  14184. (forward-line -1)
  14185. (indent-for-tab-command)
  14186. ;; Move point to the beginning of the first blank line
  14187. ;; after the last non-blank line in region. Insert
  14188. ;; drawer's closing, then indent it.
  14189. (goto-char rend)
  14190. (skip-chars-backward " \r\t\n")
  14191. (insert "\n:END:")
  14192. (deactivate-mark t)
  14193. (indent-for-tab-command)
  14194. (unless (eolp) (insert "\n")))
  14195. ;; Clear marker, whatever the outcome of insertion is.
  14196. (set-marker rend nil)))))))
  14197. (defvar org-property-set-functions-alist nil
  14198. "Property set function alist.
  14199. Each entry should have the following format:
  14200. (PROPERTY . READ-FUNCTION)
  14201. The read function will be called with the same argument as
  14202. `org-completing-read'.")
  14203. (defun org-set-property-function (property)
  14204. "Get the function that should be used to set PROPERTY.
  14205. This is computed according to `org-property-set-functions-alist'."
  14206. (or (cdr (assoc property org-property-set-functions-alist))
  14207. 'org-completing-read))
  14208. (defun org-read-property-value (property)
  14209. "Read PROPERTY value from user."
  14210. (let* ((completion-ignore-case t)
  14211. (allowed (org-property-get-allowed-values nil property 'table))
  14212. (cur (org-entry-get nil property))
  14213. (prompt (concat property " value"
  14214. (if (and cur (string-match "\\S-" cur))
  14215. (concat " [" cur "]") "") ": "))
  14216. (set-function (org-set-property-function property))
  14217. (val (if allowed
  14218. (funcall set-function prompt allowed nil
  14219. (not (get-text-property 0 'org-unrestricted
  14220. (caar allowed))))
  14221. (funcall set-function prompt
  14222. (mapcar 'list (org-property-values property))
  14223. nil nil "" nil cur))))
  14224. (org-trim val)))
  14225. (defvar org-last-set-property nil)
  14226. (defvar org-last-set-property-value nil)
  14227. (defun org-read-property-name ()
  14228. "Read a property name."
  14229. (let ((completion-ignore-case t)
  14230. (default-prop (or (and (org-at-property-p)
  14231. (match-string-no-properties 2))
  14232. org-last-set-property)))
  14233. (org-completing-read
  14234. (concat "Property"
  14235. (if default-prop (concat " [" default-prop "]") "")
  14236. ": ")
  14237. (mapcar #'list (org-buffer-property-keys nil t t))
  14238. nil nil nil nil default-prop)))
  14239. (defun org-set-property-and-value (use-last)
  14240. "Allow to set [PROPERTY]: [value] direction from prompt.
  14241. When use-default, don't even ask, just use the last
  14242. \"[PROPERTY]: [value]\" string from the history."
  14243. (interactive "P")
  14244. (let* ((completion-ignore-case t)
  14245. (pv (or (and use-last org-last-set-property-value)
  14246. (org-completing-read
  14247. "Enter a \"[Property]: [value]\" pair: "
  14248. nil nil nil nil nil
  14249. org-last-set-property-value)))
  14250. prop val)
  14251. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14252. (setq prop (match-string 1 pv)
  14253. val (match-string 2 pv))
  14254. (org-set-property prop val))))
  14255. (defun org-set-property (property value)
  14256. "In the current entry, set PROPERTY to VALUE.
  14257. When called interactively, this will prompt for a property name, offering
  14258. completion on existing and default properties. And then it will prompt
  14259. for a value, offering completion either on allowed values (via an inherited
  14260. xxx_ALL property) or on existing values in other instances of this property
  14261. in the current file.
  14262. Throw an error when trying to set a property with an invalid name."
  14263. (interactive (list nil nil))
  14264. (let ((property (or property (org-read-property-name))))
  14265. ;; `org-entry-put' also makes the following check, but this one
  14266. ;; avoids polluting `org-last-set-property' and
  14267. ;; `org-last-set-property-value' needlessly.
  14268. (unless (org--valid-property-p property)
  14269. (user-error "Invalid property name: \"%s\"" property))
  14270. (let ((value (or value (org-read-property-value property)))
  14271. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14272. (setq org-last-set-property property)
  14273. (setq org-last-set-property-value (concat property ": " value))
  14274. ;; Possibly postprocess the inserted value:
  14275. (when fn (setq value (funcall fn value)))
  14276. (unless (equal (org-entry-get nil property) value)
  14277. (org-entry-put nil property value)))))
  14278. (defun org-find-property (property &optional value)
  14279. "Find first entry in buffer that sets PROPERTY.
  14280. When optional argument VALUE is non-nil, only consider an entry
  14281. if it contains PROPERTY set to this value. If PROPERTY should be
  14282. explicitly set to nil, use string \"nil\" for VALUE.
  14283. Return position where the entry begins, or nil if there is no
  14284. such entry. If narrowing is in effect, only search the visible
  14285. part of the buffer."
  14286. (save-excursion
  14287. (goto-char (point-min))
  14288. (let ((case-fold-search t)
  14289. (re (org-re-property property nil (not value) value)))
  14290. (catch 'exit
  14291. (while (re-search-forward re nil t)
  14292. (when (if value (org-at-property-p)
  14293. (org-entry-get (point) property nil t))
  14294. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14295. (defun org-delete-property (property)
  14296. "In the current entry, delete PROPERTY."
  14297. (interactive
  14298. (let* ((completion-ignore-case t)
  14299. (cat (org-entry-get (point) "CATEGORY"))
  14300. (props0 (org-entry-properties nil 'standard))
  14301. (props (if cat props0
  14302. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14303. (prop (if (< 1 (length props))
  14304. (completing-read "Property: " props nil t)
  14305. (caar props))))
  14306. (list prop)))
  14307. (if (not property)
  14308. (message "No property to delete in this entry")
  14309. (org-entry-delete nil property)
  14310. (message "Property \"%s\" deleted" property)))
  14311. (defun org-delete-property-globally (property)
  14312. "Remove PROPERTY globally, from all entries.
  14313. This function ignores narrowing, if any."
  14314. (interactive
  14315. (let* ((completion-ignore-case t)
  14316. (prop (completing-read
  14317. "Globally remove property: "
  14318. (mapcar #'list (org-buffer-property-keys)))))
  14319. (list prop)))
  14320. (org-with-wide-buffer
  14321. (goto-char (point-min))
  14322. (let ((count 0)
  14323. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14324. (while (re-search-forward re nil t)
  14325. (when (org-entry-delete (point) property) (cl-incf count)))
  14326. (message "Property \"%s\" removed from %d entries" property count))))
  14327. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14328. (defun org-compute-property-at-point ()
  14329. "Compute the property at point.
  14330. This looks for an enclosing column format, extracts the operator and
  14331. then applies it to the property in the column format's scope."
  14332. (interactive)
  14333. (unless (org-at-property-p)
  14334. (user-error "Not at a property"))
  14335. (let ((prop (match-string-no-properties 2)))
  14336. (org-columns-get-format-and-top-level)
  14337. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14338. (user-error "No operator defined for property %s" prop))
  14339. (org-columns-compute prop)))
  14340. (defvar org-property-allowed-value-functions nil
  14341. "Hook for functions supplying allowed values for a specific property.
  14342. The functions must take a single argument, the name of the property, and
  14343. return a flat list of allowed values. If \":ETC\" is one of
  14344. the values, this means that these values are intended as defaults for
  14345. completion, but that other values should be allowed too.
  14346. The functions must return nil if they are not responsible for this
  14347. property.")
  14348. (defun org-property-get-allowed-values (pom property &optional table)
  14349. "Get allowed values for the property PROPERTY.
  14350. When TABLE is non-nil, return an alist that can directly be used for
  14351. completion."
  14352. (let (vals)
  14353. (cond
  14354. ((equal property "TODO")
  14355. (setq vals (org-with-point-at pom
  14356. (append org-todo-keywords-1 '("")))))
  14357. ((equal property "PRIORITY")
  14358. (let ((n org-lowest-priority))
  14359. (while (>= n org-highest-priority)
  14360. (push (char-to-string n) vals)
  14361. (setq n (1- n)))))
  14362. ((equal property "CATEGORY"))
  14363. ((member property org-special-properties))
  14364. ((setq vals (run-hook-with-args-until-success
  14365. 'org-property-allowed-value-functions property)))
  14366. (t
  14367. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14368. (when (and vals (string-match "\\S-" vals))
  14369. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14370. (setq vals (mapcar (lambda (x)
  14371. (cond ((stringp x) x)
  14372. ((numberp x) (number-to-string x))
  14373. ((symbolp x) (symbol-name x))
  14374. (t "???")))
  14375. vals)))))
  14376. (when (member ":ETC" vals)
  14377. (setq vals (remove ":ETC" vals))
  14378. (org-add-props (car vals) '(org-unrestricted t)))
  14379. (if table (mapcar 'list vals) vals)))
  14380. (defun org-property-previous-allowed-value (&optional _previous)
  14381. "Switch to the next allowed value for this property."
  14382. (interactive)
  14383. (org-property-next-allowed-value t))
  14384. (defun org-property-next-allowed-value (&optional previous)
  14385. "Switch to the next allowed value for this property."
  14386. (interactive)
  14387. (unless (org-at-property-p)
  14388. (user-error "Not at a property"))
  14389. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14390. (key (match-string 2))
  14391. (value (match-string 3))
  14392. (allowed (or (org-property-get-allowed-values (point) key)
  14393. (and (member value '("[ ]" "[-]" "[X]"))
  14394. '("[ ]" "[X]"))))
  14395. (heading (save-match-data (nth 4 (org-heading-components))))
  14396. nval)
  14397. (unless allowed
  14398. (user-error "Allowed values for this property have not been defined"))
  14399. (when previous (setq allowed (reverse allowed)))
  14400. (when (member value allowed)
  14401. (setq nval (car (cdr (member value allowed)))))
  14402. (setq nval (or nval (car allowed)))
  14403. (when (equal nval value)
  14404. (user-error "Only one allowed value for this property"))
  14405. (org-at-property-p)
  14406. (replace-match (concat " :" key ": " nval) t t)
  14407. (org-indent-line)
  14408. (beginning-of-line 1)
  14409. (skip-chars-forward " \t")
  14410. (when (equal prop org-effort-property)
  14411. (org-refresh-property
  14412. '((effort . identity)
  14413. (effort-minutes . org-duration-to-minutes))
  14414. nval)
  14415. (when (string= org-clock-current-task heading)
  14416. (setq org-clock-effort nval)
  14417. (org-clock-update-mode-line)))
  14418. (run-hook-with-args 'org-property-changed-functions key nval)))
  14419. (defun org-find-olp (path &optional this-buffer)
  14420. "Return a marker pointing to the entry at outline path OLP.
  14421. If anything goes wrong, throw an error.
  14422. You can wrap this call to catch the error like this:
  14423. (condition-case msg
  14424. (org-mobile-locate-entry (match-string 4))
  14425. (error (nth 1 msg)))
  14426. The return value will then be either a string with the error message,
  14427. or a marker if everything is OK.
  14428. If THIS-BUFFER is set, the outline path does not contain a file,
  14429. only headings."
  14430. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14431. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14432. (level 1)
  14433. (lmin 1)
  14434. (lmax 1)
  14435. end found flevel)
  14436. (unless buffer (error "File not found :%s" file))
  14437. (with-current-buffer buffer
  14438. (unless (derived-mode-p 'org-mode)
  14439. (error "Buffer %s needs to be in Org mode" buffer))
  14440. (org-with-wide-buffer
  14441. (goto-char (point-min))
  14442. (dolist (heading path)
  14443. (let ((re (format org-complex-heading-regexp-format
  14444. (regexp-quote heading)))
  14445. (cnt 0))
  14446. (while (re-search-forward re end t)
  14447. (setq level (- (match-end 1) (match-beginning 1)))
  14448. (when (and (>= level lmin) (<= level lmax))
  14449. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14450. (when (= cnt 0)
  14451. (error "Heading not found on level %d: %s" lmax heading))
  14452. (when (> cnt 1)
  14453. (error "Heading not unique on level %d: %s" lmax heading))
  14454. (goto-char found)
  14455. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14456. (setq end (save-excursion (org-end-of-subtree t t)))))
  14457. (when (org-at-heading-p)
  14458. (point-marker))))))
  14459. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14460. "Find node HEADING in BUFFER.
  14461. Return a marker to the heading if it was found, or nil if not.
  14462. If POS-ONLY is set, return just the position instead of a marker.
  14463. The heading text must match exact, but it may have a TODO keyword,
  14464. a priority cookie and tags in the standard locations."
  14465. (with-current-buffer (or buffer (current-buffer))
  14466. (org-with-wide-buffer
  14467. (goto-char (point-min))
  14468. (let (case-fold-search)
  14469. (when (re-search-forward
  14470. (format org-complex-heading-regexp-format
  14471. (regexp-quote heading)) nil t)
  14472. (if pos-only
  14473. (match-beginning 0)
  14474. (move-marker (make-marker) (match-beginning 0))))))))
  14475. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14476. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14477. When the target headline is found, return a marker to this location."
  14478. (let ((files (directory-files (or dir default-directory)
  14479. t "\\`[^.#].*\\.org\\'"))
  14480. visiting m buffer)
  14481. (catch 'found
  14482. (dolist (file files)
  14483. (message "trying %s" file)
  14484. (setq visiting (org-find-base-buffer-visiting file))
  14485. (setq buffer (or visiting (find-file-noselect file)))
  14486. (setq m (org-find-exact-headline-in-buffer
  14487. heading buffer))
  14488. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14489. (and m (throw 'found m))))))
  14490. (defun org-find-entry-with-id (ident)
  14491. "Locate the entry that contains the ID property with exact value IDENT.
  14492. IDENT can be a string, a symbol or a number, this function will search for
  14493. the string representation of it.
  14494. Return the position where this entry starts, or nil if there is no such entry."
  14495. (interactive "sID: ")
  14496. (let ((id (cond
  14497. ((stringp ident) ident)
  14498. ((symbolp ident) (symbol-name ident))
  14499. ((numberp ident) (number-to-string ident))
  14500. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14501. (org-with-wide-buffer (org-find-property "ID" id))))
  14502. ;;;; Timestamps
  14503. (defvar org-last-changed-timestamp nil)
  14504. (defvar org-last-inserted-timestamp nil
  14505. "The last time stamp inserted with `org-insert-time-stamp'.")
  14506. (defun org-time-stamp (arg &optional inactive)
  14507. "Prompt for a date/time and insert a time stamp.
  14508. If the user specifies a time like HH:MM or if this command is
  14509. called with at least one prefix argument, the time stamp contains
  14510. the date and the time. Otherwise, only the date is included.
  14511. All parts of a date not specified by the user are filled in from
  14512. the timestamp at point, if any, or the current date/time
  14513. otherwise.
  14514. If there is already a timestamp at the cursor, it is replaced.
  14515. With two universal prefix arguments, insert an active timestamp
  14516. with the current time without prompting the user.
  14517. When called from lisp, the timestamp is inactive if INACTIVE is
  14518. non-nil."
  14519. (interactive "P")
  14520. (let* ((ts (cond
  14521. ((org-at-date-range-p t)
  14522. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14523. ((org-at-timestamp-p 'lax) (match-string 0))))
  14524. ;; Default time is either the timestamp at point or today.
  14525. ;; When entering a range, only the range start is considered.
  14526. (default-time (if (not ts) (current-time)
  14527. (apply #'encode-time (org-parse-time-string ts))))
  14528. (default-input (and ts (org-get-compact-tod ts)))
  14529. (repeater (and ts
  14530. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14531. (match-string 0 ts)))
  14532. org-time-was-given
  14533. org-end-time-was-given
  14534. (time
  14535. (and (if (equal arg '(16)) (current-time)
  14536. ;; Preserve `this-command' and `last-command'.
  14537. (let ((this-command this-command)
  14538. (last-command last-command))
  14539. (org-read-date
  14540. arg 'totime nil nil default-time default-input
  14541. inactive))))))
  14542. (cond
  14543. ((and ts
  14544. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14545. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14546. (insert "--")
  14547. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14548. (ts
  14549. ;; Make sure we're on a timestamp. When in the middle of a date
  14550. ;; range, move arbitrarily to range end.
  14551. (unless (org-at-timestamp-p 'lax)
  14552. (skip-chars-forward "-")
  14553. (org-at-timestamp-p 'lax))
  14554. (replace-match "")
  14555. (setq org-last-changed-timestamp
  14556. (org-insert-time-stamp
  14557. time (or org-time-was-given arg)
  14558. inactive nil nil (list org-end-time-was-given)))
  14559. (when repeater
  14560. (backward-char)
  14561. (insert " " repeater)
  14562. (setq org-last-changed-timestamp
  14563. (concat (substring org-last-inserted-timestamp 0 -1)
  14564. " " repeater ">")))
  14565. (message "Timestamp updated"))
  14566. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14567. (t (org-insert-time-stamp
  14568. time (or org-time-was-given arg) inactive nil nil
  14569. (list org-end-time-was-given))))))
  14570. ;; FIXME: can we use this for something else, like computing time differences?
  14571. (defun org-get-compact-tod (s)
  14572. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14573. (let* ((t1 (match-string 1 s))
  14574. (h1 (string-to-number (match-string 2 s)))
  14575. (m1 (string-to-number (match-string 3 s)))
  14576. (t2 (and (match-end 4) (match-string 5 s)))
  14577. (h2 (and t2 (string-to-number (match-string 6 s))))
  14578. (m2 (and t2 (string-to-number (match-string 7 s))))
  14579. dh dm)
  14580. (if (not t2)
  14581. t1
  14582. (setq dh (- h2 h1) dm (- m2 m1))
  14583. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14584. (concat t1 "+" (number-to-string dh)
  14585. (and (/= 0 dm) (format ":%02d" dm)))))))
  14586. (defun org-time-stamp-inactive (&optional arg)
  14587. "Insert an inactive time stamp.
  14588. An inactive time stamp is enclosed in square brackets instead of angle
  14589. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14590. does not link to the calendar and cannot be changed with the S-cursor keys.
  14591. So these are more for recording a certain time/date.
  14592. If the user specifies a time like HH:MM or if this command is called with
  14593. at least one prefix argument, the time stamp contains the date and the time.
  14594. Otherwise, only the date is included.
  14595. When called with two universal prefix arguments, insert an active time stamp
  14596. with the current time without prompting the user."
  14597. (interactive "P")
  14598. (org-time-stamp arg 'inactive))
  14599. (defvar org-date-ovl (make-overlay 1 1))
  14600. (overlay-put org-date-ovl 'face 'org-date-selected)
  14601. (delete-overlay org-date-ovl)
  14602. (defvar org-ans1) ; dynamically scoped parameter
  14603. (defvar org-ans2) ; dynamically scoped parameter
  14604. (defvar org-plain-time-of-day-regexp) ; defined below
  14605. (defvar org-overriding-default-time nil) ; dynamically scoped
  14606. (defvar org-read-date-overlay nil)
  14607. (defvar org-dcst nil) ; dynamically scoped
  14608. (defvar org-read-date-history nil)
  14609. (defvar org-read-date-final-answer nil)
  14610. (defvar org-read-date-analyze-futurep nil)
  14611. (defvar org-read-date-analyze-forced-year nil)
  14612. (defvar org-read-date-inactive)
  14613. (defvar org-read-date-minibuffer-local-map
  14614. (let* ((map (make-sparse-keymap)))
  14615. (set-keymap-parent map minibuffer-local-map)
  14616. (org-defkey map (kbd ".")
  14617. (lambda () (interactive)
  14618. ;; Are we at the beginning of the prompt?
  14619. (if (looking-back "^[^:]+: "
  14620. (let ((inhibit-field-text-motion t))
  14621. (line-beginning-position)))
  14622. (org-eval-in-calendar '(calendar-goto-today))
  14623. (insert "."))))
  14624. (org-defkey map (kbd "C-.")
  14625. (lambda () (interactive)
  14626. (org-eval-in-calendar '(calendar-goto-today))))
  14627. (org-defkey map (kbd "M-S-<left>")
  14628. (lambda () (interactive)
  14629. (org-eval-in-calendar '(calendar-backward-month 1))))
  14630. (org-defkey map (kbd "ESC S-<left>")
  14631. (lambda () (interactive)
  14632. (org-eval-in-calendar '(calendar-backward-month 1))))
  14633. (org-defkey map (kbd "M-S-<right>")
  14634. (lambda () (interactive)
  14635. (org-eval-in-calendar '(calendar-forward-month 1))))
  14636. (org-defkey map (kbd "ESC S-<right>")
  14637. (lambda () (interactive)
  14638. (org-eval-in-calendar '(calendar-forward-month 1))))
  14639. (org-defkey map (kbd "M-S-<up>")
  14640. (lambda () (interactive)
  14641. (org-eval-in-calendar '(calendar-backward-year 1))))
  14642. (org-defkey map (kbd "ESC S-<up>")
  14643. (lambda () (interactive)
  14644. (org-eval-in-calendar '(calendar-backward-year 1))))
  14645. (org-defkey map (kbd "M-S-<down>")
  14646. (lambda () (interactive)
  14647. (org-eval-in-calendar '(calendar-forward-year 1))))
  14648. (org-defkey map (kbd "ESC S-<down>")
  14649. (lambda () (interactive)
  14650. (org-eval-in-calendar '(calendar-forward-year 1))))
  14651. (org-defkey map (kbd "S-<up>")
  14652. (lambda () (interactive)
  14653. (org-eval-in-calendar '(calendar-backward-week 1))))
  14654. (org-defkey map (kbd "S-<down>")
  14655. (lambda () (interactive)
  14656. (org-eval-in-calendar '(calendar-forward-week 1))))
  14657. (org-defkey map (kbd "S-<left>")
  14658. (lambda () (interactive)
  14659. (org-eval-in-calendar '(calendar-backward-day 1))))
  14660. (org-defkey map (kbd "S-<right>")
  14661. (lambda () (interactive)
  14662. (org-eval-in-calendar '(calendar-forward-day 1))))
  14663. (org-defkey map (kbd "!")
  14664. (lambda () (interactive)
  14665. (org-eval-in-calendar '(diary-view-entries))
  14666. (message "")))
  14667. (org-defkey map (kbd ">")
  14668. (lambda () (interactive)
  14669. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14670. (org-defkey map (kbd "<")
  14671. (lambda () (interactive)
  14672. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14673. (org-defkey map (kbd "C-v")
  14674. (lambda () (interactive)
  14675. (org-eval-in-calendar
  14676. '(calendar-scroll-left-three-months 1))))
  14677. (org-defkey map (kbd "M-v")
  14678. (lambda () (interactive)
  14679. (org-eval-in-calendar
  14680. '(calendar-scroll-right-three-months 1))))
  14681. map)
  14682. "Keymap for minibuffer commands when using `org-read-date'.")
  14683. (defvar org-def)
  14684. (defvar org-defdecode)
  14685. (defvar org-with-time)
  14686. (defvar calendar-setup) ; Dynamically scoped.
  14687. (defun org-read-date (&optional with-time to-time from-string prompt
  14688. default-time default-input inactive)
  14689. "Read a date, possibly a time, and make things smooth for the user.
  14690. The prompt will suggest to enter an ISO date, but you can also enter anything
  14691. which will at least partially be understood by `parse-time-string'.
  14692. Unrecognized parts of the date will default to the current day, month, year,
  14693. hour and minute. If this command is called to replace a timestamp at point,
  14694. or to enter the second timestamp of a range, the default time is taken
  14695. from the existing stamp. Furthermore, the command prefers the future,
  14696. so if you are giving a date where the year is not given, and the day-month
  14697. combination is already past in the current year, it will assume you
  14698. mean next year. For details, see the manual. A few examples:
  14699. 3-2-5 --> 2003-02-05
  14700. feb 15 --> currentyear-02-15
  14701. 2/15 --> currentyear-02-15
  14702. sep 12 9 --> 2009-09-12
  14703. 12:45 --> today 12:45
  14704. 22 sept 0:34 --> currentyear-09-22 0:34
  14705. 12 --> currentyear-currentmonth-12
  14706. Fri --> nearest Friday after today
  14707. -Tue --> last Tuesday
  14708. etc.
  14709. Furthermore you can specify a relative date by giving, as the *first* thing
  14710. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14711. change in days weeks, months, years.
  14712. With a single plus or minus, the date is relative to today. With a double
  14713. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14714. +4d --> four days from today
  14715. +4 --> same as above
  14716. +2w --> two weeks from today
  14717. ++5 --> five days from default date
  14718. The function understands only English month and weekday abbreviations.
  14719. While prompting, a calendar is popped up - you can also select the
  14720. date with the mouse (button 1). The calendar shows a period of three
  14721. months. To scroll it to other months, use the keys `>' and `<'.
  14722. If you don't like the calendar, turn it off with
  14723. (setq org-read-date-popup-calendar nil)
  14724. With optional argument TO-TIME, the date will immediately be converted
  14725. to an internal time.
  14726. With an optional argument WITH-TIME, the prompt will suggest to
  14727. also insert a time. Note that when WITH-TIME is not set, you can
  14728. still enter a time, and this function will inform the calling routine
  14729. about this change. The calling routine may then choose to change the
  14730. format used to insert the time stamp into the buffer to include the time.
  14731. With optional argument FROM-STRING, read from this string instead from
  14732. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14733. the time/date that is used for everything that is not specified by the
  14734. user."
  14735. (require 'parse-time)
  14736. (let* ((org-with-time with-time)
  14737. (org-time-stamp-rounding-minutes
  14738. (if (equal org-with-time '(16))
  14739. '(0 0)
  14740. org-time-stamp-rounding-minutes))
  14741. (org-dcst org-display-custom-times)
  14742. (ct (org-current-time))
  14743. (org-def (or org-overriding-default-time default-time ct))
  14744. (org-defdecode (decode-time org-def))
  14745. (cur-frame (selected-frame))
  14746. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14747. (calendar-setup
  14748. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14749. (calendar-move-hook nil)
  14750. (calendar-view-diary-initially-flag nil)
  14751. (calendar-view-holidays-initially-flag nil)
  14752. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14753. ;; Rationalize `org-def' and `org-defdecode', if required.
  14754. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14755. (setf (nth 2 org-defdecode) -1)
  14756. (setf (nth 1 org-defdecode) 59)
  14757. (setq org-def (apply #'encode-time org-defdecode))
  14758. (setq org-defdecode (decode-time org-def)))
  14759. (let* ((timestr (format-time-string
  14760. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14761. org-def))
  14762. (prompt (concat (if prompt (concat prompt " ") "")
  14763. (format "Date+time [%s]: " timestr))))
  14764. (cond
  14765. (from-string (setq ans from-string))
  14766. (org-read-date-popup-calendar
  14767. (save-excursion
  14768. (save-window-excursion
  14769. (calendar)
  14770. (when (eq calendar-setup 'calendar-only)
  14771. (setq cal-frame
  14772. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14773. (select-frame cal-frame))
  14774. (org-eval-in-calendar '(setq cursor-type nil) t)
  14775. (unwind-protect
  14776. (progn
  14777. (calendar-forward-day (- (time-to-days org-def)
  14778. (calendar-absolute-from-gregorian
  14779. (calendar-current-date))))
  14780. (org-eval-in-calendar nil t)
  14781. (let* ((old-map (current-local-map))
  14782. (map (copy-keymap calendar-mode-map))
  14783. (minibuffer-local-map
  14784. (copy-keymap org-read-date-minibuffer-local-map)))
  14785. (org-defkey map (kbd "RET") 'org-calendar-select)
  14786. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14787. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14788. (unwind-protect
  14789. (progn
  14790. (use-local-map map)
  14791. (setq org-read-date-inactive inactive)
  14792. (add-hook 'post-command-hook 'org-read-date-display)
  14793. (setq org-ans0
  14794. (read-string prompt
  14795. default-input
  14796. 'org-read-date-history
  14797. nil))
  14798. ;; org-ans0: from prompt
  14799. ;; org-ans1: from mouse click
  14800. ;; org-ans2: from calendar motion
  14801. (setq ans
  14802. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14803. (remove-hook 'post-command-hook 'org-read-date-display)
  14804. (use-local-map old-map)
  14805. (when org-read-date-overlay
  14806. (delete-overlay org-read-date-overlay)
  14807. (setq org-read-date-overlay nil)))))
  14808. (bury-buffer "*Calendar*")
  14809. (when cal-frame
  14810. (delete-frame cal-frame)
  14811. (select-frame-set-input-focus cur-frame))))))
  14812. (t ; Naked prompt only
  14813. (unwind-protect
  14814. (setq ans (read-string prompt default-input
  14815. 'org-read-date-history timestr))
  14816. (when org-read-date-overlay
  14817. (delete-overlay org-read-date-overlay)
  14818. (setq org-read-date-overlay nil))))))
  14819. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14820. (when org-read-date-analyze-forced-year
  14821. (message "Year was forced into %s"
  14822. (if org-read-date-force-compatible-dates
  14823. "compatible range (1970-2037)"
  14824. "range representable on this machine"))
  14825. (ding))
  14826. ;; One round trip to get rid of 34th of August and stuff like that....
  14827. (setq final (decode-time (apply 'encode-time final)))
  14828. (setq org-read-date-final-answer ans)
  14829. (if to-time
  14830. (apply 'encode-time final)
  14831. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14832. (format "%04d-%02d-%02d %02d:%02d"
  14833. (nth 5 final) (nth 4 final) (nth 3 final)
  14834. (nth 2 final) (nth 1 final))
  14835. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14836. (defun org-read-date-display ()
  14837. "Display the current date prompt interpretation in the minibuffer."
  14838. (when org-read-date-display-live
  14839. (when org-read-date-overlay
  14840. (delete-overlay org-read-date-overlay))
  14841. (when (minibufferp (current-buffer))
  14842. (save-excursion
  14843. (end-of-line 1)
  14844. (while (not (equal (buffer-substring
  14845. (max (point-min) (- (point) 4)) (point))
  14846. " "))
  14847. (insert " ")))
  14848. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14849. " " (or org-ans1 org-ans2)))
  14850. (org-end-time-was-given nil)
  14851. (f (org-read-date-analyze ans org-def org-defdecode))
  14852. (fmts (if org-dcst
  14853. org-time-stamp-custom-formats
  14854. org-time-stamp-formats))
  14855. (fmt (if (or org-with-time
  14856. (and (boundp 'org-time-was-given) org-time-was-given))
  14857. (cdr fmts)
  14858. (car fmts)))
  14859. (txt (format-time-string fmt (apply 'encode-time f)))
  14860. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14861. (txt (concat "=> " txt)))
  14862. (when (and org-end-time-was-given
  14863. (string-match org-plain-time-of-day-regexp txt))
  14864. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14865. org-end-time-was-given
  14866. (substring txt (match-end 0)))))
  14867. (when org-read-date-analyze-futurep
  14868. (setq txt (concat txt " (=>F)")))
  14869. (setq org-read-date-overlay
  14870. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14871. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14872. (defun org-read-date-analyze (ans def defdecode)
  14873. "Analyze the combined answer of the date prompt."
  14874. ;; FIXME: cleanup and comment
  14875. ;; Pass `current-time' result to `decode-time' (instead of calling
  14876. ;; without arguments) so that only `current-time' has to be
  14877. ;; overridden in tests.
  14878. (let ((org-def def)
  14879. (org-defdecode defdecode)
  14880. (nowdecode (decode-time (current-time)))
  14881. delta deltan deltaw deltadef year month day
  14882. hour minute second wday pm h2 m2 tl wday1
  14883. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14884. (setq org-read-date-analyze-futurep nil
  14885. org-read-date-analyze-forced-year nil)
  14886. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14887. (setq ans "+0"))
  14888. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14889. (setq ans (replace-match "" t t ans)
  14890. deltan (car delta)
  14891. deltaw (nth 1 delta)
  14892. deltadef (nth 2 delta)))
  14893. ;; Check if there is an iso week date in there. If yes, store the
  14894. ;; info and postpone interpreting it until the rest of the parsing
  14895. ;; is done.
  14896. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14897. (setq iso-year (when (match-end 1)
  14898. (org-small-year-to-year
  14899. (string-to-number (match-string 1 ans))))
  14900. iso-weekday (when (match-end 3)
  14901. (string-to-number (match-string 3 ans)))
  14902. iso-week (string-to-number (match-string 2 ans)))
  14903. (setq ans (replace-match "" t t ans)))
  14904. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14905. (when (string-match
  14906. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14907. (setq year (if (match-end 2)
  14908. (string-to-number (match-string 2 ans))
  14909. (progn (setq kill-year t)
  14910. (string-to-number (format-time-string "%Y"))))
  14911. month (string-to-number (match-string 3 ans))
  14912. day (string-to-number (match-string 4 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 dotted european dates
  14917. (when (string-match
  14918. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14919. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14920. (setq kill-year t)
  14921. (string-to-number (format-time-string "%Y")))
  14922. day (string-to-number (match-string 1 ans))
  14923. month (string-to-number (match-string 2 ans))
  14924. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14925. t nil ans)))
  14926. ;; Help matching american dates, like 5/30 or 5/30/7
  14927. (when (string-match
  14928. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14929. (setq year (if (match-end 4)
  14930. (string-to-number (match-string 4 ans))
  14931. (progn (setq kill-year t)
  14932. (string-to-number (format-time-string "%Y"))))
  14933. month (string-to-number (match-string 1 ans))
  14934. day (string-to-number (match-string 2 ans)))
  14935. (setq year (org-small-year-to-year year))
  14936. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14937. t nil ans)))
  14938. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14939. ;; If there is a time with am/pm, and *no* time without it, we convert
  14940. ;; so that matching will be successful.
  14941. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14942. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14943. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14944. (setq hour (string-to-number (match-string 1 ans))
  14945. minute (if (match-end 3)
  14946. (string-to-number (match-string 3 ans))
  14947. 0)
  14948. pm (equal ?p
  14949. (string-to-char (downcase (match-string 4 ans)))))
  14950. (if (and (= hour 12) (not pm))
  14951. (setq hour 0)
  14952. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14953. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14954. t t ans))))
  14955. ;; Check if a time range is given as a duration
  14956. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14957. (setq hour (string-to-number (match-string 1 ans))
  14958. h2 (+ hour (string-to-number (match-string 3 ans)))
  14959. minute (string-to-number (match-string 2 ans))
  14960. m2 (+ minute (if (match-end 5) (string-to-number
  14961. (match-string 5 ans))0)))
  14962. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14963. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14964. t t ans)))
  14965. ;; Check if there is a time range
  14966. (when (boundp 'org-end-time-was-given)
  14967. (setq org-time-was-given nil)
  14968. (when (and (string-match org-plain-time-of-day-regexp ans)
  14969. (match-end 8))
  14970. (setq org-end-time-was-given (match-string 8 ans))
  14971. (setq ans (concat (substring ans 0 (match-beginning 7))
  14972. (substring ans (match-end 7))))))
  14973. (setq tl (parse-time-string ans)
  14974. day (or (nth 3 tl) (nth 3 org-defdecode))
  14975. month
  14976. (cond ((nth 4 tl))
  14977. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14978. ;; Day was specified. Make sure DAY+MONTH
  14979. ;; combination happens in the future.
  14980. ((nth 3 tl)
  14981. (setq futurep t)
  14982. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14983. (nth 4 nowdecode)))
  14984. (t (nth 4 org-defdecode)))
  14985. year
  14986. (cond ((and (not kill-year) (nth 5 tl)))
  14987. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14988. ;; Month was guessed in the future and is at least
  14989. ;; equal to NOWDECODE's. Fix year accordingly.
  14990. (futurep
  14991. (if (or (> month (nth 4 nowdecode))
  14992. (>= day (nth 3 nowdecode)))
  14993. (nth 5 nowdecode)
  14994. (1+ (nth 5 nowdecode))))
  14995. ;; Month was specified. Make sure MONTH+YEAR
  14996. ;; combination happens in the future.
  14997. ((nth 4 tl)
  14998. (setq futurep t)
  14999. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15000. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15001. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15002. (t (nth 5 nowdecode))))
  15003. (t (nth 5 org-defdecode)))
  15004. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15005. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15006. second (or (nth 0 tl) 0)
  15007. wday (nth 6 tl))
  15008. (when (and (eq org-read-date-prefer-future 'time)
  15009. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15010. (equal day (nth 3 nowdecode))
  15011. (equal month (nth 4 nowdecode))
  15012. (equal year (nth 5 nowdecode))
  15013. (nth 2 tl)
  15014. (or (< (nth 2 tl) (nth 2 nowdecode))
  15015. (and (= (nth 2 tl) (nth 2 nowdecode))
  15016. (nth 1 tl)
  15017. (< (nth 1 tl) (nth 1 nowdecode)))))
  15018. (setq day (1+ day)
  15019. futurep t))
  15020. ;; Special date definitions below
  15021. (cond
  15022. (iso-week
  15023. ;; There was an iso week
  15024. (require 'cal-iso)
  15025. (setq futurep nil)
  15026. (setq year (or iso-year year)
  15027. day (or iso-weekday wday 1)
  15028. wday nil ; to make sure that the trigger below does not match
  15029. iso-date (calendar-gregorian-from-absolute
  15030. (calendar-iso-to-absolute
  15031. (list iso-week day year))))
  15032. ; FIXME: Should we also push ISO weeks into the future?
  15033. ; (when (and org-read-date-prefer-future
  15034. ; (not iso-year)
  15035. ; (< (calendar-absolute-from-gregorian iso-date)
  15036. ; (time-to-days (current-time))))
  15037. ; (setq year (1+ year)
  15038. ; iso-date (calendar-gregorian-from-absolute
  15039. ; (calendar-iso-to-absolute
  15040. ; (list iso-week day year)))))
  15041. (setq month (car iso-date)
  15042. year (nth 2 iso-date)
  15043. day (nth 1 iso-date)))
  15044. (deltan
  15045. (setq futurep nil)
  15046. (unless deltadef
  15047. ;; Pass `current-time' result to `decode-time' (instead of
  15048. ;; calling without arguments) so that only `current-time' has
  15049. ;; to be overridden in tests.
  15050. (let ((now (decode-time (current-time))))
  15051. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15052. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15053. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15054. ((equal deltaw "m") (setq month (+ month deltan)))
  15055. ((equal deltaw "y") (setq year (+ year deltan)))))
  15056. ((and wday (not (nth 3 tl)))
  15057. ;; Weekday was given, but no day, so pick that day in the week
  15058. ;; on or after the derived date.
  15059. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15060. (unless (equal wday wday1)
  15061. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15062. (when (and (boundp 'org-time-was-given)
  15063. (nth 2 tl))
  15064. (setq org-time-was-given t))
  15065. (when (< year 100) (setq year (+ 2000 year)))
  15066. ;; Check of the date is representable
  15067. (if org-read-date-force-compatible-dates
  15068. (progn
  15069. (when (< year 1970)
  15070. (setq year 1970 org-read-date-analyze-forced-year t))
  15071. (when (> year 2037)
  15072. (setq year 2037 org-read-date-analyze-forced-year t)))
  15073. (condition-case nil
  15074. (ignore (encode-time second minute hour day month year))
  15075. (error
  15076. (setq year (nth 5 org-defdecode))
  15077. (setq org-read-date-analyze-forced-year t))))
  15078. (setq org-read-date-analyze-futurep futurep)
  15079. (list second minute hour day month year)))
  15080. (defvar parse-time-weekdays)
  15081. (defun org-read-date-get-relative (s today default)
  15082. "Check string S for special relative date string.
  15083. TODAY and DEFAULT are internal times, for today and for a default.
  15084. Return shift list (N what def-flag)
  15085. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15086. N is the number of WHATs to shift.
  15087. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15088. the DEFAULT date rather than TODAY."
  15089. (require 'parse-time)
  15090. (when (and
  15091. (string-match
  15092. (concat
  15093. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15094. "\\([0-9]+\\)?"
  15095. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15096. "\\([ \t]\\|$\\)") s)
  15097. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15098. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15099. (string-to-char (substring (match-string 1 s) -1))
  15100. ?+))
  15101. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15102. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15103. (what (if (match-end 3) (match-string 3 s) "d"))
  15104. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15105. (date (if rel default today))
  15106. (wday (nth 6 (decode-time date)))
  15107. delta)
  15108. (if wday1
  15109. (progn
  15110. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15111. (when (= delta 0) (setq delta 7))
  15112. (when (= dir ?-)
  15113. (setq delta (- delta 7))
  15114. (when (= delta 0) (setq delta -7)))
  15115. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15116. (list delta "d" rel))
  15117. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15118. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15119. "Turn a user-specified date into the internal representation.
  15120. The internal representation needed by the calendar is (month day year).
  15121. This is a wrapper to handle the brain-dead convention in calendar that
  15122. user function argument order change dependent on argument order."
  15123. (pcase calendar-date-style
  15124. (`american (list arg1 arg2 arg3))
  15125. (`european (list arg2 arg1 arg3))
  15126. (`iso (list arg2 arg3 arg1))))
  15127. (defun org-eval-in-calendar (form &optional keepdate)
  15128. "Eval FORM in the calendar window and return to current window.
  15129. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15130. (let ((sf (selected-frame))
  15131. (sw (selected-window)))
  15132. (select-window (get-buffer-window "*Calendar*" t))
  15133. (eval form)
  15134. (when (and (not keepdate) (calendar-cursor-to-date))
  15135. (let* ((date (calendar-cursor-to-date))
  15136. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15137. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15138. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15139. (select-window sw)
  15140. (select-frame-set-input-focus sf)))
  15141. (defun org-calendar-select ()
  15142. "Return to `org-read-date' with the date currently selected.
  15143. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15144. (interactive)
  15145. (when (calendar-cursor-to-date)
  15146. (let* ((date (calendar-cursor-to-date))
  15147. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15148. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15149. (when (active-minibuffer-window) (exit-minibuffer))))
  15150. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15151. "Insert a date stamp for the date given by the internal TIME.
  15152. See `format-time-string' for the format of TIME.
  15153. WITH-HM means use the stamp format that includes the time of the day.
  15154. INACTIVE means use square brackets instead of angular ones, so that the
  15155. stamp will not contribute to the agenda.
  15156. PRE and POST are optional strings to be inserted before and after the
  15157. stamp.
  15158. The command returns the inserted time stamp."
  15159. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15160. stamp)
  15161. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15162. (insert-before-markers (or pre ""))
  15163. (when (listp extra)
  15164. (setq extra (car extra))
  15165. (if (and (stringp extra)
  15166. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15167. (setq extra (format "-%02d:%02d"
  15168. (string-to-number (match-string 1 extra))
  15169. (string-to-number (match-string 2 extra))))
  15170. (setq extra nil)))
  15171. (when extra
  15172. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15173. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15174. (insert-before-markers (or post ""))
  15175. (setq org-last-inserted-timestamp stamp)))
  15176. (defun org-toggle-time-stamp-overlays ()
  15177. "Toggle the use of custom time stamp formats."
  15178. (interactive)
  15179. (setq org-display-custom-times (not org-display-custom-times))
  15180. (unless org-display-custom-times
  15181. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15182. (while (setq p (next-single-property-change p 'display))
  15183. (when (and (get-text-property p 'display)
  15184. (eq (get-text-property p 'face) 'org-date))
  15185. (remove-text-properties
  15186. p (setq p (next-single-property-change p 'display))
  15187. '(display t))))
  15188. (set-buffer-modified-p bmp)))
  15189. (org-restart-font-lock)
  15190. (setq org-table-may-need-update t)
  15191. (if org-display-custom-times
  15192. (message "Time stamps are overlaid with custom format")
  15193. (message "Time stamp overlays removed")))
  15194. (defun org-display-custom-time (beg end)
  15195. "Overlay modified time stamp format over timestamp between BEG and END."
  15196. (let* ((ts (buffer-substring beg end))
  15197. t1 with-hm tf time str (off 0))
  15198. (save-match-data
  15199. (setq t1 (org-parse-time-string ts t))
  15200. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15201. (setq off (- (match-end 0) (match-beginning 0)))))
  15202. (setq end (- end off))
  15203. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15204. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15205. time (org-fix-decoded-time t1)
  15206. str (org-add-props
  15207. (format-time-string
  15208. (substring tf 1 -1) (apply 'encode-time time))
  15209. nil 'mouse-face 'highlight))
  15210. (put-text-property beg end 'display str)))
  15211. (defun org-fix-decoded-time (time)
  15212. "Set 0 instead of nil for the first 6 elements of time.
  15213. Don't touch the rest."
  15214. (let ((n 0))
  15215. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15216. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15217. "Difference between TIMESTAMP-STRING and now in days.
  15218. If SECONDS is non-nil, return the difference in seconds."
  15219. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15220. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15221. (funcall fdiff (current-time)))))
  15222. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15223. "Is the time in TIMESTAMP-STRING close to the current date?"
  15224. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15225. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15226. (not (org-entry-is-done-p))))
  15227. (defun org-get-wdays (ts &optional delay zero-delay)
  15228. "Get the deadline lead time appropriate for timestring TS.
  15229. When DELAY is non-nil, get the delay time for scheduled items
  15230. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15231. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15232. don't try to find the delay cookie in the scheduled timestamp."
  15233. (let ((tv (if delay org-scheduled-delay-days
  15234. org-deadline-warning-days)))
  15235. (cond
  15236. ((or (and delay (< tv 0))
  15237. (and delay zero-delay (<= tv 0))
  15238. (and (not delay) (<= tv 0)))
  15239. ;; Enforce this value no matter what
  15240. (- tv))
  15241. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15242. ;; lead time is specified.
  15243. (floor (* (string-to-number (match-string 1 ts))
  15244. (cdr (assoc (match-string 2 ts)
  15245. '(("d" . 1) ("w" . 7)
  15246. ("m" . 30.4) ("y" . 365.25)
  15247. ("h" . 0.041667)))))))
  15248. ;; go for the default.
  15249. (t tv))))
  15250. (defun org-calendar-select-mouse (ev)
  15251. "Return to `org-read-date' with the date currently selected.
  15252. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15253. (interactive "e")
  15254. (mouse-set-point ev)
  15255. (when (calendar-cursor-to-date)
  15256. (let* ((date (calendar-cursor-to-date))
  15257. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15258. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15259. (when (active-minibuffer-window) (exit-minibuffer))))
  15260. (defun org-check-deadlines (ndays)
  15261. "Check if there are any deadlines due or past due.
  15262. A deadline is considered due if it happens within `org-deadline-warning-days'
  15263. days from today's date. If the deadline appears in an entry marked DONE,
  15264. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15265. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15266. are shown."
  15267. (interactive "P")
  15268. (let* ((org-warn-days
  15269. (cond
  15270. ((equal ndays '(4)) 100000)
  15271. (ndays (prefix-numeric-value ndays))
  15272. (t (abs org-deadline-warning-days))))
  15273. (case-fold-search nil)
  15274. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15275. (callback
  15276. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15277. (message "%d deadlines past-due or due within %d days"
  15278. (org-occur regexp nil callback)
  15279. org-warn-days)))
  15280. (defsubst org-re-timestamp (type)
  15281. "Return a regexp for timestamp TYPE.
  15282. Allowed values for TYPE are:
  15283. all: all timestamps
  15284. active: only active timestamps (<...>)
  15285. inactive: only inactive timestamps ([...])
  15286. scheduled: only scheduled timestamps
  15287. deadline: only deadline timestamps
  15288. closed: only closed time-stamps
  15289. When TYPE is nil, fall back on returning a regexp that matches
  15290. both scheduled and deadline timestamps."
  15291. (cl-case type
  15292. (all org-ts-regexp-both)
  15293. (active org-ts-regexp)
  15294. (inactive org-ts-regexp-inactive)
  15295. (scheduled org-scheduled-time-regexp)
  15296. (deadline org-deadline-time-regexp)
  15297. (closed org-closed-time-regexp)
  15298. (otherwise
  15299. (concat "\\<"
  15300. (regexp-opt (list org-deadline-string org-scheduled-string))
  15301. " *<\\([^>]+\\)>"))))
  15302. (defun org-check-before-date (d)
  15303. "Check if there are deadlines or scheduled entries before date D."
  15304. (interactive (list (org-read-date)))
  15305. (let* ((case-fold-search nil)
  15306. (regexp (org-re-timestamp org-ts-type))
  15307. (ts-type org-ts-type)
  15308. (callback
  15309. (lambda ()
  15310. (let ((match (match-string 1)))
  15311. (and (if (memq ts-type '(active inactive all))
  15312. (eq (org-element-type (save-excursion
  15313. (backward-char)
  15314. (org-element-context)))
  15315. 'timestamp)
  15316. (org-at-planning-p))
  15317. (time-less-p
  15318. (org-time-string-to-time match)
  15319. (org-time-string-to-time d)))))))
  15320. (message "%d entries before %s"
  15321. (org-occur regexp nil callback)
  15322. d)))
  15323. (defun org-check-after-date (d)
  15324. "Check if there are deadlines or scheduled entries after date D."
  15325. (interactive (list (org-read-date)))
  15326. (let* ((case-fold-search nil)
  15327. (regexp (org-re-timestamp org-ts-type))
  15328. (ts-type org-ts-type)
  15329. (callback
  15330. (lambda ()
  15331. (let ((match (match-string 1)))
  15332. (and (if (memq ts-type '(active inactive all))
  15333. (eq (org-element-type (save-excursion
  15334. (backward-char)
  15335. (org-element-context)))
  15336. 'timestamp)
  15337. (org-at-planning-p))
  15338. (not (time-less-p
  15339. (org-time-string-to-time match)
  15340. (org-time-string-to-time d))))))))
  15341. (message "%d entries after %s"
  15342. (org-occur regexp nil callback)
  15343. d)))
  15344. (defun org-check-dates-range (start-date end-date)
  15345. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15346. (interactive (list (org-read-date nil nil nil "Range starts")
  15347. (org-read-date nil nil nil "Range end")))
  15348. (let ((case-fold-search nil)
  15349. (regexp (org-re-timestamp org-ts-type))
  15350. (callback
  15351. (let ((type org-ts-type))
  15352. (lambda ()
  15353. (let ((match (match-string 1)))
  15354. (and
  15355. (if (memq type '(active inactive all))
  15356. (eq (org-element-type (save-excursion
  15357. (backward-char)
  15358. (org-element-context)))
  15359. 'timestamp)
  15360. (org-at-planning-p))
  15361. (not (time-less-p
  15362. (org-time-string-to-time match)
  15363. (org-time-string-to-time start-date)))
  15364. (time-less-p
  15365. (org-time-string-to-time match)
  15366. (org-time-string-to-time end-date))))))))
  15367. (message "%d entries between %s and %s"
  15368. (org-occur regexp nil callback) start-date end-date)))
  15369. (defun org-evaluate-time-range (&optional to-buffer)
  15370. "Evaluate a time range by computing the difference between start and end.
  15371. Normally the result is just printed in the echo area, but with prefix arg
  15372. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15373. If the time range is actually in a table, the result is inserted into the
  15374. next column.
  15375. For time difference computation, a year is assumed to be exactly 365
  15376. days in order to avoid rounding problems."
  15377. (interactive "P")
  15378. (or
  15379. (org-clock-update-time-maybe)
  15380. (save-excursion
  15381. (unless (org-at-date-range-p t)
  15382. (goto-char (point-at-bol))
  15383. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15384. (unless (org-at-date-range-p t)
  15385. (user-error "Not at a time-stamp range, and none found in current line")))
  15386. (let* ((ts1 (match-string 1))
  15387. (ts2 (match-string 2))
  15388. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15389. (match-end (match-end 0))
  15390. (time1 (org-time-string-to-time ts1))
  15391. (time2 (org-time-string-to-time ts2))
  15392. (t1 (float-time time1))
  15393. (t2 (float-time time2))
  15394. (diff (abs (- t2 t1)))
  15395. (negative (< (- t2 t1) 0))
  15396. ;; (ys (floor (* 365 24 60 60)))
  15397. (ds (* 24 60 60))
  15398. (hs (* 60 60))
  15399. (fy "%dy %dd %02d:%02d")
  15400. (fy1 "%dy %dd")
  15401. (fd "%dd %02d:%02d")
  15402. (fd1 "%dd")
  15403. (fh "%02d:%02d")
  15404. y d h m align)
  15405. (if havetime
  15406. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15407. y 0
  15408. d (floor (/ diff ds)) diff (mod diff ds)
  15409. h (floor (/ diff hs)) diff (mod diff hs)
  15410. m (floor (/ diff 60)))
  15411. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15412. y 0
  15413. d (floor (+ (/ diff ds) 0.5))
  15414. h 0 m 0))
  15415. (if (not to-buffer)
  15416. (message "%s" (org-make-tdiff-string y d h m))
  15417. (if (org-at-table-p)
  15418. (progn
  15419. (goto-char match-end)
  15420. (setq align t)
  15421. (and (looking-at " *|") (goto-char (match-end 0))))
  15422. (goto-char match-end))
  15423. (when (looking-at
  15424. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15425. (replace-match ""))
  15426. (when negative (insert " -"))
  15427. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15428. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15429. (insert " " (format fh h m))))
  15430. (when align (org-table-align))
  15431. (message "Time difference inserted")))))
  15432. (defun org-make-tdiff-string (y d h m)
  15433. (let ((fmt "")
  15434. (l nil))
  15435. (when (> y 0)
  15436. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15437. (push y l))
  15438. (when (> d 0)
  15439. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15440. (push d l))
  15441. (when (> h 0)
  15442. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15443. (push h l))
  15444. (when (> m 0)
  15445. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15446. (push m l))
  15447. (apply 'format fmt (nreverse l))))
  15448. (defun org-time-string-to-time (s)
  15449. "Convert timestamp string S into internal time."
  15450. (apply #'encode-time (org-parse-time-string s)))
  15451. (defun org-time-string-to-seconds (s)
  15452. "Convert a timestamp string S into a number of seconds."
  15453. (float-time (org-time-string-to-time s)))
  15454. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15455. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15456. "Convert time stamp S to an absolute day number.
  15457. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15458. stamp, get the closest date to DAYNR. If PREFER is
  15459. `past' (respectively `future') return a date past (respectively
  15460. after) or equal to DAYNR.
  15461. POS is the location of time stamp S, as a buffer position in
  15462. BUFFER.
  15463. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15464. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15465. signaled."
  15466. (cond
  15467. ((string-match "\\`%%\\((.*)\\)" s)
  15468. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15469. ;; only able to match individual dates. If it fails, raise an
  15470. ;; error.
  15471. (if (and daynr
  15472. (org-diary-sexp-entry
  15473. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15474. daynr
  15475. (signal 'org-diary-sexp-no-match (list s))))
  15476. (daynr (org-closest-date s daynr prefer))
  15477. (t (time-to-days
  15478. (condition-case errdata
  15479. (apply #'encode-time (org-parse-time-string s))
  15480. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15481. s
  15482. (if (not (and buffer pos)) ""
  15483. (format-message " at %d in buffer `%s'" pos buffer))
  15484. (cdr errdata))))))))
  15485. (defun org-days-to-iso-week (days)
  15486. "Return the iso week number."
  15487. (require 'cal-iso)
  15488. (car (calendar-iso-from-absolute days)))
  15489. (defun org-small-year-to-year (year)
  15490. "Convert 2-digit years into 4-digit years.
  15491. YEAR is expanded into one of the 30 next years, if possible, or
  15492. into a past one. Any year larger than 99 is returned unchanged."
  15493. (if (>= year 100) year
  15494. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15495. (century (/ current 100))
  15496. (offset (- year (% current 100))))
  15497. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15498. ((> offset -70) (+ (* century 100) year))
  15499. (t (+ (* (1+ century) 100) year))))))
  15500. (defun org-time-from-absolute (d)
  15501. "Return the time corresponding to date D.
  15502. D may be an absolute day number, or a calendar-type list (month day year)."
  15503. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15504. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15505. (defvar org-agenda-current-date)
  15506. (defun org-calendar-holiday ()
  15507. "List of holidays, for Diary display in Org mode."
  15508. (require 'holidays)
  15509. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15510. (and hl (mapconcat #'identity hl "; "))))
  15511. (defun org-diary-sexp-entry (sexp entry d)
  15512. "Process a SEXP diary ENTRY for date D."
  15513. (require 'diary-lib)
  15514. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15515. ;; dynamically.
  15516. (let* ((sexp `(let ((entry ,entry)
  15517. (date ',d))
  15518. ,(car (read-from-string sexp))))
  15519. (result (if calendar-debug-sexp (eval sexp)
  15520. (condition-case nil
  15521. (eval sexp)
  15522. (error
  15523. (beep)
  15524. (message "Bad sexp at line %d in %s: %s"
  15525. (org-current-line)
  15526. (buffer-file-name) sexp)
  15527. (sleep-for 2))))))
  15528. (cond ((stringp result) (split-string result "; "))
  15529. ((and (consp result)
  15530. (not (consp (cdr result)))
  15531. (stringp (cdr result))) (cdr result))
  15532. ((and (consp result)
  15533. (stringp (car result))) result)
  15534. (result entry))))
  15535. (defun org-diary-to-ical-string (frombuf)
  15536. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15537. This uses the icalendar.el library."
  15538. (let* ((tmpdir temporary-file-directory)
  15539. (tmpfile (make-temp-name
  15540. (expand-file-name "orgics" tmpdir)))
  15541. buf rtn b e)
  15542. (with-current-buffer frombuf
  15543. (icalendar-export-region (point-min) (point-max) tmpfile)
  15544. (setq buf (find-buffer-visiting tmpfile))
  15545. (set-buffer buf)
  15546. (goto-char (point-min))
  15547. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15548. (setq b (match-beginning 0)))
  15549. (goto-char (point-max))
  15550. (when (re-search-backward "^END:VEVENT" nil t)
  15551. (setq e (match-end 0)))
  15552. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15553. (kill-buffer buf)
  15554. (delete-file tmpfile)
  15555. rtn))
  15556. (defun org-closest-date (start current prefer)
  15557. "Return closest date to CURRENT starting from START.
  15558. CURRENT and START are both time stamps.
  15559. When PREFER is `past', return a date that is either CURRENT or
  15560. past. When PREFER is `future', return a date that is either
  15561. CURRENT or future.
  15562. Only time stamps with a repeater are modified. Any other time
  15563. stamp stay unchanged. In any case, return value is an absolute
  15564. day number."
  15565. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15566. ;; No repeater. Do not shift time stamp.
  15567. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15568. (let ((value (string-to-number (match-string 1 start)))
  15569. (type (match-string 2 start)))
  15570. (if (= 0 value)
  15571. ;; Repeater with a 0-value is considered as void.
  15572. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15573. (let* ((base (org-date-to-gregorian start))
  15574. (target (org-date-to-gregorian current))
  15575. (sday (calendar-absolute-from-gregorian base))
  15576. (cday (calendar-absolute-from-gregorian target))
  15577. n1 n2)
  15578. ;; If START is already past CURRENT, just return START.
  15579. (if (<= cday sday) sday
  15580. ;; Compute closest date before (N1) and closest date past
  15581. ;; (N2) CURRENT.
  15582. (pcase type
  15583. ("h"
  15584. (let ((missing-hours
  15585. (mod (+ (- (* 24 (- cday sday))
  15586. (nth 2 (org-parse-time-string start)))
  15587. org-extend-today-until)
  15588. value)))
  15589. (setf n1 (if (= missing-hours 0) cday
  15590. (- cday (1+ (/ missing-hours 24)))))
  15591. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15592. ((or "d" "w")
  15593. (let ((value (if (equal type "w") (* 7 value) value)))
  15594. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15595. (setf n2 (+ n1 value))))
  15596. ("m"
  15597. (let* ((add-months
  15598. (lambda (d n)
  15599. ;; Add N months to gregorian date D, i.e.,
  15600. ;; a list (MONTH DAY YEAR). Return a valid
  15601. ;; gregorian date.
  15602. (let ((m (+ (nth 0 d) n)))
  15603. (list (mod m 12)
  15604. (nth 1 d)
  15605. (+ (/ m 12) (nth 2 d))))))
  15606. (months ; Complete months to TARGET.
  15607. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15608. (- (nth 0 target) (nth 0 base))
  15609. ;; If START's day is greater than
  15610. ;; TARGET's, remove incomplete month.
  15611. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15612. value)
  15613. value))
  15614. (before (funcall add-months base months)))
  15615. (setf n1 (calendar-absolute-from-gregorian before))
  15616. (setf n2
  15617. (calendar-absolute-from-gregorian
  15618. (funcall add-months before value)))))
  15619. (_
  15620. (let* ((d (nth 1 base))
  15621. (m (nth 0 base))
  15622. (y (nth 2 base))
  15623. (years ; Complete years to TARGET.
  15624. (* (/ (- (nth 2 target)
  15625. y
  15626. ;; If START's month and day are
  15627. ;; greater than TARGET's, remove
  15628. ;; incomplete year.
  15629. (if (or (> (nth 0 target) m)
  15630. (and (= (nth 0 target) m)
  15631. (> (nth 1 target) d)))
  15632. 0
  15633. 1))
  15634. value)
  15635. value))
  15636. (before (list m d (+ y years))))
  15637. (setf n1 (calendar-absolute-from-gregorian before))
  15638. (setf n2 (calendar-absolute-from-gregorian
  15639. (list m d (+ (nth 2 before) value)))))))
  15640. ;; Handle PREFER parameter, if any.
  15641. (cond
  15642. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15643. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15644. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15645. (defun org-date-to-gregorian (d)
  15646. "Turn any specification of date D into a Gregorian date for the calendar."
  15647. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15648. ((and (listp d) (= (length d) 3)) d)
  15649. ((stringp d)
  15650. (let ((d (org-parse-time-string d)))
  15651. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15652. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15653. (defun org-parse-time-string (s &optional nodefault)
  15654. "Parse the standard Org time string.
  15655. This should be a lot faster than the normal `parse-time-string'.
  15656. If time is not given, defaults to 0:00. However, with optional
  15657. NODEFAULT, hour and minute fields will be nil if not given."
  15658. (cond ((string-match org-ts-regexp0 s)
  15659. (list 0
  15660. (when (or (match-beginning 8) (not nodefault))
  15661. (string-to-number (or (match-string 8 s) "0")))
  15662. (when (or (match-beginning 7) (not nodefault))
  15663. (string-to-number (or (match-string 7 s) "0")))
  15664. (string-to-number (match-string 4 s))
  15665. (string-to-number (match-string 3 s))
  15666. (string-to-number (match-string 2 s))
  15667. nil nil nil))
  15668. ((string-match "^<[^>]+>$" s)
  15669. ;; FIXME: `decode-time' needs to be called with ZONE as its
  15670. ;; second argument. However, this requires at least Emacs
  15671. ;; 25.1. We can do it when we switch to this version as our
  15672. ;; minimal requirement.
  15673. (decode-time (seconds-to-time (org-matcher-time s))))
  15674. (t (error "Not a standard Org time string: %s" s))))
  15675. (defun org-timestamp-up (&optional arg)
  15676. "Increase the date item at the cursor by one.
  15677. If the cursor is on the year, change the year. If it is on the month,
  15678. the day or the time, change that.
  15679. With prefix ARG, change by that many units."
  15680. (interactive "p")
  15681. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15682. (defun org-timestamp-down (&optional arg)
  15683. "Decrease the date item at the cursor by one.
  15684. If the cursor is on the year, change the year. If it is on the month,
  15685. the day or the time, change that.
  15686. With prefix ARG, change by that many units."
  15687. (interactive "p")
  15688. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15689. (defun org-timestamp-up-day (&optional arg)
  15690. "Increase the date in the time stamp by one day.
  15691. With prefix ARG, change that many days."
  15692. (interactive "p")
  15693. (if (and (not (org-at-timestamp-p 'lax))
  15694. (org-at-heading-p))
  15695. (org-todo 'up)
  15696. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15697. (defun org-timestamp-down-day (&optional arg)
  15698. "Decrease the date in the time stamp by one day.
  15699. With prefix ARG, change that many days."
  15700. (interactive "p")
  15701. (if (and (not (org-at-timestamp-p 'lax))
  15702. (org-at-heading-p))
  15703. (org-todo 'down)
  15704. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15705. (defun org-at-timestamp-p (&optional extended)
  15706. "Non-nil if point is inside a timestamp.
  15707. By default, the function only consider syntactically valid active
  15708. timestamps. However, the caller may have a broader definition
  15709. for timestamps. As a consequence, optional argument EXTENDED can
  15710. be set to the following values
  15711. `inactive'
  15712. Include also syntactically valid inactive timestamps.
  15713. `agenda'
  15714. Include timestamps allowed in Agenda, i.e., those in
  15715. properties drawers, planning lines and clock lines.
  15716. `lax'
  15717. Ignore context. The function matches any part of the
  15718. document looking like a timestamp. This includes comments,
  15719. example blocks...
  15720. For backward-compatibility with Org 9.0, every other non-nil
  15721. value is equivalent to `inactive'.
  15722. When at a timestamp, return the position of the point as a symbol
  15723. among `bracket', `after', `year', `month', `hour', `minute',
  15724. `day' or a number of character from the last know part of the
  15725. time stamp.
  15726. When matching, the match groups are the following:
  15727. group 1: year
  15728. group 2: month
  15729. group 3: day number
  15730. group 4: day name
  15731. group 5: hours, if any
  15732. group 6: minutes, if any"
  15733. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15734. (pos (point))
  15735. (match?
  15736. (let ((boundaries (org-in-regexp regexp)))
  15737. (save-match-data
  15738. (cond ((null boundaries) nil)
  15739. ((eq extended 'lax) t)
  15740. (t
  15741. (or (and (eq extended 'agenda)
  15742. (or (org-at-planning-p)
  15743. (org-at-property-p)
  15744. (and (bound-and-true-p
  15745. org-agenda-include-inactive-timestamps)
  15746. (org-at-clock-log-p))))
  15747. (eq 'timestamp
  15748. (save-excursion
  15749. (when (= pos (cdr boundaries)) (forward-char -1))
  15750. (org-element-type (org-element-context)))))))))))
  15751. (cond
  15752. ((not match?) nil)
  15753. ((= pos (match-beginning 0)) 'bracket)
  15754. ;; Distinguish location right before the closing bracket from
  15755. ;; right after it.
  15756. ((= pos (1- (match-end 0))) 'bracket)
  15757. ((= pos (match-end 0)) 'after)
  15758. ((org-pos-in-match-range pos 2) 'year)
  15759. ((org-pos-in-match-range pos 3) 'month)
  15760. ((org-pos-in-match-range pos 7) 'hour)
  15761. ((org-pos-in-match-range pos 8) 'minute)
  15762. ((or (org-pos-in-match-range pos 4)
  15763. (org-pos-in-match-range pos 5)) 'day)
  15764. ((and (> pos (or (match-end 8) (match-end 5)))
  15765. (< pos (match-end 0)))
  15766. (- pos (or (match-end 8) (match-end 5))))
  15767. (t 'day))))
  15768. (defun org-toggle-timestamp-type ()
  15769. "Toggle the type (<active> or [inactive]) of a time stamp."
  15770. (interactive)
  15771. (when (org-at-timestamp-p 'lax)
  15772. (let ((beg (match-beginning 0)) (end (match-end 0))
  15773. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15774. (save-excursion
  15775. (goto-char beg)
  15776. (while (re-search-forward "[][<>]" end t)
  15777. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15778. t t)))
  15779. (message "Timestamp is now %sactive"
  15780. (if (equal (char-after beg) ?<) "" "in")))))
  15781. (defun org-at-clock-log-p ()
  15782. "Non-nil if point is on a clock log line."
  15783. (and (org-match-line org-clock-line-re)
  15784. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15785. (defvar org-clock-history) ; defined in org-clock.el
  15786. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15787. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15788. "Change the date in the time stamp at point.
  15789. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15790. `year', `minute', `second'. If WHAT is not given, the cursor position
  15791. in the timestamp determines what will be changed.
  15792. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15793. (let ((origin (point))
  15794. (timestamp? (org-at-timestamp-p 'lax))
  15795. origin-cat
  15796. with-hm inactive
  15797. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15798. extra rem
  15799. ts time time0 fixnext clrgx)
  15800. (unless timestamp? (user-error "Not at a timestamp"))
  15801. (if (and (not what) (eq timestamp? 'bracket))
  15802. (org-toggle-timestamp-type)
  15803. ;; Point isn't on brackets. Remember the part of the time-stamp
  15804. ;; the point was in. Indeed, size of time-stamps may change,
  15805. ;; but point must be kept in the same category nonetheless.
  15806. (setq origin-cat timestamp?)
  15807. (when (and (not what) (not (eq timestamp? 'day))
  15808. org-display-custom-times
  15809. (get-text-property (point) 'display)
  15810. (not (get-text-property (1- (point)) 'display)))
  15811. (setq timestamp? 'day))
  15812. (setq timestamp? (or what timestamp?)
  15813. inactive (= (char-after (match-beginning 0)) ?\[)
  15814. ts (match-string 0))
  15815. (replace-match "")
  15816. (when (string-match
  15817. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15818. ts)
  15819. (setq extra (match-string 1 ts))
  15820. (when suppress-tmp-delay
  15821. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15822. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15823. (setq with-hm t))
  15824. (setq time0 (org-parse-time-string ts))
  15825. (when (and updown
  15826. (eq timestamp? 'minute)
  15827. (not current-prefix-arg))
  15828. ;; This looks like s-up and s-down. Change by one rounding step.
  15829. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15830. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15831. (setcar (cdr time0) (+ (nth 1 time0)
  15832. (if (> n 0) (- rem) (- dm rem))))))
  15833. (setq time
  15834. (apply #'encode-time
  15835. (or (car time0) 0)
  15836. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15837. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15838. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15839. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15840. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15841. (nthcdr 6 time0)))
  15842. (when (and (memq timestamp? '(hour minute))
  15843. extra
  15844. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15845. (setq extra (org-modify-ts-extra
  15846. extra
  15847. (if (eq timestamp? 'hour) 2 5)
  15848. n dm)))
  15849. (when (integerp timestamp?)
  15850. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15851. (when (eq what 'calendar)
  15852. (let ((cal-date (org-get-date-from-calendar)))
  15853. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15854. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15855. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15856. (setcar time0 (or (car time0) 0))
  15857. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15858. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15859. (setq time (apply 'encode-time time0))))
  15860. ;; Insert the new time-stamp, and ensure point stays in the same
  15861. ;; category as before (i.e. not after the last position in that
  15862. ;; category).
  15863. (let ((pos (point)))
  15864. ;; Stay before inserted string. `save-excursion' is of no use.
  15865. (setq org-last-changed-timestamp
  15866. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15867. (goto-char pos))
  15868. (save-match-data
  15869. (looking-at org-ts-regexp3)
  15870. (goto-char
  15871. (pcase origin-cat
  15872. ;; `day' category ends before `hour' if any, or at the end
  15873. ;; of the day name.
  15874. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15875. (`hour (min (match-end 7) origin))
  15876. (`minute (min (1- (match-end 8)) origin))
  15877. ((pred integerp) (min (1- (match-end 0)) origin))
  15878. ;; Point was right after the time-stamp. However, the
  15879. ;; time-stamp length might have changed, so refer to
  15880. ;; (match-end 0) instead.
  15881. (`after (match-end 0))
  15882. ;; `year' and `month' have both fixed size: point couldn't
  15883. ;; have moved into another part.
  15884. (_ origin))))
  15885. ;; Update clock if on a CLOCK line.
  15886. (org-clock-update-time-maybe)
  15887. ;; Maybe adjust the closest clock in `org-clock-history'
  15888. (when org-clock-adjust-closest
  15889. (if (not (and (org-at-clock-log-p)
  15890. (< 1 (length (delq nil (mapcar 'marker-position
  15891. org-clock-history))))))
  15892. (message "No clock to adjust")
  15893. (cond ((save-excursion ; fix previous clock?
  15894. (re-search-backward org-ts-regexp0 nil t)
  15895. (looking-back (concat org-clock-string " \\[")
  15896. (line-beginning-position)))
  15897. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15898. ((save-excursion ; fix next clock?
  15899. (re-search-backward org-ts-regexp0 nil t)
  15900. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15901. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15902. (save-window-excursion
  15903. ;; Find closest clock to point, adjust the previous/next one in history
  15904. (let* ((p (save-excursion (org-back-to-heading t)))
  15905. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15906. (clfixnth
  15907. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15908. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15909. (if (not clfixpos)
  15910. (message "No clock to adjust")
  15911. (save-excursion
  15912. (org-goto-marker-or-bmk clfixpos)
  15913. (org-show-subtree)
  15914. (when (re-search-forward clrgx nil t)
  15915. (goto-char (match-beginning 1))
  15916. (let (org-clock-adjust-closest)
  15917. (org-timestamp-change n timestamp? updown))
  15918. (message "Clock adjusted in %s for heading: %s"
  15919. (file-name-nondirectory (buffer-file-name))
  15920. (org-get-heading t t)))))))))
  15921. ;; Try to recenter the calendar window, if any.
  15922. (when (and org-calendar-follow-timestamp-change
  15923. (get-buffer-window "*Calendar*" t)
  15924. (memq timestamp? '(day month year)))
  15925. (org-recenter-calendar (time-to-days time))))))
  15926. (defun org-modify-ts-extra (s pos n dm)
  15927. "Change the different parts of the lead-time and repeat fields in timestamp."
  15928. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15929. ng h m new rem)
  15930. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15931. (cond
  15932. ((or (org-pos-in-match-range pos 2)
  15933. (org-pos-in-match-range pos 3))
  15934. (setq m (string-to-number (match-string 3 s))
  15935. h (string-to-number (match-string 2 s)))
  15936. (if (org-pos-in-match-range pos 2)
  15937. (setq h (+ h n))
  15938. (setq n (* dm (with-no-warnings (signum n))))
  15939. (unless (= 0 (setq rem (% m dm)))
  15940. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15941. (setq m (+ m n)))
  15942. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15943. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15944. (setq h (mod h 24))
  15945. (setq ng 1 new (format "-%02d:%02d" h m)))
  15946. ((org-pos-in-match-range pos 6)
  15947. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15948. ((org-pos-in-match-range pos 5)
  15949. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15950. ((org-pos-in-match-range pos 9)
  15951. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15952. ((org-pos-in-match-range pos 8)
  15953. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15954. (when ng
  15955. (setq s (concat
  15956. (substring s 0 (match-beginning ng))
  15957. new
  15958. (substring s (match-end ng))))))
  15959. s))
  15960. (defun org-recenter-calendar (d)
  15961. "If the calendar is visible, recenter it to date D."
  15962. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15963. (when cwin
  15964. (let ((calendar-move-hook nil))
  15965. (with-selected-window cwin
  15966. (calendar-goto-date
  15967. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15968. (defun org-goto-calendar (&optional arg)
  15969. "Go to the Emacs calendar at the current date.
  15970. If there is a time stamp in the current line, go to that date.
  15971. A prefix ARG can be used to force the current date."
  15972. (interactive "P")
  15973. (let ((calendar-move-hook nil)
  15974. (calendar-view-holidays-initially-flag nil)
  15975. (calendar-view-diary-initially-flag nil)
  15976. diff)
  15977. (when (or (org-at-timestamp-p 'lax)
  15978. (org-match-line (concat ".*" org-ts-regexp)))
  15979. (let ((d1 (time-to-days (current-time)))
  15980. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15981. (setq diff (- d2 d1))))
  15982. (calendar)
  15983. (calendar-goto-today)
  15984. (when (and diff (not arg)) (calendar-forward-day diff))))
  15985. (defun org-get-date-from-calendar ()
  15986. "Return a list (month day year) of date at point in calendar."
  15987. (with-current-buffer "*Calendar*"
  15988. (save-match-data
  15989. (calendar-cursor-to-date))))
  15990. (defun org-date-from-calendar ()
  15991. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15992. If there is already a time stamp at the cursor position, update it."
  15993. (interactive)
  15994. (if (org-at-timestamp-p 'lax)
  15995. (org-timestamp-change 0 'calendar)
  15996. (let ((cal-date (org-get-date-from-calendar)))
  15997. (org-insert-time-stamp
  15998. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15999. (defcustom org-effort-durations
  16000. `(("min" . 1)
  16001. ("h" . 60)
  16002. ("d" . ,(* 60 8))
  16003. ("w" . ,(* 60 8 5))
  16004. ("m" . ,(* 60 8 5 4))
  16005. ("y" . ,(* 60 8 5 40)))
  16006. "Conversion factor to minutes for an effort modifier.
  16007. Each entry has the form (MODIFIER . MINUTES).
  16008. In an effort string, a number followed by MODIFIER is multiplied
  16009. by the specified number of MINUTES to obtain an effort in
  16010. minutes.
  16011. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16012. effort string \"2hours\" is equivalent to 120 minutes."
  16013. :group 'org-agenda
  16014. :version "26.1"
  16015. :package-version '(Org . "8.3")
  16016. :type '(alist :key-type (string :tag "Modifier")
  16017. :value-type (number :tag "Minutes")))
  16018. (defcustom org-image-actual-width t
  16019. "Should we use the actual width of images when inlining them?
  16020. When set to t, always use the image width.
  16021. When set to a number, use imagemagick (when available) to set
  16022. the image's width to this value.
  16023. When set to a number in a list, try to get the width from any
  16024. #+ATTR.* keyword if it matches a width specification like
  16025. #+ATTR_HTML: :width 300px
  16026. and fall back on that number if none is found.
  16027. When set to nil, try to get the width from an #+ATTR.* keyword
  16028. and fall back on the original width if none is found.
  16029. This requires Emacs >= 24.1, build with imagemagick support."
  16030. :group 'org-appearance
  16031. :version "24.4"
  16032. :package-version '(Org . "8.0")
  16033. :type '(choice
  16034. (const :tag "Use the image width" t)
  16035. (integer :tag "Use a number of pixels")
  16036. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16037. (const :tag "Use #+ATTR* or don't resize" nil)))
  16038. (defcustom org-agenda-inhibit-startup nil
  16039. "Inhibit startup when preparing agenda buffers.
  16040. When this variable is t, the initialization of the Org agenda
  16041. buffers is inhibited: e.g. the visibility state is not set, the
  16042. tables are not re-aligned, etc."
  16043. :type 'boolean
  16044. :version "24.3"
  16045. :group 'org-agenda)
  16046. (defcustom org-agenda-ignore-properties nil
  16047. "Avoid updating text properties when building the agenda.
  16048. Properties are used to prepare buffers for effort estimates,
  16049. appointments, statistics and subtree-local categories.
  16050. If you don't use these in the agenda, you can add them to this
  16051. list and agenda building will be a bit faster.
  16052. The value is a list, with zero or more of the symbols `effort', `appt',
  16053. `stats' or `category'."
  16054. :type '(set :greedy t
  16055. (const effort)
  16056. (const appt)
  16057. (const stats)
  16058. (const category))
  16059. :version "26.1"
  16060. :package-version '(Org . "8.3")
  16061. :group 'org-agenda)
  16062. ;;;; Files
  16063. (defun org-save-all-org-buffers ()
  16064. "Save all Org buffers without user confirmation."
  16065. (interactive)
  16066. (message "Saving all Org buffers...")
  16067. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16068. (when (featurep 'org-id) (org-id-locations-save))
  16069. (message "Saving all Org buffers... done"))
  16070. (defun org-revert-all-org-buffers ()
  16071. "Revert all Org buffers.
  16072. Prompt for confirmation when there are unsaved changes.
  16073. Be sure you know what you are doing before letting this function
  16074. overwrite your changes.
  16075. This function is useful in a setup where one tracks Org files
  16076. with a version control system, to revert on one machine after pulling
  16077. changes from another. I believe the procedure must be like this:
  16078. 1. M-x org-save-all-org-buffers
  16079. 2. Pull changes from the other machine, resolve conflicts
  16080. 3. M-x org-revert-all-org-buffers"
  16081. (interactive)
  16082. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16083. (user-error "Abort"))
  16084. (save-excursion
  16085. (save-window-excursion
  16086. (dolist (b (buffer-list))
  16087. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16088. (with-current-buffer b buffer-file-name))
  16089. (pop-to-buffer-same-window b)
  16090. (revert-buffer t 'no-confirm)))
  16091. (when (and (featurep 'org-id) org-id-track-globally)
  16092. (org-id-locations-load)))))
  16093. ;;;; Agenda files
  16094. ;;;###autoload
  16095. (defun org-switchb (&optional arg)
  16096. "Switch between Org buffers.
  16097. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16098. With `\\[universal-argument] \\[universal-argument]' \
  16099. prefix, restrict available buffers to agenda files."
  16100. (interactive "P")
  16101. (let ((blist (org-buffer-list
  16102. (cond ((equal arg '(4)) 'files)
  16103. ((equal arg '(16)) 'agenda)))))
  16104. (pop-to-buffer-same-window
  16105. (completing-read "Org buffer: "
  16106. (mapcar #'list (mapcar #'buffer-name blist))
  16107. nil t))))
  16108. (defun org-buffer-list (&optional predicate exclude-tmp)
  16109. "Return a list of Org buffers.
  16110. PREDICATE can be `export', `files' or `agenda'.
  16111. export restrict the list to Export buffers.
  16112. files restrict the list to buffers visiting Org files.
  16113. agenda restrict the list to buffers visiting agenda files.
  16114. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16115. (let* ((bfn nil)
  16116. (agenda-files (and (eq predicate 'agenda)
  16117. (mapcar 'file-truename (org-agenda-files t))))
  16118. (filter
  16119. (cond
  16120. ((eq predicate 'files)
  16121. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16122. ((eq predicate 'export)
  16123. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16124. ((eq predicate 'agenda)
  16125. (lambda (b)
  16126. (with-current-buffer b
  16127. (and (derived-mode-p 'org-mode)
  16128. (setq bfn (buffer-file-name b))
  16129. (member (file-truename bfn) agenda-files)))))
  16130. (t (lambda (b) (with-current-buffer b
  16131. (or (derived-mode-p 'org-mode)
  16132. (string-match "\\*Org .*Export"
  16133. (buffer-name b)))))))))
  16134. (delq nil
  16135. (mapcar
  16136. (lambda(b)
  16137. (if (and (funcall filter b)
  16138. (or (not exclude-tmp)
  16139. (not (string-match "tmp" (buffer-name b)))))
  16140. b
  16141. nil))
  16142. (buffer-list)))))
  16143. (defun org-agenda-files (&optional unrestricted archives)
  16144. "Get the list of agenda files.
  16145. Optional UNRESTRICTED means return the full list even if a restriction
  16146. is currently in place.
  16147. When ARCHIVES is t, include all archive files that are really being
  16148. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16149. `org-agenda-archives-mode' is t."
  16150. (let ((files
  16151. (cond
  16152. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16153. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16154. ((listp org-agenda-files) org-agenda-files)
  16155. (t (error "Invalid value of `org-agenda-files'")))))
  16156. (setq files (apply 'append
  16157. (mapcar (lambda (f)
  16158. (if (file-directory-p f)
  16159. (directory-files
  16160. f t org-agenda-file-regexp)
  16161. (list f)))
  16162. files)))
  16163. (when org-agenda-skip-unavailable-files
  16164. (setq files (delq nil
  16165. (mapcar (function
  16166. (lambda (file)
  16167. (and (file-readable-p file) file)))
  16168. files))))
  16169. (when (or (eq archives t)
  16170. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16171. (setq files (org-add-archive-files files)))
  16172. files))
  16173. (defun org-agenda-file-p (&optional file)
  16174. "Return non-nil, if FILE is an agenda file.
  16175. If FILE is omitted, use the file associated with the current
  16176. buffer."
  16177. (let ((fname (or file (buffer-file-name))))
  16178. (and fname
  16179. (member (file-truename fname)
  16180. (mapcar #'file-truename (org-agenda-files t))))))
  16181. (defun org-edit-agenda-file-list ()
  16182. "Edit the list of agenda files.
  16183. Depending on setup, this either uses customize to edit the variable
  16184. `org-agenda-files', or it visits the file that is holding the list. In the
  16185. latter case, the buffer is set up in a way that saving it automatically kills
  16186. the buffer and restores the previous window configuration."
  16187. (interactive)
  16188. (if (stringp org-agenda-files)
  16189. (let ((cw (current-window-configuration)))
  16190. (find-file org-agenda-files)
  16191. (setq-local org-window-configuration cw)
  16192. (add-hook 'after-save-hook
  16193. (lambda ()
  16194. (set-window-configuration
  16195. (prog1 org-window-configuration
  16196. (kill-buffer (current-buffer))))
  16197. (org-install-agenda-files-menu)
  16198. (message "New agenda file list installed"))
  16199. nil 'local)
  16200. (message "%s" (substitute-command-keys
  16201. "Edit list and finish with \\[save-buffer]")))
  16202. (customize-variable 'org-agenda-files)))
  16203. (defun org-store-new-agenda-file-list (list)
  16204. "Set new value for the agenda file list and save it correctly."
  16205. (if (stringp org-agenda-files)
  16206. (let ((fe (org-read-agenda-file-list t)) b u)
  16207. (while (setq b (find-buffer-visiting org-agenda-files))
  16208. (kill-buffer b))
  16209. (with-temp-file org-agenda-files
  16210. (insert
  16211. (mapconcat
  16212. (lambda (f) ;; Keep un-expanded entries.
  16213. (if (setq u (assoc f fe))
  16214. (cdr u)
  16215. f))
  16216. list "\n")
  16217. "\n")))
  16218. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16219. (org-insert-mode-line-in-empty-file nil))
  16220. (setq org-agenda-files list)
  16221. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16222. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16223. "Read the list of agenda files from a file.
  16224. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16225. filenames, used by `org-store-new-agenda-file-list' to write back
  16226. un-expanded file names."
  16227. (when (file-directory-p org-agenda-files)
  16228. (error "`org-agenda-files' cannot be a single directory"))
  16229. (when (stringp org-agenda-files)
  16230. (with-temp-buffer
  16231. (insert-file-contents org-agenda-files)
  16232. (mapcar
  16233. (lambda (f)
  16234. (let ((e (expand-file-name (substitute-in-file-name f)
  16235. org-directory)))
  16236. (if pair-with-expansion
  16237. (cons e f)
  16238. e)))
  16239. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16240. ;;;###autoload
  16241. (defun org-cycle-agenda-files ()
  16242. "Cycle through the files in `org-agenda-files'.
  16243. If the current buffer visits an agenda file, find the next one in the list.
  16244. If the current buffer does not, find the first agenda file."
  16245. (interactive)
  16246. (let* ((fs (or (org-agenda-files t)
  16247. (user-error "No agenda files")))
  16248. (files (copy-sequence fs))
  16249. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16250. file)
  16251. (when tcf
  16252. (while (and (setq file (pop files))
  16253. (not (equal (file-truename file) tcf)))))
  16254. (find-file (car (or files fs)))
  16255. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16256. (defun org-agenda-file-to-front (&optional to-end)
  16257. "Move/add the current file to the top of the agenda file list.
  16258. If the file is not present in the list, it is added to the front. If it is
  16259. present, it is moved there. With optional argument TO-END, add/move to the
  16260. end of the list."
  16261. (interactive "P")
  16262. (let ((org-agenda-skip-unavailable-files nil)
  16263. (file-alist (mapcar (lambda (x)
  16264. (cons (file-truename x) x))
  16265. (org-agenda-files t)))
  16266. (ctf (file-truename
  16267. (or buffer-file-name
  16268. (user-error "Please save the current buffer to a file"))))
  16269. x had)
  16270. (setq x (assoc ctf file-alist) had x)
  16271. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16272. (if to-end
  16273. (setq file-alist (append (delq x file-alist) (list x)))
  16274. (setq file-alist (cons x (delq x file-alist))))
  16275. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16276. (org-install-agenda-files-menu)
  16277. (message "File %s to %s of agenda file list"
  16278. (if had "moved" "added") (if to-end "end" "front"))))
  16279. (defun org-remove-file (&optional file)
  16280. "Remove current file from the list of files in variable `org-agenda-files'.
  16281. These are the files which are being checked for agenda entries.
  16282. Optional argument FILE means use this file instead of the current."
  16283. (interactive)
  16284. (let* ((org-agenda-skip-unavailable-files nil)
  16285. (file (or file buffer-file-name
  16286. (user-error "Current buffer does not visit a file")))
  16287. (true-file (file-truename file))
  16288. (afile (abbreviate-file-name file))
  16289. (files (delq nil (mapcar
  16290. (lambda (x)
  16291. (unless (equal true-file
  16292. (file-truename x))
  16293. x))
  16294. (org-agenda-files t)))))
  16295. (if (not (= (length files) (length (org-agenda-files t))))
  16296. (progn
  16297. (org-store-new-agenda-file-list files)
  16298. (org-install-agenda-files-menu)
  16299. (message "Removed from Org Agenda list: %s" afile))
  16300. (message "File was not in list: %s (not removed)" afile))))
  16301. (defun org-file-menu-entry (file)
  16302. (vector file (list 'find-file file) t))
  16303. (defun org-check-agenda-file (file)
  16304. "Make sure FILE exists. If not, ask user what to do."
  16305. (unless (file-exists-p file)
  16306. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16307. (abbreviate-file-name file))
  16308. (let ((r (downcase (read-char-exclusive))))
  16309. (cond
  16310. ((equal r ?r)
  16311. (org-remove-file file)
  16312. (throw 'nextfile t))
  16313. (t (user-error "Abort"))))))
  16314. (defun org-get-agenda-file-buffer (file)
  16315. "Get an agenda buffer visiting FILE.
  16316. If the buffer needs to be created, add it to the list of buffers
  16317. which might be released later."
  16318. (let ((buf (org-find-base-buffer-visiting file)))
  16319. (if buf
  16320. buf ; just return it
  16321. ;; Make a new buffer and remember it
  16322. (setq buf (find-file-noselect file))
  16323. (when buf (push buf org-agenda-new-buffers))
  16324. buf)))
  16325. (defun org-release-buffers (blist)
  16326. "Release all buffers in list, asking the user for confirmation when needed.
  16327. When a buffer is unmodified, it is just killed. When modified, it is saved
  16328. \(if the user agrees) and then killed."
  16329. (let (file)
  16330. (dolist (buf blist)
  16331. (setq file (buffer-file-name buf))
  16332. (when (and (buffer-modified-p buf)
  16333. file
  16334. (y-or-n-p (format "Save file %s? " file)))
  16335. (with-current-buffer buf (save-buffer)))
  16336. (kill-buffer buf))))
  16337. (defun org-agenda-prepare-buffers (files)
  16338. "Create buffers for all agenda files, protect archived trees and comments."
  16339. (interactive)
  16340. (let ((pa '(:org-archived t))
  16341. (pc '(:org-comment t))
  16342. (pall '(:org-archived t :org-comment t))
  16343. (inhibit-read-only t)
  16344. (org-inhibit-startup org-agenda-inhibit-startup)
  16345. (rea (concat ":" org-archive-tag ":"))
  16346. re pos)
  16347. (setq org-tag-alist-for-agenda nil
  16348. org-tag-groups-alist-for-agenda nil)
  16349. (save-excursion
  16350. (save-restriction
  16351. (dolist (file files)
  16352. (catch 'nextfile
  16353. (if (bufferp file)
  16354. (set-buffer file)
  16355. (org-check-agenda-file file)
  16356. (set-buffer (org-get-agenda-file-buffer file)))
  16357. (widen)
  16358. (org-set-regexps-and-options 'tags-only)
  16359. (setq pos (point))
  16360. (or (memq 'category org-agenda-ignore-properties)
  16361. (org-refresh-category-properties))
  16362. (or (memq 'stats org-agenda-ignore-properties)
  16363. (org-refresh-stats-properties))
  16364. (or (memq 'effort org-agenda-ignore-properties)
  16365. (org-refresh-effort-properties))
  16366. (or (memq 'appt org-agenda-ignore-properties)
  16367. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16368. (setq org-todo-keywords-for-agenda
  16369. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16370. (setq org-done-keywords-for-agenda
  16371. (append org-done-keywords-for-agenda org-done-keywords))
  16372. (setq org-todo-keyword-alist-for-agenda
  16373. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16374. (setq org-tag-alist-for-agenda
  16375. (org-tag-add-to-alist
  16376. org-tag-alist-for-agenda
  16377. org-current-tag-alist))
  16378. ;; Merge current file's tag groups into global
  16379. ;; `org-tag-groups-alist-for-agenda'.
  16380. (when org-group-tags
  16381. (dolist (alist org-tag-groups-alist)
  16382. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16383. (if old
  16384. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16385. (push alist org-tag-groups-alist-for-agenda)))))
  16386. (org-with-silent-modifications
  16387. (save-excursion
  16388. (remove-text-properties (point-min) (point-max) pall)
  16389. (when org-agenda-skip-archived-trees
  16390. (goto-char (point-min))
  16391. (while (re-search-forward rea nil t)
  16392. (when (org-at-heading-p t)
  16393. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16394. (goto-char (point-min))
  16395. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16396. (while (re-search-forward re nil t)
  16397. (when (save-match-data (org-in-commented-heading-p t))
  16398. (add-text-properties
  16399. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16400. (goto-char pos)))))
  16401. (setq org-todo-keywords-for-agenda
  16402. (org-uniquify org-todo-keywords-for-agenda))
  16403. (setq org-todo-keyword-alist-for-agenda
  16404. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16405. ;;;; CDLaTeX minor mode
  16406. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16407. "Keymap for the minor `org-cdlatex-mode'.")
  16408. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16409. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16410. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16411. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16412. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16413. (defvar org-cdlatex-texmathp-advice-is-done nil
  16414. "Flag remembering if we have applied the advice to texmathp already.")
  16415. (define-minor-mode org-cdlatex-mode
  16416. "Toggle the minor `org-cdlatex-mode'.
  16417. This mode supports entering LaTeX environment and math in LaTeX fragments
  16418. in Org mode.
  16419. \\{org-cdlatex-mode-map}"
  16420. nil " OCDL" nil
  16421. (when org-cdlatex-mode
  16422. (require 'cdlatex)
  16423. (run-hooks 'cdlatex-mode-hook)
  16424. (cdlatex-compute-tables))
  16425. (unless org-cdlatex-texmathp-advice-is-done
  16426. (setq org-cdlatex-texmathp-advice-is-done t)
  16427. (defadvice texmathp (around org-math-always-on activate)
  16428. "Always return t in Org buffers.
  16429. This is because we want to insert math symbols without dollars even outside
  16430. the LaTeX math segments. If Org mode thinks that point is actually inside
  16431. an embedded LaTeX fragment, let `texmathp' do its job.
  16432. `\\[org-cdlatex-mode-map]'"
  16433. (interactive)
  16434. (let (p)
  16435. (cond
  16436. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16437. ((eq this-command 'cdlatex-math-symbol)
  16438. (setq ad-return-value t
  16439. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16440. (t
  16441. (let ((p (org-inside-LaTeX-fragment-p)))
  16442. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16443. (setq ad-return-value t
  16444. texmathp-why '("Org mode embedded math" . 0))
  16445. (when p ad-do-it)))))))))
  16446. (defun turn-on-org-cdlatex ()
  16447. "Unconditionally turn on `org-cdlatex-mode'."
  16448. (org-cdlatex-mode 1))
  16449. (defun org-try-cdlatex-tab ()
  16450. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16451. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16452. - inside a LaTeX fragment, or
  16453. - after the first word in a line, where an abbreviation expansion could
  16454. insert a LaTeX environment."
  16455. (when org-cdlatex-mode
  16456. (cond
  16457. ;; Before any word on the line: No expansion possible.
  16458. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16459. ;; Just after first word on the line: Expand it. Make sure it
  16460. ;; cannot happen on headlines, though.
  16461. ((save-excursion
  16462. (skip-chars-backward "a-zA-Z0-9*")
  16463. (skip-chars-backward " \t")
  16464. (and (bolp) (not (org-at-heading-p))))
  16465. (cdlatex-tab) t)
  16466. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16467. (defun org-cdlatex-underscore-caret (&optional _arg)
  16468. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16469. Revert to the normal definition outside of these fragments."
  16470. (interactive "P")
  16471. (if (org-inside-LaTeX-fragment-p)
  16472. (call-interactively 'cdlatex-sub-superscript)
  16473. (let (org-cdlatex-mode)
  16474. (call-interactively (key-binding (vector last-input-event))))))
  16475. (defun org-cdlatex-math-modify (&optional _arg)
  16476. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16477. Revert to the normal definition outside of these fragments."
  16478. (interactive "P")
  16479. (if (org-inside-LaTeX-fragment-p)
  16480. (call-interactively 'cdlatex-math-modify)
  16481. (let (org-cdlatex-mode)
  16482. (call-interactively (key-binding (vector last-input-event))))))
  16483. (defun org-cdlatex-environment-indent (&optional environment item)
  16484. "Execute `cdlatex-environment' and indent the inserted environment.
  16485. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16486. The inserted environment is indented to current indentation
  16487. unless point is at the beginning of the line, in which the
  16488. environment remains unintended."
  16489. (interactive)
  16490. ;; cdlatex-environment always return nil. Therefore, capture output
  16491. ;; first and determine if an environment was selected.
  16492. (let* ((beg (point-marker))
  16493. (end (copy-marker (point) t))
  16494. (inserted (progn
  16495. (ignore-errors (cdlatex-environment environment item))
  16496. (< beg end)))
  16497. ;; Figure out how many lines to move forward after the
  16498. ;; environment has been inserted.
  16499. (lines (when inserted
  16500. (save-excursion
  16501. (- (cl-loop while (< beg (point))
  16502. with x = 0
  16503. do (forward-line -1)
  16504. (cl-incf x)
  16505. finally return x)
  16506. (if (progn (goto-char beg)
  16507. (and (progn (skip-chars-forward " \t") (eolp))
  16508. (progn (skip-chars-backward " \t") (bolp))))
  16509. 1 0)))))
  16510. (env (org-trim (delete-and-extract-region beg end))))
  16511. (when inserted
  16512. ;; Get indentation of next line unless at column 0.
  16513. (let ((ind (if (bolp) 0
  16514. (save-excursion
  16515. (org-return-indent)
  16516. (prog1 (org-get-indentation)
  16517. (when (progn (skip-chars-forward " \t") (eolp))
  16518. (delete-region beg (point)))))))
  16519. (bol (progn (skip-chars-backward " \t") (bolp))))
  16520. ;; Insert a newline before environment unless at column zero
  16521. ;; to "escape" the current line. Insert a newline if
  16522. ;; something is one the same line as \end{ENVIRONMENT}.
  16523. (insert
  16524. (concat (unless bol "\n") env
  16525. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16526. (unless (zerop ind)
  16527. (save-excursion
  16528. (goto-char beg)
  16529. (while (< (point) end)
  16530. (unless (eolp) (indent-line-to ind))
  16531. (forward-line))))
  16532. (goto-char beg)
  16533. (forward-line lines)
  16534. (indent-line-to ind)))
  16535. (set-marker beg nil)
  16536. (set-marker end nil)))
  16537. ;;;; LaTeX fragments
  16538. (defun org-inside-LaTeX-fragment-p ()
  16539. "Test if point is inside a LaTeX fragment.
  16540. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16541. sequence appearing also before point.
  16542. Even though the matchers for math are configurable, this function assumes
  16543. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16544. delimiters are skipped when they have been removed by customization.
  16545. The return value is nil, or a cons cell with the delimiter and the
  16546. position of this delimiter.
  16547. This function does a reasonably good job, but can locally be fooled by
  16548. for example currency specifications. For example it will assume being in
  16549. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16550. fragments that are properly closed, but during editing, we have to live
  16551. with the uncertainty caused by missing closing delimiters. This function
  16552. looks only before point, not after."
  16553. (catch 'exit
  16554. (let ((pos (point))
  16555. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16556. (lim (save-excursion (org-backward-paragraph) (point)))
  16557. dd-on str (start 0) m re)
  16558. (goto-char pos)
  16559. (when dodollar
  16560. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16561. re (nth 1 (assoc "$" org-latex-regexps)))
  16562. (while (string-match re str start)
  16563. (cond
  16564. ((= (match-end 0) (length str))
  16565. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16566. ((= (match-end 0) (- (length str) 5))
  16567. (throw 'exit nil))
  16568. (t (setq start (match-end 0))))))
  16569. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16570. (goto-char pos)
  16571. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16572. (and (match-beginning 2) (throw 'exit nil))
  16573. ;; count $$
  16574. (while (re-search-backward "\\$\\$" lim t)
  16575. (setq dd-on (not dd-on)))
  16576. (goto-char pos)
  16577. (when dd-on (cons "$$" m))))))
  16578. (defun org-inside-latex-macro-p ()
  16579. "Is point inside a LaTeX macro or its arguments?"
  16580. (save-match-data
  16581. (org-in-regexp
  16582. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16583. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16584. "Build an overlay between BEG and END using IMAGE file.
  16585. Argument IMAGETYPE is the extension of the displayed image,
  16586. as a string. It defaults to \"png\"."
  16587. (let ((ov (make-overlay beg end))
  16588. (imagetype (or (intern imagetype) 'png)))
  16589. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16590. (overlay-put ov 'evaporate t)
  16591. (overlay-put ov
  16592. 'modification-hooks
  16593. (list (lambda (o _flag _beg _end &optional _l)
  16594. (delete-overlay o))))
  16595. (overlay-put ov
  16596. 'display
  16597. (list 'image :type imagetype :file image :ascent 'center))))
  16598. (defun org--list-latex-overlays (&optional beg end)
  16599. "List all Org LaTeX overlays in current buffer.
  16600. Limit to overlays between BEG and END when those are provided."
  16601. (cl-remove-if-not
  16602. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16603. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16604. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16605. "Remove all overlays with LaTeX fragment images in current buffer.
  16606. When optional arguments BEG and END are non-nil, remove all
  16607. overlays between them instead. Return a non-nil value when some
  16608. overlays were removed, nil otherwise."
  16609. (let ((overlays (org--list-latex-overlays beg end)))
  16610. (mapc #'delete-overlay overlays)
  16611. overlays))
  16612. (defun org-toggle-latex-fragment (&optional arg)
  16613. "Preview the LaTeX fragment at point, or all locally or globally.
  16614. If the cursor is on a LaTeX fragment, create the image and overlay
  16615. it over the source code, if there is none. Remove it otherwise.
  16616. If there is no fragment at point, display all fragments in the
  16617. current section.
  16618. With prefix ARG, preview or clear image for all fragments in the
  16619. current subtree or in the whole buffer when used before the first
  16620. headline. With a prefix ARG `\\[universal-argument] \
  16621. \\[universal-argument]' preview or clear images
  16622. for all fragments in the buffer."
  16623. (interactive "P")
  16624. (when (display-graphic-p)
  16625. (catch 'exit
  16626. (save-excursion
  16627. (let (beg end msg)
  16628. (cond
  16629. ((or (equal arg '(16))
  16630. (and (equal arg '(4))
  16631. (org-with-limited-levels (org-before-first-heading-p))))
  16632. (if (org-remove-latex-fragment-image-overlays)
  16633. (progn (message "LaTeX fragments images removed from buffer")
  16634. (throw 'exit nil))
  16635. (setq msg "Creating images for buffer...")))
  16636. ((equal arg '(4))
  16637. (org-with-limited-levels (org-back-to-heading t))
  16638. (setq beg (point))
  16639. (setq end (progn (org-end-of-subtree t) (point)))
  16640. (if (org-remove-latex-fragment-image-overlays beg end)
  16641. (progn
  16642. (message "LaTeX fragment images removed from subtree")
  16643. (throw 'exit nil))
  16644. (setq msg "Creating images for subtree...")))
  16645. ((let ((datum (org-element-context)))
  16646. (when (memq (org-element-type datum)
  16647. '(latex-environment latex-fragment))
  16648. (setq beg (org-element-property :begin datum))
  16649. (setq end (org-element-property :end datum))
  16650. (if (org-remove-latex-fragment-image-overlays beg end)
  16651. (progn (message "LaTeX fragment image removed")
  16652. (throw 'exit nil))
  16653. (setq msg "Creating image...")))))
  16654. (t
  16655. (org-with-limited-levels
  16656. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16657. (outline-previous-heading)
  16658. (point)))
  16659. (setq end (progn (outline-next-heading) (point)))
  16660. (if (org-remove-latex-fragment-image-overlays beg end)
  16661. (progn
  16662. (message "LaTeX fragment images removed from section")
  16663. (throw 'exit nil))
  16664. (setq msg "Creating images for section...")))))
  16665. (let ((file (buffer-file-name (buffer-base-buffer))))
  16666. (org-format-latex
  16667. (concat org-preview-latex-image-directory "org-ltximg")
  16668. beg end
  16669. ;; Emacs cannot overlay images from remote hosts. Create
  16670. ;; it in `temporary-file-directory' instead.
  16671. (if (or (not file) (file-remote-p file))
  16672. temporary-file-directory
  16673. default-directory)
  16674. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16675. (message (concat msg "done")))))))
  16676. (defun org-format-latex
  16677. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16678. "Replace LaTeX fragments with links to an image.
  16679. The function takes care of creating the replacement image.
  16680. Only consider fragments between BEG and END when those are
  16681. provided.
  16682. When optional argument OVERLAYS is non-nil, display the image on
  16683. top of the fragment instead of replacing it.
  16684. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16685. Some of the options can be changed using the variable
  16686. `org-format-latex-options', which see."
  16687. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16688. (unless (eq processing-type 'verbatim)
  16689. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16690. (cnt 0)
  16691. checkdir-flag)
  16692. (goto-char (or beg (point-min)))
  16693. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16694. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16695. (overlay-recenter (or end (point-max))))
  16696. (while (re-search-forward math-regexp end t)
  16697. (unless (and overlays
  16698. (eq (get-char-property (point) 'org-overlay-type)
  16699. 'org-latex-overlay))
  16700. (let* ((context (org-element-context))
  16701. (type (org-element-type context)))
  16702. (when (memq type '(latex-environment latex-fragment))
  16703. (let ((block-type (eq type 'latex-environment))
  16704. (value (org-element-property :value context))
  16705. (beg (org-element-property :begin context))
  16706. (end (save-excursion
  16707. (goto-char (org-element-property :end context))
  16708. (skip-chars-backward " \r\t\n")
  16709. (point))))
  16710. (cond
  16711. ((eq processing-type 'mathjax)
  16712. ;; Prepare for MathJax processing.
  16713. (if (not (string-match "\\`\\$\\$?" value))
  16714. (goto-char end)
  16715. (delete-region beg end)
  16716. (if (string= (match-string 0 value) "$$")
  16717. (insert "\\[" (substring value 2 -2) "\\]")
  16718. (insert "\\(" (substring value 1 -1) "\\)"))))
  16719. ((assq processing-type org-preview-latex-process-alist)
  16720. ;; Process to an image.
  16721. (cl-incf cnt)
  16722. (goto-char beg)
  16723. (let* ((processing-info
  16724. (cdr (assq processing-type org-preview-latex-process-alist)))
  16725. (face (face-at-point))
  16726. ;; Get the colors from the face at point.
  16727. (fg
  16728. (let ((color (plist-get org-format-latex-options
  16729. :foreground)))
  16730. (if (and forbuffer (eq color 'auto))
  16731. (face-attribute face :foreground nil 'default)
  16732. color)))
  16733. (bg
  16734. (let ((color (plist-get org-format-latex-options
  16735. :background)))
  16736. (if (and forbuffer (eq color 'auto))
  16737. (face-attribute face :background nil 'default)
  16738. color)))
  16739. (hash (sha1 (prin1-to-string
  16740. (list org-format-latex-header
  16741. org-latex-default-packages-alist
  16742. org-latex-packages-alist
  16743. org-format-latex-options
  16744. forbuffer value fg bg))))
  16745. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16746. (absprefix (expand-file-name prefix dir))
  16747. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16748. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16749. (sep (and block-type "\n\n"))
  16750. (link (concat sep "[[file:" linkfile "]]" sep))
  16751. (options
  16752. (org-combine-plists
  16753. org-format-latex-options
  16754. `(:foreground ,fg :background ,bg))))
  16755. (when msg (message msg cnt))
  16756. (unless checkdir-flag ; Ensure the directory exists.
  16757. (setq checkdir-flag t)
  16758. (let ((todir (file-name-directory absprefix)))
  16759. (unless (file-directory-p todir)
  16760. (make-directory todir t))))
  16761. (unless (file-exists-p movefile)
  16762. (org-create-formula-image
  16763. value movefile options forbuffer processing-type))
  16764. (if overlays
  16765. (progn
  16766. (dolist (o (overlays-in beg end))
  16767. (when (eq (overlay-get o 'org-overlay-type)
  16768. 'org-latex-overlay)
  16769. (delete-overlay o)))
  16770. (org--format-latex-make-overlay beg end movefile imagetype)
  16771. (goto-char end))
  16772. (delete-region beg end)
  16773. (insert
  16774. (org-add-props link
  16775. (list 'org-latex-src
  16776. (replace-regexp-in-string "\"" "" value)
  16777. 'org-latex-src-embed-type
  16778. (if block-type 'paragraph 'character)))))))
  16779. ((eq processing-type 'mathml)
  16780. ;; Process to MathML.
  16781. (unless (org-format-latex-mathml-available-p)
  16782. (user-error "LaTeX to MathML converter not configured"))
  16783. (cl-incf cnt)
  16784. (when msg (message msg cnt))
  16785. (goto-char beg)
  16786. (delete-region beg end)
  16787. (insert (org-format-latex-as-mathml
  16788. value block-type prefix dir)))
  16789. (t
  16790. (error "Unknown conversion process %s for LaTeX fragments"
  16791. processing-type)))))))))))
  16792. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16793. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16794. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16795. sucessful, return the portion between \"<math...> </math>\"
  16796. elements otherwise return nil. When MATHML-FILE is specified,
  16797. write the results in to that file. When invoked as an
  16798. interactive command, prompt for LATEX-FRAG, with initial value
  16799. set to the current active region and echo the results for user
  16800. inspection."
  16801. (interactive (list (let ((frag (when (org-region-active-p)
  16802. (buffer-substring-no-properties
  16803. (region-beginning) (region-end)))))
  16804. (read-string "LaTeX Fragment: " frag nil frag))))
  16805. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16806. (let* ((tmp-in-file
  16807. (let ((file (file-relative-name
  16808. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16809. (write-region latex-frag nil file)
  16810. file))
  16811. (tmp-out-file (file-relative-name
  16812. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16813. (cmd (format-spec
  16814. org-latex-to-mathml-convert-command
  16815. `((?j . ,(and org-latex-to-mathml-jar-file
  16816. (shell-quote-argument
  16817. (expand-file-name
  16818. org-latex-to-mathml-jar-file))))
  16819. (?I . ,(shell-quote-argument tmp-in-file))
  16820. (?i . ,latex-frag)
  16821. (?o . ,(shell-quote-argument tmp-out-file)))))
  16822. mathml shell-command-output)
  16823. (when (called-interactively-p 'any)
  16824. (unless (org-format-latex-mathml-available-p)
  16825. (user-error "LaTeX to MathML converter not configured")))
  16826. (message "Running %s" cmd)
  16827. (setq shell-command-output (shell-command-to-string cmd))
  16828. (setq mathml
  16829. (when (file-readable-p tmp-out-file)
  16830. (with-current-buffer (find-file-noselect tmp-out-file t)
  16831. (goto-char (point-min))
  16832. (when (re-search-forward
  16833. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16834. (regexp-quote
  16835. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16836. nil t)
  16837. (prog1 (match-string 0) (kill-buffer))))))
  16838. (cond
  16839. (mathml
  16840. (setq mathml
  16841. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16842. (when mathml-file
  16843. (write-region mathml nil mathml-file))
  16844. (when (called-interactively-p 'any)
  16845. (message mathml)))
  16846. ((message "LaTeX to MathML conversion failed")
  16847. (message shell-command-output)))
  16848. (delete-file tmp-in-file)
  16849. (when (file-exists-p tmp-out-file)
  16850. (delete-file tmp-out-file))
  16851. mathml))
  16852. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16853. prefix &optional dir)
  16854. "Use `org-create-math-formula' but check local cache first."
  16855. (let* ((absprefix (expand-file-name prefix dir))
  16856. (print-length nil) (print-level nil)
  16857. (formula-id (concat
  16858. "formula-"
  16859. (sha1
  16860. (prin1-to-string
  16861. (list latex-frag
  16862. org-latex-to-mathml-convert-command)))))
  16863. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16864. (formula-cache-dir (file-name-directory formula-cache)))
  16865. (unless (file-directory-p formula-cache-dir)
  16866. (make-directory formula-cache-dir t))
  16867. (unless (file-exists-p formula-cache)
  16868. (org-create-math-formula latex-frag formula-cache))
  16869. (if (file-exists-p formula-cache)
  16870. ;; Successful conversion. Return the link to MathML file.
  16871. (org-add-props
  16872. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16873. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16874. 'org-latex-src-embed-type (if latex-frag-type
  16875. 'paragraph 'character)))
  16876. ;; Failed conversion. Return the LaTeX fragment verbatim
  16877. latex-frag)))
  16878. (defun org--get-display-dpi ()
  16879. "Get the DPI of the display.
  16880. The function assumes that the display has the same pixel width in
  16881. the horizontal and vertical directions."
  16882. (if (display-graphic-p)
  16883. (round (/ (display-pixel-height)
  16884. (/ (display-mm-height) 25.4)))
  16885. (error "Attempt to calculate the dpi of a non-graphic display")))
  16886. (defun org-create-formula-image
  16887. (string tofile options buffer &optional processing-type)
  16888. "Create an image from LaTeX source using external processes.
  16889. The LaTeX STRING is saved to a temporary LaTeX file, then
  16890. converted to an image file by process PROCESSING-TYPE defined in
  16891. `org-preview-latex-process-alist'. A nil value defaults to
  16892. `org-preview-latex-default-process'.
  16893. The generated image file is eventually moved to TOFILE.
  16894. The OPTIONS argument controls the size, foreground color and
  16895. background color of the generated image.
  16896. When BUFFER non-nil, this function is used for LaTeX previewing.
  16897. Otherwise, it is used to deal with LaTeX snippets showed in
  16898. a HTML file."
  16899. (let* ((processing-type (or processing-type
  16900. org-preview-latex-default-process))
  16901. (processing-info
  16902. (cdr (assq processing-type org-preview-latex-process-alist)))
  16903. (programs (plist-get processing-info :programs))
  16904. (error-message (or (plist-get processing-info :message) ""))
  16905. (use-xcolor (plist-get processing-info :use-xcolor))
  16906. (image-input-type (plist-get processing-info :image-input-type))
  16907. (image-output-type (plist-get processing-info :image-output-type))
  16908. (post-clean (or (plist-get processing-info :post-clean)
  16909. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16910. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16911. (latex-header
  16912. (or (plist-get processing-info :latex-header)
  16913. (org-latex-make-preamble
  16914. (org-export-get-environment (org-export-get-backend 'latex))
  16915. org-format-latex-header
  16916. 'snippet)))
  16917. (latex-compiler (plist-get processing-info :latex-compiler))
  16918. (image-converter (plist-get processing-info :image-converter))
  16919. (tmpdir temporary-file-directory)
  16920. (texfilebase (make-temp-name
  16921. (expand-file-name "orgtex" tmpdir)))
  16922. (texfile (concat texfilebase ".tex"))
  16923. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16924. '(1.0 . 1.0)))
  16925. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16926. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16927. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16928. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16929. "Black"))
  16930. (bg (or (plist-get options (if buffer :background :html-background))
  16931. "Transparent"))
  16932. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16933. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16934. (dolist (program programs)
  16935. (org-check-external-command program error-message))
  16936. (if use-xcolor
  16937. (progn (if (eq fg 'default)
  16938. (setq fg (org-latex-color :foreground))
  16939. (setq fg (org-latex-color-format fg)))
  16940. (if (eq bg 'default)
  16941. (setq bg (org-latex-color :background))
  16942. (setq bg (org-latex-color-format
  16943. (if (string= bg "Transparent") "white" bg))))
  16944. (with-temp-file texfile
  16945. (insert latex-header)
  16946. (insert "\n\\begin{document}\n"
  16947. "\\definecolor{fg}{rgb}{" fg "}\n"
  16948. "\\definecolor{bg}{rgb}{" bg "}\n"
  16949. "\n\\pagecolor{bg}\n"
  16950. "\n{\\color{fg}\n"
  16951. string
  16952. "\n}\n"
  16953. "\n\\end{document}\n")))
  16954. (if (eq fg 'default)
  16955. (setq fg (org-dvipng-color :foreground))
  16956. (unless (string= fg "Transparent")
  16957. (setq fg (org-dvipng-color-format fg))))
  16958. (if (eq bg 'default)
  16959. (setq bg (org-dvipng-color :background))
  16960. (unless (string= bg "Transparent")
  16961. (setq bg (org-dvipng-color-format bg))))
  16962. (with-temp-file texfile
  16963. (insert latex-header)
  16964. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16965. (let* ((err-msg (format "Please adjust `%s' part of \
  16966. `org-preview-latex-process-alist'."
  16967. processing-type))
  16968. (image-input-file
  16969. (org-compile-file
  16970. texfile latex-compiler image-input-type err-msg log-buf))
  16971. (image-output-file
  16972. (org-compile-file
  16973. image-input-file image-converter image-output-type err-msg log-buf
  16974. `((?F . ,(shell-quote-argument fg))
  16975. (?B . ,(shell-quote-argument bg))
  16976. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16977. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16978. (copy-file image-output-file tofile 'replace)
  16979. (dolist (e post-clean)
  16980. (when (file-exists-p (concat texfilebase e))
  16981. (delete-file (concat texfilebase e))))
  16982. image-output-file)))
  16983. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16984. "Fill a LaTeX header template TPL.
  16985. In the template, the following place holders will be recognized:
  16986. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16987. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16988. [PACKAGES] \\usepackage statements for PKG
  16989. [NO-PACKAGES] do not include PKG
  16990. [EXTRA] the string EXTRA
  16991. [NO-EXTRA] do not include EXTRA
  16992. For backward compatibility, if both the positive and the negative place
  16993. holder is missing, the positive one (without the \"NO-\") will be
  16994. assumed to be present at the end of the template.
  16995. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16996. EXTRA is a string.
  16997. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16998. (let (rpl (end ""))
  16999. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17000. (setq rpl (if (or (match-end 1) (not def-pkg))
  17001. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17002. tpl (replace-match rpl t t tpl))
  17003. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17004. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17005. (setq rpl (if (or (match-end 1) (not pkg))
  17006. "" (org-latex-packages-to-string pkg snippets-p t))
  17007. tpl (replace-match rpl t t tpl))
  17008. (when pkg (setq end
  17009. (concat end "\n"
  17010. (org-latex-packages-to-string pkg snippets-p)))))
  17011. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17012. (setq rpl (if (or (match-end 1) (not extra))
  17013. "" (concat extra "\n"))
  17014. tpl (replace-match rpl t t tpl))
  17015. (when (and extra (string-match "\\S-" extra))
  17016. (setq end (concat end "\n" extra))))
  17017. (if (string-match "\\S-" end)
  17018. (concat tpl "\n" end)
  17019. tpl)))
  17020. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17021. "Turn an alist of packages into a string with the \\usepackage macros."
  17022. (setq pkg (mapconcat (lambda(p)
  17023. (cond
  17024. ((stringp p) p)
  17025. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17026. (format "%% Package %s omitted" (cadr p)))
  17027. ((equal "" (car p))
  17028. (format "\\usepackage{%s}" (cadr p)))
  17029. (t
  17030. (format "\\usepackage[%s]{%s}"
  17031. (car p) (cadr p)))))
  17032. pkg
  17033. "\n"))
  17034. (if newline (concat pkg "\n") pkg))
  17035. (defun org-dvipng-color (attr)
  17036. "Return a RGB color specification for dvipng."
  17037. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17038. (defun org-dvipng-color-format (color-name)
  17039. "Convert COLOR-NAME to a RGB color value for dvipng."
  17040. (apply #'format "rgb %s %s %s"
  17041. (mapcar 'org-normalize-color
  17042. (color-values color-name))))
  17043. (defun org-latex-color (attr)
  17044. "Return a RGB color for the LaTeX color package."
  17045. (org-latex-color-format (face-attribute 'default attr nil)))
  17046. (defun org-latex-color-format (color-name)
  17047. "Convert COLOR-NAME to a RGB color value."
  17048. (apply #'format "%s,%s,%s"
  17049. (mapcar 'org-normalize-color
  17050. (color-values color-name))))
  17051. (defun org-normalize-color (value)
  17052. "Return string to be used as color value for an RGB component."
  17053. (format "%g" (/ value 65535.0)))
  17054. ;; Image display
  17055. (defvar-local org-inline-image-overlays nil)
  17056. (defun org-toggle-inline-images (&optional include-linked)
  17057. "Toggle the display of inline images.
  17058. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17059. (interactive "P")
  17060. (if org-inline-image-overlays
  17061. (progn
  17062. (org-remove-inline-images)
  17063. (when (called-interactively-p 'interactive)
  17064. (message "Inline image display turned off")))
  17065. (org-display-inline-images include-linked)
  17066. (when (called-interactively-p 'interactive)
  17067. (message (if org-inline-image-overlays
  17068. (format "%d images displayed inline"
  17069. (length org-inline-image-overlays))
  17070. "No images to display inline")))))
  17071. (defun org-redisplay-inline-images ()
  17072. "Refresh the display of inline images."
  17073. (interactive)
  17074. (if (not org-inline-image-overlays)
  17075. (org-toggle-inline-images)
  17076. (org-toggle-inline-images)
  17077. (org-toggle-inline-images)))
  17078. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17079. "Display inline images.
  17080. An inline image is a link which follows either of these
  17081. conventions:
  17082. 1. Its path is a file with an extension matching return value
  17083. from `image-file-name-regexp' and it has no contents.
  17084. 2. Its description consists in a single link of the previous
  17085. type.
  17086. When optional argument INCLUDE-LINKED is non-nil, also links with
  17087. a text description part will be inlined. This can be nice for
  17088. a quick look at those images, but it does not reflect what
  17089. exported files will look like.
  17090. When optional argument REFRESH is non-nil, refresh existing
  17091. images between BEG and END. This will create new image displays
  17092. only if necessary. BEG and END default to the buffer
  17093. boundaries."
  17094. (interactive "P")
  17095. (when (display-graphic-p)
  17096. (unless refresh
  17097. (org-remove-inline-images)
  17098. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17099. (org-with-wide-buffer
  17100. (goto-char (or beg (point-min)))
  17101. (let* ((case-fold-search t)
  17102. (file-extension-re (image-file-name-regexp))
  17103. (link-abbrevs (mapcar #'car
  17104. (append org-link-abbrev-alist-local
  17105. org-link-abbrev-alist)))
  17106. ;; Check absolute, relative file names and explicit
  17107. ;; "file:" links. Also check link abbreviations since
  17108. ;; some might expand to "file" links.
  17109. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17110. (if (not link-abbrevs) ""
  17111. (format "\\|\\(?:%s:\\)"
  17112. (regexp-opt link-abbrevs))))))
  17113. (while (re-search-forward file-types-re end t)
  17114. (let ((link (save-match-data (org-element-context))))
  17115. ;; Check if we're at an inline image, i.e., an image file
  17116. ;; link without a description (unless INCLUDE-LINKED is
  17117. ;; non-nil).
  17118. (when (and (equal "file" (org-element-property :type link))
  17119. (or include-linked
  17120. (null (org-element-contents link)))
  17121. (string-match-p file-extension-re
  17122. (org-element-property :path link)))
  17123. (let ((file (expand-file-name
  17124. (org-link-unescape
  17125. (org-element-property :path link)))))
  17126. (when (file-exists-p file)
  17127. (let ((width
  17128. ;; Apply `org-image-actual-width' specifications.
  17129. (cond
  17130. ((not (image-type-available-p 'imagemagick)) nil)
  17131. ((eq org-image-actual-width t) nil)
  17132. ((listp org-image-actual-width)
  17133. (or
  17134. ;; First try to find a width among
  17135. ;; attributes associated to the paragraph
  17136. ;; containing link.
  17137. (let ((paragraph
  17138. (let ((e link))
  17139. (while (and (setq e (org-element-property
  17140. :parent e))
  17141. (not (eq (org-element-type e)
  17142. 'paragraph))))
  17143. e)))
  17144. (when paragraph
  17145. (save-excursion
  17146. (goto-char (org-element-property :begin paragraph))
  17147. (when
  17148. (re-search-forward
  17149. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17150. (org-element-property
  17151. :post-affiliated paragraph)
  17152. t)
  17153. (string-to-number (match-string 1))))))
  17154. ;; Otherwise, fall-back to provided number.
  17155. (car org-image-actual-width)))
  17156. ((numberp org-image-actual-width)
  17157. org-image-actual-width)))
  17158. (old (get-char-property-and-overlay
  17159. (org-element-property :begin link)
  17160. 'org-image-overlay)))
  17161. (if (and (car-safe old) refresh)
  17162. (image-refresh (overlay-get (cdr old) 'display))
  17163. (let ((image (create-image file
  17164. (and width 'imagemagick)
  17165. nil
  17166. :width width)))
  17167. (when image
  17168. (let ((ov (make-overlay
  17169. (org-element-property :begin link)
  17170. (progn
  17171. (goto-char
  17172. (org-element-property :end link))
  17173. (skip-chars-backward " \t")
  17174. (point)))))
  17175. (overlay-put ov 'display image)
  17176. (overlay-put ov 'face 'default)
  17177. (overlay-put ov 'org-image-overlay t)
  17178. (overlay-put
  17179. ov 'modification-hooks
  17180. (list 'org-display-inline-remove-overlay))
  17181. (push ov org-inline-image-overlays)))))))))))))))
  17182. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17183. "Remove inline-display overlay if a corresponding region is modified."
  17184. (let ((inhibit-modification-hooks t))
  17185. (when (and ov after)
  17186. (delete ov org-inline-image-overlays)
  17187. (delete-overlay ov))))
  17188. (defun org-remove-inline-images ()
  17189. "Remove inline display of images."
  17190. (interactive)
  17191. (mapc #'delete-overlay org-inline-image-overlays)
  17192. (setq org-inline-image-overlays nil))
  17193. ;;; Key bindings
  17194. (defun org-remap (map &rest commands)
  17195. "In MAP, remap the functions given in COMMANDS.
  17196. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17197. (let (new old)
  17198. (while commands
  17199. (setq old (pop commands) new (pop commands))
  17200. (org-defkey map (vector 'remap old) new))))
  17201. ;;;; Outline functions that can be remapped in Org
  17202. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17203. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17204. (define-key org-mode-map [remap outline-forward-same-level]
  17205. #'org-forward-heading-same-level)
  17206. (define-key org-mode-map [remap outline-backward-same-level]
  17207. #'org-backward-heading-same-level)
  17208. (define-key org-mode-map [remap outline-show-branches]
  17209. #'org-kill-note-or-show-branches)
  17210. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17211. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17212. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17213. (define-key org-mode-map [remap outline-next-visible-heading]
  17214. #'org-next-visible-heading)
  17215. (define-key org-mode-map [remap outline-previous-visible-heading]
  17216. #'org-previous-visible-heading)
  17217. (define-key org-mode-map [remap show-children] #'org-show-children)
  17218. ;;;; Make `C-c C-x' a prefix key
  17219. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17220. ;;;; TAB key with modifiers
  17221. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17222. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17223. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17224. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17225. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17226. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17227. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17228. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17229. ;;;; RET key with modifiers
  17230. (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
  17231. (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
  17232. (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
  17233. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17234. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17235. ;;;; Cursor keys with modifiers
  17236. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17237. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17238. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17239. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17240. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17241. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17242. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17243. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17244. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17245. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17246. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17247. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17248. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17249. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17250. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17251. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17252. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17253. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17254. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17255. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17256. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17257. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17258. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17259. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17260. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17261. ;;;; Babel keys
  17262. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17263. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17264. (define-key org-babel-map key def))
  17265. ;;;; Extra keys for TTY access.
  17266. ;; We only set them when really needed because otherwise the
  17267. ;; menus don't show the simple keys
  17268. (when (or org-use-extra-keys (not window-system))
  17269. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17270. (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
  17271. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17272. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17273. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17274. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17275. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17276. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17277. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17278. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17279. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17280. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17281. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17282. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17283. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17284. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17285. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17286. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17287. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17288. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17289. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17290. ;;;; Narrow map
  17291. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17292. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17293. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17294. ;;;; Remap usual Emacs bindings
  17295. (org-remap org-mode-map
  17296. 'self-insert-command 'org-self-insert-command
  17297. 'delete-char 'org-delete-char
  17298. 'delete-backward-char 'org-delete-backward-char
  17299. 'kill-line 'org-kill-line
  17300. 'open-line 'org-open-line
  17301. 'yank 'org-yank
  17302. 'comment-dwim 'org-comment-dwim
  17303. 'move-beginning-of-line 'org-beginning-of-line
  17304. 'move-end-of-line 'org-end-of-line
  17305. 'forward-paragraph 'org-forward-paragraph
  17306. 'backward-paragraph 'org-backward-paragraph
  17307. 'backward-sentence 'org-backward-sentence
  17308. 'forward-sentence 'org-forward-sentence
  17309. 'fill-paragraph 'org-fill-paragraph
  17310. 'delete-indentation 'org-delete-indentation
  17311. 'transpose-words 'org-transpose-words)
  17312. ;;;; All the other keys
  17313. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17314. (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
  17315. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17316. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17317. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17318. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17319. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17320. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17321. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17322. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17323. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17324. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17325. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17326. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17327. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17328. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17329. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17330. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17331. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17332. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17333. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17334. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17335. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17336. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17337. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17338. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17339. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17340. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17341. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17342. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17343. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17344. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17345. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17346. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17347. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17348. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17349. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17350. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17351. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17352. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17353. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17354. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17355. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17356. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17357. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17358. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17359. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17360. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17361. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17362. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17363. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17364. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17365. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17366. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17367. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17368. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17369. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17370. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17371. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17372. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17373. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17374. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17375. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17376. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17377. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17378. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17379. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17380. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17381. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17382. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17383. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17384. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17385. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17386. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17387. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17388. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17389. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17390. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17391. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17392. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17393. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17394. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17395. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17396. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17397. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17398. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17399. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17400. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17401. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17402. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17403. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17404. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17405. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17406. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17407. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17408. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17409. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17410. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17411. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17412. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17413. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17414. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17415. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17416. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17417. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17418. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17419. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17420. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17421. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17422. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17423. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17424. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17425. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17426. (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
  17427. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17428. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17429. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17430. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17431. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17432. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17433. (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17434. (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
  17435. (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17436. (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17437. (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17438. ;;; Speed commands
  17439. (defconst org-speed-commands-default
  17440. '(
  17441. ("Outline Navigation")
  17442. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17443. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17444. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17445. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17446. ("F" . org-next-block)
  17447. ("B" . org-previous-block)
  17448. ("u" . (org-speed-move-safe 'outline-up-heading))
  17449. ("j" . org-goto)
  17450. ("g" . (org-refile t))
  17451. ("Outline Visibility")
  17452. ("c" . org-cycle)
  17453. ("C" . org-shifttab)
  17454. (" " . org-display-outline-path)
  17455. ("s" . org-narrow-to-subtree)
  17456. ("=" . org-columns)
  17457. ("Outline Structure Editing")
  17458. ("U" . org-metaup)
  17459. ("D" . org-metadown)
  17460. ("r" . org-metaright)
  17461. ("l" . org-metaleft)
  17462. ("R" . org-shiftmetaright)
  17463. ("L" . org-shiftmetaleft)
  17464. ("i" . (progn (forward-char 1) (call-interactively
  17465. 'org-insert-heading-respect-content)))
  17466. ("^" . org-sort)
  17467. ("w" . org-refile)
  17468. ("a" . org-archive-subtree-default-with-confirmation)
  17469. ("@" . org-mark-subtree)
  17470. ("#" . org-toggle-comment)
  17471. ("Clock Commands")
  17472. ("I" . org-clock-in)
  17473. ("O" . org-clock-out)
  17474. ("Meta Data Editing")
  17475. ("t" . org-todo)
  17476. ("," . (org-priority))
  17477. ("0" . (org-priority ?\ ))
  17478. ("1" . (org-priority ?A))
  17479. ("2" . (org-priority ?B))
  17480. ("3" . (org-priority ?C))
  17481. (":" . org-set-tags-command)
  17482. ("e" . org-set-effort)
  17483. ("E" . org-inc-effort)
  17484. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17485. (org-entry-put (point) "APPT_WARNTIME" m)))
  17486. ("Agenda Views etc")
  17487. ("v" . org-agenda)
  17488. ("/" . org-sparse-tree)
  17489. ("Misc")
  17490. ("o" . org-open-at-point)
  17491. ("?" . org-speed-command-help)
  17492. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17493. (">" . (org-agenda-remove-restriction-lock))
  17494. )
  17495. "The default speed commands.")
  17496. (defun org-print-speed-command (e)
  17497. (if (> (length (car e)) 1)
  17498. (progn
  17499. (princ "\n")
  17500. (princ (car e))
  17501. (princ "\n")
  17502. (princ (make-string (length (car e)) ?-))
  17503. (princ "\n"))
  17504. (princ (car e))
  17505. (princ " ")
  17506. (if (symbolp (cdr e))
  17507. (princ (symbol-name (cdr e)))
  17508. (prin1 (cdr e)))
  17509. (princ "\n")))
  17510. (defun org-speed-command-help ()
  17511. "Show the available speed commands."
  17512. (interactive)
  17513. (if (not org-use-speed-commands)
  17514. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17515. (with-output-to-temp-buffer "*Help*"
  17516. (princ "User-defined Speed commands\n===========================\n")
  17517. (mapc #'org-print-speed-command org-speed-commands-user)
  17518. (princ "\n")
  17519. (princ "Built-in Speed commands\n=======================\n")
  17520. (mapc #'org-print-speed-command org-speed-commands-default))
  17521. (with-current-buffer "*Help*"
  17522. (setq truncate-lines t))))
  17523. (defun org-speed-move-safe (cmd)
  17524. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17525. If not, return to the original position and throw an error."
  17526. (interactive)
  17527. (let ((pos (point)))
  17528. (call-interactively cmd)
  17529. (unless (and (bolp) (org-at-heading-p))
  17530. (goto-char pos)
  17531. (error "Boundary reached while executing %s" cmd))))
  17532. (defvar org-self-insert-command-undo-counter 0)
  17533. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17534. (defvar org-speed-command nil)
  17535. (defun org-speed-command-activate (keys)
  17536. "Hook for activating single-letter speed commands.
  17537. `org-speed-commands-default' specifies a minimal command set.
  17538. Use `org-speed-commands-user' for further customization."
  17539. (when (or (and (bolp) (looking-at org-outline-regexp))
  17540. (and (functionp org-use-speed-commands)
  17541. (funcall org-use-speed-commands)))
  17542. (cdr (assoc keys (append org-speed-commands-user
  17543. org-speed-commands-default)))))
  17544. (defun org-babel-speed-command-activate (keys)
  17545. "Hook for activating single-letter code block commands."
  17546. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17547. (cdr (assoc keys org-babel-key-bindings))))
  17548. (defcustom org-speed-command-hook
  17549. '(org-speed-command-activate org-babel-speed-command-activate)
  17550. "Hook for activating speed commands at strategic locations.
  17551. Hook functions are called in sequence until a valid handler is
  17552. found.
  17553. Each hook takes a single argument, a user-pressed command key
  17554. which is also a `self-insert-command' from the global map.
  17555. Within the hook, examine the cursor position and the command key
  17556. and return nil or a valid handler as appropriate. Handler could
  17557. be one of an interactive command, a function, or a form.
  17558. Set `org-use-speed-commands' to non-nil value to enable this
  17559. hook. The default setting is `org-speed-command-activate'."
  17560. :group 'org-structure
  17561. :version "24.1"
  17562. :type 'hook)
  17563. (defun org-self-insert-command (N)
  17564. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17565. If the cursor is in a table looking at whitespace, the whitespace is
  17566. overwritten, and the table is not marked as requiring realignment."
  17567. (interactive "p")
  17568. (org-check-before-invisible-edit 'insert)
  17569. (cond
  17570. ((and org-use-speed-commands
  17571. (let ((kv (this-command-keys-vector)))
  17572. (setq org-speed-command
  17573. (run-hook-with-args-until-success
  17574. 'org-speed-command-hook
  17575. (make-string 1 (aref kv (1- (length kv))))))))
  17576. (cond
  17577. ((commandp org-speed-command)
  17578. (setq this-command org-speed-command)
  17579. (call-interactively org-speed-command))
  17580. ((functionp org-speed-command)
  17581. (funcall org-speed-command))
  17582. ((and org-speed-command (listp org-speed-command))
  17583. (eval org-speed-command))
  17584. (t (let (org-use-speed-commands)
  17585. (call-interactively 'org-self-insert-command)))))
  17586. ((and
  17587. (= N 1)
  17588. (not (org-region-active-p))
  17589. (org-at-table-p)
  17590. (progn
  17591. ;; Check if we blank the field, and if that triggers align.
  17592. (and (featurep 'org-table)
  17593. org-table-auto-blank-field
  17594. (memq last-command
  17595. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17596. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17597. ;; Got extra space, this field does not determine
  17598. ;; column width.
  17599. (let (org-table-may-need-update) (org-table-blank-field))
  17600. ;; No extra space, this field may determine column
  17601. ;; width.
  17602. (org-table-blank-field)))
  17603. t)
  17604. (looking-at "[^|\n]* |"))
  17605. ;; There is room for insertion without re-aligning the table.
  17606. (self-insert-command N)
  17607. (org-table-with-shrunk-field
  17608. (save-excursion
  17609. (skip-chars-forward "^|")
  17610. ;; Do not delete last space, which is
  17611. ;; `org-table-separator-space', but the regular space before
  17612. ;; it.
  17613. (delete-region (- (point) 2) (1- (point))))))
  17614. (t
  17615. (setq org-table-may-need-update t)
  17616. (self-insert-command N)
  17617. (org-fix-tags-on-the-fly)
  17618. (when org-self-insert-cluster-for-undo
  17619. (if (not (eq last-command 'org-self-insert-command))
  17620. (setq org-self-insert-command-undo-counter 1)
  17621. (if (>= org-self-insert-command-undo-counter 20)
  17622. (setq org-self-insert-command-undo-counter 1)
  17623. (and (> org-self-insert-command-undo-counter 0)
  17624. buffer-undo-list (listp buffer-undo-list)
  17625. (not (cadr buffer-undo-list)) ; remove nil entry
  17626. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17627. (setq org-self-insert-command-undo-counter
  17628. (1+ org-self-insert-command-undo-counter))))))))
  17629. (defun org-check-before-invisible-edit (kind)
  17630. "Check is editing if kind KIND would be dangerous with invisible text around.
  17631. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17632. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17633. (when (and org-catch-invisible-edits
  17634. (or (not (boundp 'visible-mode)) (not visible-mode))
  17635. (or (get-char-property (point) 'invisible)
  17636. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17637. ;; OK, we need to take a closer look. Do not consider
  17638. ;; invisibility obtained through text properties (e.g., link
  17639. ;; fontification), as it cannot be toggled.
  17640. (let* ((invisible-at-point
  17641. (pcase (get-char-property-and-overlay (point) 'invisible)
  17642. (`(,_ . ,(and (pred overlayp) o)) o)))
  17643. ;; Assume that point cannot land in the middle of an
  17644. ;; overlay, or between two overlays.
  17645. (invisible-before-point
  17646. (and (not invisible-at-point)
  17647. (not (bobp))
  17648. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17649. (`(,_ . ,(and (pred overlayp) o)) o))))
  17650. (border-and-ok-direction
  17651. (or
  17652. ;; Check if we are acting predictably before invisible
  17653. ;; text.
  17654. (and invisible-at-point
  17655. (memq kind '(insert delete-backward)))
  17656. ;; Check if we are acting predictably after invisible text
  17657. ;; This works not well, and I have turned it off. It seems
  17658. ;; better to always show and stop after invisible text.
  17659. ;; (and (not invisible-at-point) invisible-before-point
  17660. ;; (memq kind '(insert delete)))
  17661. )))
  17662. (when (or invisible-at-point invisible-before-point)
  17663. (when (eq org-catch-invisible-edits 'error)
  17664. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17665. (if (and org-custom-properties-overlays
  17666. (y-or-n-p "Display invisible properties in this buffer? "))
  17667. (org-toggle-custom-properties-visibility)
  17668. ;; Make the area visible
  17669. (save-excursion
  17670. (when invisible-before-point
  17671. (goto-char
  17672. (previous-single-char-property-change (point) 'invisible)))
  17673. ;; Remove whatever overlay is currently making yet-to-be
  17674. ;; edited text invisible. Also remove nested invisibility
  17675. ;; related overlays.
  17676. (delete-overlay (or invisible-at-point invisible-before-point))
  17677. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17678. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17679. (`(,_ . ,(and (pred overlayp) o))
  17680. (delete-overlay o)
  17681. t)))))
  17682. (cond
  17683. ((eq org-catch-invisible-edits 'show)
  17684. ;; That's it, we do the edit after showing
  17685. (message
  17686. "Unfolding invisible region around point before editing")
  17687. (sit-for 1))
  17688. ((and (eq org-catch-invisible-edits 'smart)
  17689. border-and-ok-direction)
  17690. (message "Unfolding invisible region around point before editing"))
  17691. (t
  17692. ;; Don't do the edit, make the user repeat it in full visibility
  17693. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17694. (defun org-fix-tags-on-the-fly ()
  17695. "Align tags in headline at point.
  17696. Unlike to `org-set-tags', it ignores region and sorting."
  17697. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  17698. (org-at-heading-p))
  17699. (let ((org-ignore-region t)
  17700. (org-tags-sort-function nil))
  17701. (org-set-tags nil t))))
  17702. (defun org-delete-backward-char (N)
  17703. "Like `delete-backward-char', insert whitespace at field end in tables.
  17704. When deleting backwards, in tables this function will insert whitespace in
  17705. front of the next \"|\" separator, to keep the table aligned. The table will
  17706. still be marked for re-alignment if the field did fill the entire column,
  17707. because, in this case the deletion might narrow the column."
  17708. (interactive "p")
  17709. (save-match-data
  17710. (org-check-before-invisible-edit 'delete-backward)
  17711. (if (and (= N 1)
  17712. (not overwrite-mode)
  17713. (not (org-region-active-p))
  17714. (not (eq (char-before) ?|))
  17715. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17716. (looking-at-p ".*?|")
  17717. (org-at-table-p))
  17718. (progn (forward-char -1) (org-delete-char 1))
  17719. (backward-delete-char N)
  17720. (org-fix-tags-on-the-fly))))
  17721. (defun org-delete-char (N)
  17722. "Like `delete-char', but insert whitespace at field end in tables.
  17723. When deleting characters, in tables this function will insert whitespace in
  17724. front of the next \"|\" separator, to keep the table aligned. The table will
  17725. still be marked for re-alignment if the field did fill the entire column,
  17726. because, in this case the deletion might narrow the column."
  17727. (interactive "p")
  17728. (save-match-data
  17729. (org-check-before-invisible-edit 'delete)
  17730. (cond
  17731. ((or (/= N 1)
  17732. (eq (char-after) ?|)
  17733. (save-excursion (skip-chars-backward " \t") (bolp))
  17734. (not (org-at-table-p)))
  17735. (delete-char N)
  17736. (org-fix-tags-on-the-fly))
  17737. ((looking-at ".\\(.*?\\)|")
  17738. (let* ((update? org-table-may-need-update)
  17739. (noalign (looking-at-p ".*? |")))
  17740. (delete-char 1)
  17741. (org-table-with-shrunk-field
  17742. (save-excursion
  17743. ;; Last space is `org-table-separator-space', so insert
  17744. ;; a regular one before it instead.
  17745. (goto-char (- (match-end 0) 2))
  17746. (insert " ")))
  17747. ;; If there were two spaces at the end, this field does not
  17748. ;; determine the width of the column.
  17749. (when noalign (setq org-table-may-need-update update?))))
  17750. (t
  17751. (delete-char N)))))
  17752. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17753. (put 'org-self-insert-command 'delete-selection
  17754. (lambda ()
  17755. (not (run-hook-with-args-until-success
  17756. 'self-insert-uses-region-functions))))
  17757. (put 'orgtbl-self-insert-command 'delete-selection
  17758. (lambda ()
  17759. (not (run-hook-with-args-until-success
  17760. 'self-insert-uses-region-functions))))
  17761. (put 'org-delete-char 'delete-selection 'supersede)
  17762. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17763. (put 'org-yank 'delete-selection 'yank)
  17764. ;; Make `flyspell-mode' delay after some commands
  17765. (put 'org-self-insert-command 'flyspell-delayed t)
  17766. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17767. (put 'org-delete-char 'flyspell-delayed t)
  17768. (put 'org-delete-backward-char 'flyspell-delayed t)
  17769. ;; Make pabbrev-mode expand after Org mode commands
  17770. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17771. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17772. (defun org-transpose-words ()
  17773. "Transpose words for Org.
  17774. This uses the `org-mode-transpose-word-syntax-table' syntax
  17775. table, which interprets characters in `org-emphasis-alist' as
  17776. word constituents."
  17777. (interactive)
  17778. (with-syntax-table org-mode-transpose-word-syntax-table
  17779. (call-interactively 'transpose-words)))
  17780. (defvar org-ctrl-c-ctrl-c-hook nil
  17781. "Hook for functions attaching themselves to `C-c C-c'.
  17782. This can be used to add additional functionality to the C-c C-c
  17783. key which executes context-dependent commands. This hook is run
  17784. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17785. run after the last test.
  17786. Each function will be called with no arguments. The function
  17787. must check if the context is appropriate for it to act. If yes,
  17788. it should do its thing and then return a non-nil value. If the
  17789. context is wrong, just do nothing and return nil.")
  17790. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17791. "Hook for functions attaching themselves to `C-c C-c'.
  17792. This can be used to add additional functionality to the C-c C-c
  17793. key which executes context-dependent commands. This hook is run
  17794. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17795. before the first test.
  17796. Each function will be called with no arguments. The function
  17797. must check if the context is appropriate for it to act. If yes,
  17798. it should do its thing and then return a non-nil value. If the
  17799. context is wrong, just do nothing and return nil.")
  17800. (defvar org-tab-first-hook nil
  17801. "Hook for functions to attach themselves to TAB.
  17802. See `org-ctrl-c-ctrl-c-hook' for more information.
  17803. This hook runs as the first action when TAB is pressed, even before
  17804. `org-cycle' messes around with the `outline-regexp' to cater for
  17805. inline tasks and plain list item folding.
  17806. If any function in this hook returns t, any other actions that
  17807. would have been caused by TAB (such as table field motion or visibility
  17808. cycling) will not occur.")
  17809. (defvar org-tab-after-check-for-table-hook nil
  17810. "Hook for functions to attach themselves to TAB.
  17811. See `org-ctrl-c-ctrl-c-hook' for more information.
  17812. This hook runs after it has been established that the cursor is not in a
  17813. table, but before checking if the cursor is in a headline or if global cycling
  17814. should be done.
  17815. If any function in this hook returns t, not other actions like visibility
  17816. cycling will be done.")
  17817. (defvar org-tab-after-check-for-cycling-hook nil
  17818. "Hook for functions to attach themselves to TAB.
  17819. See `org-ctrl-c-ctrl-c-hook' for more information.
  17820. This hook runs after it has been established that not table field motion and
  17821. not visibility should be done because of current context. This is probably
  17822. the place where a package like yasnippets can hook in.")
  17823. (defvar org-tab-before-tab-emulation-hook nil
  17824. "Hook for functions to attach themselves to TAB.
  17825. See `org-ctrl-c-ctrl-c-hook' for more information.
  17826. This hook runs after every other options for TAB have been exhausted, but
  17827. before indentation and \t insertion takes place.")
  17828. (defvar org-metaleft-hook nil
  17829. "Hook for functions attaching themselves to `M-left'.
  17830. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17831. (defvar org-metaright-hook nil
  17832. "Hook for functions attaching themselves to `M-right'.
  17833. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17834. (defvar org-metaup-hook nil
  17835. "Hook for functions attaching themselves to `M-up'.
  17836. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17837. (defvar org-metadown-hook nil
  17838. "Hook for functions attaching themselves to `M-down'.
  17839. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17840. (defvar org-shiftmetaleft-hook nil
  17841. "Hook for functions attaching themselves to `M-S-left'.
  17842. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17843. (defvar org-shiftmetaright-hook nil
  17844. "Hook for functions attaching themselves to `M-S-right'.
  17845. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17846. (defvar org-shiftmetaup-hook nil
  17847. "Hook for functions attaching themselves to `M-S-up'.
  17848. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17849. (defvar org-shiftmetadown-hook nil
  17850. "Hook for functions attaching themselves to `M-S-down'.
  17851. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17852. (defvar org-metareturn-hook nil
  17853. "Hook for functions attaching themselves to `M-RET'.
  17854. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17855. (defvar org-shiftup-hook nil
  17856. "Hook for functions attaching themselves to `S-up'.
  17857. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17858. (defvar org-shiftup-final-hook nil
  17859. "Hook for functions attaching themselves to `S-up'.
  17860. This one runs after all other options except shift-select have been excluded.
  17861. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17862. (defvar org-shiftdown-hook nil
  17863. "Hook for functions attaching themselves to `S-down'.
  17864. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17865. (defvar org-shiftdown-final-hook nil
  17866. "Hook for functions attaching themselves to `S-down'.
  17867. This one runs after all other options except shift-select have been excluded.
  17868. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17869. (defvar org-shiftleft-hook nil
  17870. "Hook for functions attaching themselves to `S-left'.
  17871. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17872. (defvar org-shiftleft-final-hook nil
  17873. "Hook for functions attaching themselves to `S-left'.
  17874. This one runs after all other options except shift-select have been excluded.
  17875. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17876. (defvar org-shiftright-hook nil
  17877. "Hook for functions attaching themselves to `S-right'.
  17878. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17879. (defvar org-shiftright-final-hook nil
  17880. "Hook for functions attaching themselves to `S-right'.
  17881. This one runs after all other options except shift-select have been excluded.
  17882. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17883. (defun org-modifier-cursor-error ()
  17884. "Throw an error, a modified cursor command was applied in wrong context."
  17885. (user-error "This command is active in special context like tables, headlines or items"))
  17886. (defun org-shiftselect-error ()
  17887. "Throw an error because Shift-Cursor command was applied in wrong context."
  17888. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17889. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17890. (user-error "This command works only in special context like headlines or timestamps")))
  17891. (defun org-call-for-shift-select (cmd)
  17892. (let ((this-command-keys-shift-translated t))
  17893. (call-interactively cmd)))
  17894. (defun org-shifttab (&optional arg)
  17895. "Global visibility cycling or move to previous table field.
  17896. Call `org-table-previous-field' within a table.
  17897. When ARG is nil, cycle globally through visibility states.
  17898. When ARG is a numeric prefix, show contents of this level."
  17899. (interactive "P")
  17900. (cond
  17901. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17902. ((integerp arg)
  17903. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17904. (message "Content view to level: %d" arg)
  17905. (org-content (prefix-numeric-value arg2))
  17906. (org-cycle-show-empty-lines t)
  17907. (setq org-cycle-global-status 'overview)))
  17908. (t (call-interactively 'org-global-cycle))))
  17909. (defun org-shiftmetaleft ()
  17910. "Promote subtree or delete table column.
  17911. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17912. `org-table-delete-column', depending on context. See the
  17913. individual commands for more information."
  17914. (interactive)
  17915. (cond
  17916. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17917. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17918. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17919. ((if (not (org-region-active-p)) (org-at-item-p)
  17920. (save-excursion (goto-char (region-beginning))
  17921. (org-at-item-p)))
  17922. (call-interactively 'org-outdent-item-tree))
  17923. (t (org-modifier-cursor-error))))
  17924. (defun org-shiftmetaright ()
  17925. "Demote subtree or insert table column.
  17926. Calls `org-demote-subtree', `org-indent-item-tree', or
  17927. `org-table-insert-column', depending on context. See the
  17928. individual commands for more information."
  17929. (interactive)
  17930. (cond
  17931. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17932. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17933. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17934. ((if (not (org-region-active-p)) (org-at-item-p)
  17935. (save-excursion (goto-char (region-beginning))
  17936. (org-at-item-p)))
  17937. (call-interactively 'org-indent-item-tree))
  17938. (t (org-modifier-cursor-error))))
  17939. (defun org-shiftmetaup (&optional _arg)
  17940. "Drag the line at point up.
  17941. In a table, kill the current row.
  17942. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17943. but also adjust the previous clocked item in the clock history.
  17944. Everywhere else, drag the line at point up."
  17945. (interactive "P")
  17946. (cond
  17947. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17948. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17949. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17950. (call-interactively 'org-timestamp-up)))
  17951. (t (call-interactively 'org-drag-line-backward))))
  17952. (defun org-shiftmetadown (&optional _arg)
  17953. "Drag the line at point down.
  17954. In a table, insert an empty row at the current line.
  17955. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17956. but also adjust the previous clocked item in the clock history.
  17957. Everywhere else, drag the line at point down."
  17958. (interactive "P")
  17959. (cond
  17960. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17961. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17962. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17963. (call-interactively 'org-timestamp-down)))
  17964. (t (call-interactively 'org-drag-line-forward))))
  17965. (defsubst org-hidden-tree-error ()
  17966. (user-error
  17967. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17968. (defun org-metaleft (&optional _arg)
  17969. "Promote heading, list item at point or move table column left.
  17970. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17971. depending on context. With no specific context, calls the Emacs
  17972. default `backward-word'. See the individual commands for more
  17973. information.
  17974. This function runs the hook `org-metaleft-hook' as a first step,
  17975. and returns at first non-nil value."
  17976. (interactive "P")
  17977. (cond
  17978. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17979. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  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-promote))
  17988. ;; At an inline task.
  17989. ((org-at-heading-p)
  17990. (call-interactively 'org-inlinetask-promote))
  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-outdent-item))
  17998. (t (call-interactively 'backward-word))))
  17999. (defun org-metaright (&optional _arg)
  18000. "Demote heading, list item at point or move table column right.
  18001. In front of a drawer or a block keyword, indent it correctly.
  18002. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18003. `org-indent-drawer' or `org-indent-block' depending on context.
  18004. With no specific context, calls the Emacs default `forward-word'.
  18005. See the individual commands for more information.
  18006. This function runs the hook `org-metaright-hook' as a first step,
  18007. and returns at first non-nil value."
  18008. (interactive "P")
  18009. (cond
  18010. ((run-hook-with-args-until-success 'org-metaright-hook))
  18011. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18012. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18013. ((org-at-block-p) (call-interactively 'org-indent-block))
  18014. ((org-with-limited-levels
  18015. (or (org-at-heading-p)
  18016. (and (org-region-active-p)
  18017. (save-excursion
  18018. (goto-char (region-beginning))
  18019. (org-at-heading-p)))))
  18020. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18021. (call-interactively 'org-do-demote))
  18022. ;; At an inline task.
  18023. ((org-at-heading-p)
  18024. (call-interactively 'org-inlinetask-demote))
  18025. ((or (org-at-item-p)
  18026. (and (org-region-active-p)
  18027. (save-excursion
  18028. (goto-char (region-beginning))
  18029. (org-at-item-p))))
  18030. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18031. (call-interactively 'org-indent-item))
  18032. (t (call-interactively 'forward-word))))
  18033. (defun org-check-for-hidden (what)
  18034. "Check if there are hidden headlines/items in the current visual line.
  18035. WHAT can be either `headlines' or `items'. If the current line is
  18036. an outline or item heading and it has a folded subtree below it,
  18037. this function returns t, nil otherwise."
  18038. (let ((re (cond
  18039. ((eq what 'headlines) org-outline-regexp-bol)
  18040. ((eq what 'items) (org-item-beginning-re))
  18041. (t (error "This should not happen"))))
  18042. beg end)
  18043. (save-excursion
  18044. (catch 'exit
  18045. (unless (org-region-active-p)
  18046. (setq beg (point-at-bol))
  18047. (beginning-of-line 2)
  18048. (while (and (not (eobp)) ;; this is like `next-line'
  18049. (get-char-property (1- (point)) 'invisible))
  18050. (beginning-of-line 2))
  18051. (setq end (point))
  18052. (goto-char beg)
  18053. (goto-char (point-at-eol))
  18054. (setq end (max end (point)))
  18055. (while (re-search-forward re end t)
  18056. (when (get-char-property (match-beginning 0) 'invisible)
  18057. (throw 'exit t))))
  18058. nil))))
  18059. (defun org-metaup (&optional _arg)
  18060. "Move subtree up or move table row up.
  18061. Calls `org-move-subtree-up' or `org-table-move-row' or
  18062. `org-move-item-up', depending on context. See the individual commands
  18063. for more information."
  18064. (interactive "P")
  18065. (cond
  18066. ((run-hook-with-args-until-success 'org-metaup-hook))
  18067. ((org-region-active-p)
  18068. (let* ((a (min (region-beginning) (region-end)))
  18069. (b (1- (max (region-beginning) (region-end))))
  18070. (c (save-excursion (goto-char a)
  18071. (move-beginning-of-line 0)))
  18072. (d (save-excursion (goto-char a)
  18073. (move-end-of-line 0) (point))))
  18074. (transpose-regions a b c d)
  18075. (goto-char c)))
  18076. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18077. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18078. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18079. (t (org-drag-element-backward))))
  18080. (defun org-metadown (&optional _arg)
  18081. "Move subtree down or move table row down.
  18082. Calls `org-move-subtree-down' or `org-table-move-row' or
  18083. `org-move-item-down', depending on context. See the individual
  18084. commands for more information."
  18085. (interactive "P")
  18086. (cond
  18087. ((run-hook-with-args-until-success 'org-metadown-hook))
  18088. ((org-region-active-p)
  18089. (let* ((a (min (region-beginning) (region-end)))
  18090. (b (max (region-beginning) (region-end)))
  18091. (c (save-excursion (goto-char b)
  18092. (move-beginning-of-line 1)))
  18093. (d (save-excursion (goto-char b)
  18094. (move-end-of-line 1) (1+ (point)))))
  18095. (transpose-regions a b c d)
  18096. (goto-char d)))
  18097. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18098. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18099. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18100. (t (org-drag-element-forward))))
  18101. (defun org-shiftup (&optional arg)
  18102. "Increase item in timestamp or increase priority of current headline.
  18103. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18104. depending on context. See the individual commands for more information."
  18105. (interactive "P")
  18106. (cond
  18107. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18108. ((and org-support-shift-select (org-region-active-p))
  18109. (org-call-for-shift-select 'previous-line))
  18110. ((org-at-timestamp-p 'lax)
  18111. (call-interactively (if org-edit-timestamp-down-means-later
  18112. 'org-timestamp-down 'org-timestamp-up)))
  18113. ((and (not (eq org-support-shift-select 'always))
  18114. org-enable-priority-commands
  18115. (org-at-heading-p))
  18116. (call-interactively 'org-priority-up))
  18117. ((and (not org-support-shift-select) (org-at-item-p))
  18118. (call-interactively 'org-previous-item))
  18119. ((org-clocktable-try-shift 'up arg))
  18120. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18121. (org-support-shift-select
  18122. (org-call-for-shift-select 'previous-line))
  18123. (t (org-shiftselect-error))))
  18124. (defun org-shiftdown (&optional arg)
  18125. "Decrease item in timestamp or decrease priority of current headline.
  18126. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18127. depending on context. See the individual commands for more information."
  18128. (interactive "P")
  18129. (cond
  18130. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18131. ((and org-support-shift-select (org-region-active-p))
  18132. (org-call-for-shift-select 'next-line))
  18133. ((org-at-timestamp-p 'lax)
  18134. (call-interactively (if org-edit-timestamp-down-means-later
  18135. 'org-timestamp-up 'org-timestamp-down)))
  18136. ((and (not (eq org-support-shift-select 'always))
  18137. org-enable-priority-commands
  18138. (org-at-heading-p))
  18139. (call-interactively 'org-priority-down))
  18140. ((and (not org-support-shift-select) (org-at-item-p))
  18141. (call-interactively 'org-next-item))
  18142. ((org-clocktable-try-shift 'down arg))
  18143. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18144. (org-support-shift-select
  18145. (org-call-for-shift-select 'next-line))
  18146. (t (org-shiftselect-error))))
  18147. (defun org-shiftright (&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 future
  18151. - on a headline, switch to the next TODO keyword.
  18152. - on an item, switch entire list to the next bullet type
  18153. - on a property line, switch to the next allowed value
  18154. - on a clocktable definition line, move time block into the future"
  18155. (interactive "P")
  18156. (cond
  18157. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18158. ((and org-support-shift-select (org-region-active-p))
  18159. (org-call-for-shift-select 'forward-char))
  18160. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-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 'right)))
  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 nil))
  18173. ((and (not (eq org-support-shift-select 'always))
  18174. (org-at-property-p))
  18175. (call-interactively 'org-property-next-allowed-value))
  18176. ((org-clocktable-try-shift 'right arg))
  18177. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18178. (org-support-shift-select
  18179. (org-call-for-shift-select 'forward-char))
  18180. (t (org-shiftselect-error))))
  18181. (defun org-shiftleft (&optional arg)
  18182. "Cycle the thing at point or in the current line, depending on context.
  18183. Depending on context, this does one of the following:
  18184. - switch a timestamp at point one day into the past
  18185. - on a headline, switch to the previous TODO keyword.
  18186. - on an item, switch entire list to the previous bullet type
  18187. - on a property line, switch to the previous allowed value
  18188. - on a clocktable definition line, move time block into the past"
  18189. (interactive "P")
  18190. (cond
  18191. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18192. ((and org-support-shift-select (org-region-active-p))
  18193. (org-call-for-shift-select 'backward-char))
  18194. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18195. ((and (not (eq org-support-shift-select 'always))
  18196. (org-at-heading-p))
  18197. (let ((org-inhibit-logging
  18198. (not org-treat-S-cursor-todo-selection-as-state-change))
  18199. (org-inhibit-blocking
  18200. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18201. (org-call-with-arg 'org-todo 'left)))
  18202. ((or (and org-support-shift-select
  18203. (not (eq org-support-shift-select 'always))
  18204. (org-at-item-bullet-p))
  18205. (and (not org-support-shift-select) (org-at-item-p)))
  18206. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18207. ((and (not (eq org-support-shift-select 'always))
  18208. (org-at-property-p))
  18209. (call-interactively 'org-property-previous-allowed-value))
  18210. ((org-clocktable-try-shift 'left arg))
  18211. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18212. (org-support-shift-select
  18213. (org-call-for-shift-select 'backward-char))
  18214. (t (org-shiftselect-error))))
  18215. (defun org-shiftcontrolright ()
  18216. "Switch to next TODO set."
  18217. (interactive)
  18218. (cond
  18219. ((and org-support-shift-select (org-region-active-p))
  18220. (org-call-for-shift-select 'forward-word))
  18221. ((and (not (eq org-support-shift-select 'always))
  18222. (org-at-heading-p))
  18223. (org-call-with-arg 'org-todo 'nextset))
  18224. (org-support-shift-select
  18225. (org-call-for-shift-select 'forward-word))
  18226. (t (org-shiftselect-error))))
  18227. (defun org-shiftcontrolleft ()
  18228. "Switch to previous TODO set."
  18229. (interactive)
  18230. (cond
  18231. ((and org-support-shift-select (org-region-active-p))
  18232. (org-call-for-shift-select 'backward-word))
  18233. ((and (not (eq org-support-shift-select 'always))
  18234. (org-at-heading-p))
  18235. (org-call-with-arg 'org-todo 'previousset))
  18236. (org-support-shift-select
  18237. (org-call-for-shift-select 'backward-word))
  18238. (t (org-shiftselect-error))))
  18239. (defun org-shiftcontrolup (&optional n)
  18240. "Change timestamps synchronously up in CLOCK log lines.
  18241. Optional argument N tells to change by that many units."
  18242. (interactive "P")
  18243. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18244. (let (org-support-shift-select)
  18245. (org-clock-timestamps-up n))
  18246. (user-error "Not at a clock log")))
  18247. (defun org-shiftcontroldown (&optional n)
  18248. "Change timestamps synchronously down in CLOCK log lines.
  18249. Optional argument N tells to change by that many units."
  18250. (interactive "P")
  18251. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18252. (let (org-support-shift-select)
  18253. (org-clock-timestamps-down n))
  18254. (user-error "Not at a clock log")))
  18255. (defun org-increase-number-at-point (&optional inc)
  18256. "Increment the number at point.
  18257. With an optional prefix numeric argument INC, increment using
  18258. this numeric value."
  18259. (interactive "p")
  18260. (if (not (number-at-point))
  18261. (user-error "Not on a number")
  18262. (unless inc (setq inc 1))
  18263. (let ((pos (point))
  18264. (beg (skip-chars-backward "-+^/*0-9eE."))
  18265. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18266. (setq nap (buffer-substring-no-properties
  18267. (+ pos beg) (+ pos beg end)))
  18268. (delete-region (+ pos beg) (+ pos beg end))
  18269. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18270. (when (org-at-table-p)
  18271. (org-table-align)
  18272. (org-table-end-of-field 1))))
  18273. (defun org-decrease-number-at-point (&optional inc)
  18274. "Decrement the number at point.
  18275. With an optional prefix numeric argument INC, decrement using
  18276. this numeric value."
  18277. (interactive "p")
  18278. (org-increase-number-at-point (- (or inc 1))))
  18279. (defun org-ctrl-c-ret ()
  18280. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18281. (interactive)
  18282. (cond
  18283. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18284. (t (call-interactively 'org-insert-heading))))
  18285. (defun org-find-visible ()
  18286. (let ((s (point)))
  18287. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18288. (get-char-property s 'invisible)))
  18289. s))
  18290. (defun org-find-invisible ()
  18291. (let ((s (point)))
  18292. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18293. (not (get-char-property s 'invisible))))
  18294. s))
  18295. (defun org-copy-visible (beg end)
  18296. "Copy the visible parts of the region."
  18297. (interactive "r")
  18298. (let ((result ""))
  18299. (while (/= beg end)
  18300. (when (get-char-property beg 'invisible)
  18301. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18302. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18303. (setq result (concat result (buffer-substring beg next)))
  18304. (setq beg next)))
  18305. (kill-new result)))
  18306. (defun org-copy-special ()
  18307. "Copy region in table or copy current subtree.
  18308. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18309. context. See the individual commands for more information."
  18310. (interactive)
  18311. (call-interactively
  18312. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18313. (defun org-cut-special ()
  18314. "Cut region in table or cut current subtree.
  18315. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18316. context. See the individual commands for more information."
  18317. (interactive)
  18318. (call-interactively
  18319. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18320. (defun org-paste-special (arg)
  18321. "Paste rectangular region into table, or past subtree relative to level.
  18322. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18323. See the individual commands for more information."
  18324. (interactive "P")
  18325. (if (org-at-table-p)
  18326. (org-table-paste-rectangle)
  18327. (org-paste-subtree arg)))
  18328. (defun org-edit-special (&optional arg)
  18329. "Call a special editor for the element at point.
  18330. When at a table, call the formula editor with `org-table-edit-formulas'.
  18331. When in a source code block, call `org-edit-src-code'.
  18332. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18333. When in an export block, call `org-edit-export-block'.
  18334. When in a LaTeX environment, call `org-edit-latex-environment'.
  18335. When at an #+INCLUDE keyword, visit the included file.
  18336. When at a footnote reference, call `org-edit-footnote-reference'
  18337. On a link, call `ffap' to visit the link at point.
  18338. Otherwise, return a user error."
  18339. (interactive "P")
  18340. (let ((element (org-element-at-point)))
  18341. (barf-if-buffer-read-only)
  18342. (pcase (org-element-type element)
  18343. (`src-block
  18344. (if (not arg) (org-edit-src-code)
  18345. (let* ((info (org-babel-get-src-block-info))
  18346. (lang (nth 0 info))
  18347. (params (nth 2 info))
  18348. (session (cdr (assq :session params))))
  18349. (if (not session) (org-edit-src-code)
  18350. ;; At a src-block with a session and function called with
  18351. ;; an ARG: switch to the buffer related to the inferior
  18352. ;; process.
  18353. (switch-to-buffer
  18354. (funcall (intern (concat "org-babel-prep-session:" lang))
  18355. session params))))))
  18356. (`keyword
  18357. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18358. (org-open-link-from-string
  18359. (format "[[%s]]"
  18360. (expand-file-name
  18361. (let ((value (org-element-property :value element)))
  18362. (cond ((org-file-url-p value)
  18363. (user-error "The file is specified as a URL, cannot be edited"))
  18364. ((not (org-string-nw-p value))
  18365. (user-error "No file to edit"))
  18366. ((string-match "\\`\"\\(.*?\\)\"" value)
  18367. (match-string 1 value))
  18368. ((string-match "\\`[^ \t\"]\\S-*" value)
  18369. (match-string 0 value))
  18370. (t (user-error "No valid file specified")))))))
  18371. (user-error "No special environment to edit here")))
  18372. (`table
  18373. (if (eq (org-element-property :type element) 'table.el)
  18374. (org-edit-table.el)
  18375. (call-interactively 'org-table-edit-formulas)))
  18376. ;; Only Org tables contain `table-row' type elements.
  18377. (`table-row (call-interactively 'org-table-edit-formulas))
  18378. (`example-block (org-edit-src-code))
  18379. (`export-block (org-edit-export-block))
  18380. (`fixed-width (org-edit-fixed-width-region))
  18381. (`latex-environment (org-edit-latex-environment))
  18382. (_
  18383. ;; No notable element at point. Though, we may be at a link or
  18384. ;; a footnote reference, which are objects. Thus, scan deeper.
  18385. (let ((context (org-element-context element)))
  18386. (pcase (org-element-type context)
  18387. (`footnote-reference (org-edit-footnote-reference))
  18388. (`inline-src-block (org-edit-inline-src-code))
  18389. (`link (call-interactively #'ffap))
  18390. (_ (user-error "No special environment to edit here"))))))))
  18391. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18392. (defun org-ctrl-c-ctrl-c (&optional arg)
  18393. "Set tags in headline, or update according to changed information at point.
  18394. This command does many different things, depending on context:
  18395. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18396. this is what we do.
  18397. - If the cursor is on a statistics cookie, update it.
  18398. - If the cursor is in a headline, prompt for tags and insert them
  18399. into the current line, aligned to `org-tags-column'. When called
  18400. with prefix arg, realign all tags in the current buffer.
  18401. - If the cursor is in one of the special #+KEYWORD lines, this
  18402. triggers scanning the buffer for these lines and updating the
  18403. information.
  18404. - If the cursor is inside a table, realign the table. This command
  18405. works even if the automatic table editor has been turned off.
  18406. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18407. the entire table.
  18408. - If the cursor is at a footnote reference or definition, jump to
  18409. the corresponding definition or references, respectively.
  18410. - If the cursor is a the beginning of a dynamic block, update it.
  18411. - If the current buffer is a capture buffer, close note and file it.
  18412. - If the cursor is on a <<<target>>>, update radio targets and
  18413. corresponding links in this buffer.
  18414. - If the cursor is on a numbered item in a plain list, renumber the
  18415. ordered list.
  18416. - If the cursor is on a checkbox, toggle it.
  18417. - If the cursor is on a code block, evaluate it. The variable
  18418. `org-confirm-babel-evaluate' can be used to control prompting
  18419. before code block evaluation, by default every code block
  18420. evaluation requires confirmation. Code block evaluation can be
  18421. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18422. (interactive "P")
  18423. (cond
  18424. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18425. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18426. (org-remove-occur-highlights)
  18427. (message "Temporary highlights/overlays removed from current buffer"))
  18428. ((and (local-variable-p 'org-finish-function)
  18429. (fboundp org-finish-function))
  18430. (funcall org-finish-function))
  18431. ((org-babel-hash-at-point))
  18432. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18433. (t
  18434. (let* ((context
  18435. (org-element-lineage
  18436. (org-element-context)
  18437. ;; Limit to supported contexts.
  18438. '(babel-call clock dynamic-block footnote-definition
  18439. footnote-reference inline-babel-call inline-src-block
  18440. inlinetask item keyword node-property paragraph
  18441. plain-list planning property-drawer radio-target
  18442. src-block statistics-cookie table table-cell table-row
  18443. timestamp)
  18444. t))
  18445. (type (org-element-type context)))
  18446. ;; For convenience: at the first line of a paragraph on the same
  18447. ;; line as an item, apply function on that item instead.
  18448. (when (eq type 'paragraph)
  18449. (let ((parent (org-element-property :parent context)))
  18450. (when (and (eq (org-element-type parent) 'item)
  18451. (= (line-beginning-position)
  18452. (org-element-property :begin parent)))
  18453. (setq context parent)
  18454. (setq type 'item))))
  18455. ;; Act according to type of element or object at point.
  18456. ;;
  18457. ;; Do nothing on a blank line, except if it is contained in
  18458. ;; a src block. Hence, we first check if point is in such
  18459. ;; a block and then if it is at a blank line.
  18460. (pcase type
  18461. ((or `inline-src-block `src-block)
  18462. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18463. (org-babel-eval-wipe-error-buffer)
  18464. (org-babel-execute-src-block
  18465. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18466. ((guard (org-match-line "[ \t]*$"))
  18467. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18468. (user-error
  18469. (substitute-command-keys
  18470. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18471. ((or `babel-call `inline-babel-call)
  18472. (let ((info (org-babel-lob-get-info context)))
  18473. (when info (org-babel-execute-src-block nil info))))
  18474. (`clock (org-clock-update-time-maybe))
  18475. (`dynamic-block
  18476. (save-excursion
  18477. (goto-char (org-element-property :post-affiliated context))
  18478. (org-update-dblock)))
  18479. (`footnote-definition
  18480. (goto-char (org-element-property :post-affiliated context))
  18481. (call-interactively 'org-footnote-action))
  18482. (`footnote-reference (call-interactively #'org-footnote-action))
  18483. ((or `headline `inlinetask)
  18484. (save-excursion (goto-char (org-element-property :begin context))
  18485. (call-interactively #'org-set-tags)))
  18486. (`item
  18487. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18488. ;; unconditionally, whereas `C-u' will toggle its presence.
  18489. ;; Without a universal argument, if the item has a checkbox,
  18490. ;; toggle it. Otherwise repair the list.
  18491. (let* ((box (org-element-property :checkbox context))
  18492. (struct (org-element-property :structure context))
  18493. (old-struct (copy-tree struct))
  18494. (parents (org-list-parents-alist struct))
  18495. (prevs (org-list-prevs-alist struct))
  18496. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18497. (org-list-set-checkbox
  18498. (org-element-property :begin context) struct
  18499. (cond ((equal arg '(16)) "[-]")
  18500. ((and (not box) (equal arg '(4))) "[ ]")
  18501. ((or (not box) (equal arg '(4))) nil)
  18502. ((eq box 'on) "[ ]")
  18503. (t "[X]")))
  18504. ;; Mimic `org-list-write-struct' but with grabbing a return
  18505. ;; value from `org-list-struct-fix-box'.
  18506. (org-list-struct-fix-ind struct parents 2)
  18507. (org-list-struct-fix-item-end struct)
  18508. (org-list-struct-fix-bul struct prevs)
  18509. (org-list-struct-fix-ind struct parents)
  18510. (let ((block-item
  18511. (org-list-struct-fix-box struct parents prevs orderedp)))
  18512. (if (and box (equal struct old-struct))
  18513. (if (equal arg '(16))
  18514. (message "Checkboxes already reset")
  18515. (user-error "Cannot toggle this checkbox: %s"
  18516. (if (eq box 'on)
  18517. "all subitems checked"
  18518. "unchecked subitems")))
  18519. (org-list-struct-apply-struct struct old-struct)
  18520. (org-update-checkbox-count-maybe))
  18521. (when block-item
  18522. (message "Checkboxes were removed due to empty box at line %d"
  18523. (org-current-line block-item))))))
  18524. (`keyword
  18525. (let ((org-inhibit-startup-visibility-stuff t)
  18526. (org-startup-align-all-tables nil))
  18527. (when (boundp 'org-table-coordinate-overlays)
  18528. (mapc #'delete-overlay org-table-coordinate-overlays)
  18529. (setq org-table-coordinate-overlays nil))
  18530. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18531. (message "Local setup has been refreshed"))
  18532. (`plain-list
  18533. ;; At a plain list, with a double C-u argument, set
  18534. ;; checkboxes of each item to "[-]", whereas a single one
  18535. ;; will toggle their presence according to the state of the
  18536. ;; first item in the list. Without an argument, repair the
  18537. ;; list.
  18538. (let* ((begin (org-element-property :contents-begin context))
  18539. (struct (org-element-property :structure context))
  18540. (old-struct (copy-tree struct))
  18541. (first-box (save-excursion
  18542. (goto-char begin)
  18543. (looking-at org-list-full-item-re)
  18544. (match-string-no-properties 3)))
  18545. (new-box (cond ((equal arg '(16)) "[-]")
  18546. ((equal arg '(4)) (unless first-box "[ ]"))
  18547. ((equal first-box "[X]") "[ ]")
  18548. (t "[X]"))))
  18549. (cond
  18550. (arg
  18551. (dolist (pos
  18552. (org-list-get-all-items
  18553. begin struct (org-list-prevs-alist struct)))
  18554. (org-list-set-checkbox pos struct new-box)))
  18555. ((and first-box (eq (point) begin))
  18556. ;; For convenience, when point is at bol on the first
  18557. ;; item of the list and no argument is provided, simply
  18558. ;; toggle checkbox of that item, if any.
  18559. (org-list-set-checkbox begin struct new-box)))
  18560. (org-list-write-struct
  18561. struct (org-list-parents-alist struct) old-struct)
  18562. (org-update-checkbox-count-maybe)))
  18563. ((or `property-drawer `node-property)
  18564. (call-interactively #'org-property-action))
  18565. (`radio-target
  18566. (call-interactively #'org-update-radio-target-regexp))
  18567. (`statistics-cookie
  18568. (call-interactively #'org-update-statistics-cookies))
  18569. ((or `table `table-cell `table-row)
  18570. ;; At a table, recalculate every field and align it. Also
  18571. ;; send the table if necessary. If the table has
  18572. ;; a `table.el' type, just give up. At a table row or cell,
  18573. ;; maybe recalculate line but always align table.
  18574. (if (eq (org-element-property :type context) 'table.el)
  18575. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18576. Use `\\[org-edit-special]' to edit table.el tables"))
  18577. (if (or (eq type 'table)
  18578. ;; Check if point is at a TBLFM line.
  18579. (and (eq type 'table-row)
  18580. (= (point) (org-element-property :end context))))
  18581. (save-excursion
  18582. (if (org-at-TBLFM-p)
  18583. (progn (require 'org-table)
  18584. (org-table-calc-current-TBLFM))
  18585. (goto-char (org-element-property :contents-begin context))
  18586. (org-call-with-arg 'org-table-recalculate (or arg t))
  18587. (orgtbl-send-table 'maybe)))
  18588. (org-table-maybe-eval-formula)
  18589. (cond (arg (call-interactively #'org-table-recalculate))
  18590. ((org-table-maybe-recalculate-line))
  18591. (t (org-table-align))))))
  18592. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18593. (org-timestamp-change 0 'day))
  18594. ((and `nil (guard (org-at-heading-p)))
  18595. ;; When point is on an unsupported object type, we can miss
  18596. ;; the fact that it also is at a heading. Handle it here.
  18597. (call-interactively #'org-set-tags))
  18598. ((guard
  18599. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18600. (_
  18601. (user-error
  18602. (substitute-command-keys
  18603. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18604. (defun org-mode-restart ()
  18605. (interactive)
  18606. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18607. (funcall major-mode)
  18608. (hack-local-variables)
  18609. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18610. (org-indent-mode -1))
  18611. (org-reset-file-cache))
  18612. (message "%s restarted" major-mode))
  18613. (defun org-kill-note-or-show-branches ()
  18614. "Abort storing current note, or call `outline-show-branches'."
  18615. (interactive)
  18616. (if (not org-finish-function)
  18617. (save-excursion
  18618. (save-restriction
  18619. (org-narrow-to-subtree)
  18620. (org-flag-subtree t)
  18621. (call-interactively 'outline-show-branches)
  18622. (org-hide-archived-subtrees (point-min) (point-max))))
  18623. (let ((org-note-abort t))
  18624. (funcall org-finish-function))))
  18625. (defun org-delete-indentation (&optional arg)
  18626. "Join current line to previous and fix whitespace at join.
  18627. If previous line is a headline add to headline title. Otherwise
  18628. the function calls `delete-indentation'.
  18629. With a non-nil optional argument, join it to the following one."
  18630. (interactive "*P")
  18631. (if (save-excursion
  18632. (beginning-of-line (if arg 1 0))
  18633. (let ((case-fold-search nil))
  18634. (looking-at org-complex-heading-regexp)))
  18635. ;; At headline.
  18636. (let ((tags-column (when (match-beginning 5)
  18637. (save-excursion (goto-char (match-beginning 5))
  18638. (current-column))))
  18639. (string (concat " " (progn (when arg (forward-line 1))
  18640. (org-trim (delete-and-extract-region
  18641. (line-beginning-position)
  18642. (line-end-position)))))))
  18643. (unless (bobp) (delete-region (point) (1- (point))))
  18644. (goto-char (or (match-end 4)
  18645. (match-beginning 5)
  18646. (match-end 0)))
  18647. (skip-chars-backward " \t")
  18648. (save-excursion (insert string))
  18649. ;; Adjust alignment of tags.
  18650. (cond
  18651. ((not tags-column)) ;no tags
  18652. (org-auto-align-tags (org-set-tags nil t))
  18653. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18654. (delete-indentation arg)))
  18655. (defun org-open-line (n)
  18656. "Insert a new row in tables, call `open-line' elsewhere.
  18657. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18658. As a special case, when a document starts with a table, allow to
  18659. call `open-line' on the very first character."
  18660. (interactive "*p")
  18661. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18662. (org-table-insert-row)
  18663. (open-line n)))
  18664. (defun org-return (&optional indent)
  18665. "Goto next table row or insert a newline.
  18666. Calls `org-table-next-row' or `newline', depending on context.
  18667. When optional INDENT argument is non-nil, call
  18668. `newline-and-indent' instead of `newline'.
  18669. When `org-return-follows-link' is non-nil and point is on
  18670. a timestamp or a link, call `org-open-at-point'. However, it
  18671. will not happen if point is in a table or on a \"dead\"
  18672. object (e.g., within a comment). In these case, you need to use
  18673. `org-open-at-point' directly."
  18674. (interactive)
  18675. (let ((context (if org-return-follows-link (org-element-context)
  18676. (org-element-at-point))))
  18677. (cond
  18678. ;; In a table, call `org-table-next-row'. However, before first
  18679. ;; column or after last one, split the table.
  18680. ((or (and (eq (org-element-type context) 'table)
  18681. (>= (point) (org-element-property :contents-begin context))
  18682. (< (point) (org-element-property :contents-end context)))
  18683. (org-element-lineage context '(table-row table-cell) t))
  18684. (if (or (looking-at-p "[ \t]*$")
  18685. (save-excursion (skip-chars-backward " \t") (bolp)))
  18686. (insert "\n")
  18687. (org-table-justify-field-maybe)
  18688. (call-interactively #'org-table-next-row)))
  18689. ;; On a link or a timestamp, call `org-open-at-point' if
  18690. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18691. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18692. ((and org-return-follows-link
  18693. (or (and (eq 'link (org-element-type context))
  18694. ;; Ensure point is not on the white spaces after
  18695. ;; the link.
  18696. (let ((origin (point)))
  18697. (org-with-point-at (org-element-property :end context)
  18698. (skip-chars-backward " \t")
  18699. (> (point) origin))))
  18700. (org-in-regexp org-ts-regexp-both nil t)
  18701. (org-in-regexp org-tsr-regexp-both nil t)
  18702. (org-in-regexp org-any-link-re nil t)))
  18703. (call-interactively #'org-open-at-point))
  18704. ;; Insert newline in heading, but preserve tags.
  18705. ((and (not (bolp))
  18706. (save-excursion (beginning-of-line)
  18707. (let ((case-fold-search nil))
  18708. (looking-at org-complex-heading-regexp))))
  18709. ;; At headline. Split line. However, if point is on keyword,
  18710. ;; priority cookie or tags, do not break any of them: add
  18711. ;; a newline after the headline instead.
  18712. (let ((tags-column (and (match-beginning 5)
  18713. (save-excursion (goto-char (match-beginning 5))
  18714. (current-column))))
  18715. (string
  18716. (when (and (match-end 4) (org-point-in-group (point) 4))
  18717. (delete-and-extract-region (point) (match-end 4)))))
  18718. ;; Adjust tag alignment.
  18719. (cond
  18720. ((not (and tags-column string)))
  18721. (org-auto-align-tags (org-set-tags nil t))
  18722. (t (org--align-tags-here tags-column))) ;preserve tags column
  18723. (end-of-line)
  18724. (org-show-entry)
  18725. (if indent (newline-and-indent) (newline))
  18726. (when string (save-excursion (insert (org-trim string))))))
  18727. ;; In a list, make sure indenting keeps trailing text within.
  18728. ((and indent
  18729. (not (eolp))
  18730. (org-element-lineage context '(item)))
  18731. (let ((trailing-data
  18732. (delete-and-extract-region (point) (line-end-position))))
  18733. (newline-and-indent)
  18734. (save-excursion (insert trailing-data))))
  18735. (t
  18736. ;; Do not auto-fill when point is in an Org property drawer.
  18737. (let ((auto-fill-function (and (not (org-at-property-p))
  18738. auto-fill-function)))
  18739. (if indent
  18740. (newline-and-indent)
  18741. (newline)))))))
  18742. (defun org-return-indent ()
  18743. "Goto next table row or insert a newline and indent.
  18744. Calls `org-table-next-row' or `newline-and-indent', depending on
  18745. context. See the individual commands for more information."
  18746. (interactive)
  18747. (org-return t))
  18748. (defun org-ctrl-c-tab (&optional _arg)
  18749. "Toggle columns width in a table, or show children.
  18750. Call `org-table-toggle-column-width' if point is in a table.
  18751. Otherwise, call `org-show-children'."
  18752. (interactive "p")
  18753. (call-interactively
  18754. (if (org-at-table-p) #'org-table-toggle-column-width
  18755. #'org-show-children)))
  18756. (defun org-ctrl-c-star ()
  18757. "Compute table, or change heading status of lines.
  18758. Calls `org-table-recalculate' or `org-toggle-heading',
  18759. depending on context."
  18760. (interactive)
  18761. (cond
  18762. ((org-at-table-p)
  18763. (call-interactively 'org-table-recalculate))
  18764. (t
  18765. ;; Convert all lines in region to list items
  18766. (call-interactively 'org-toggle-heading))))
  18767. (defun org-ctrl-c-minus ()
  18768. "Insert separator line in table or modify bullet status of line.
  18769. Also turns a plain line or a region of lines into list items.
  18770. Calls `org-table-insert-hline', `org-toggle-item', or
  18771. `org-cycle-list-bullet', depending on context."
  18772. (interactive)
  18773. (cond
  18774. ((org-at-table-p)
  18775. (call-interactively 'org-table-insert-hline))
  18776. ((org-region-active-p)
  18777. (call-interactively 'org-toggle-item))
  18778. ((org-in-item-p)
  18779. (call-interactively 'org-cycle-list-bullet))
  18780. (t
  18781. (call-interactively 'org-toggle-item))))
  18782. (defun org-toggle-heading (&optional nstars)
  18783. "Convert headings to normal text, or items or text to headings.
  18784. If there is no active region, only convert the current line.
  18785. With a `\\[universal-argument]' prefix, convert the whole list at
  18786. point into heading.
  18787. In a region:
  18788. - If the first non blank line is a headline, remove the stars
  18789. from all headlines in the region.
  18790. - If it is a normal line, turn each and every normal line (i.e.,
  18791. not an heading or an item) in the region into headings. If you
  18792. want to convert only the first line of this region, use one
  18793. universal prefix argument.
  18794. - If it is a plain list item, turn all plain list items into headings.
  18795. When converting a line into a heading, the number of stars is chosen
  18796. such that the lines become children of the current entry. However,
  18797. when a numeric prefix argument is given, its value determines the
  18798. number of stars to add."
  18799. (interactive "P")
  18800. (let ((skip-blanks
  18801. (function
  18802. ;; Return beginning of first non-blank line, starting from
  18803. ;; line at POS.
  18804. (lambda (pos)
  18805. (save-excursion
  18806. (goto-char pos)
  18807. (while (org-at-comment-p) (forward-line))
  18808. (skip-chars-forward " \r\t\n")
  18809. (point-at-bol)))))
  18810. beg end toggled)
  18811. ;; Determine boundaries of changes. If a universal prefix has
  18812. ;; been given, put the list in a region. If region ends at a bol,
  18813. ;; do not consider the last line to be in the region.
  18814. (when (and current-prefix-arg (org-at-item-p))
  18815. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18816. (org-mark-element))
  18817. (if (org-region-active-p)
  18818. (setq beg (funcall skip-blanks (region-beginning))
  18819. end (copy-marker (save-excursion
  18820. (goto-char (region-end))
  18821. (if (bolp) (point) (point-at-eol)))))
  18822. (setq beg (funcall skip-blanks (point-at-bol))
  18823. end (copy-marker (point-at-eol))))
  18824. ;; Ensure inline tasks don't count as headings.
  18825. (org-with-limited-levels
  18826. (save-excursion
  18827. (goto-char beg)
  18828. (cond
  18829. ;; Case 1. Started at an heading: de-star headings.
  18830. ((org-at-heading-p)
  18831. (while (< (point) end)
  18832. (when (org-at-heading-p t)
  18833. (looking-at org-outline-regexp) (replace-match "")
  18834. (setq toggled t))
  18835. (forward-line)))
  18836. ;; Case 2. Started at an item: change items into headlines.
  18837. ;; One star will be added by `org-list-to-subtree'.
  18838. ((org-at-item-p)
  18839. (while (< (point) end)
  18840. (when (org-at-item-p)
  18841. ;; Pay attention to cases when region ends before list.
  18842. (let* ((struct (org-list-struct))
  18843. (list-end
  18844. (min (org-list-get-bottom-point struct) (1+ end))))
  18845. (save-restriction
  18846. (narrow-to-region (point) list-end)
  18847. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18848. (setq toggled t))
  18849. (forward-line)))
  18850. ;; Case 3. Started at normal text: make every line an heading,
  18851. ;; skipping headlines and items.
  18852. (t (let* ((stars
  18853. (make-string
  18854. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18855. (add-stars
  18856. (cond (nstars "") ; stars from prefix only
  18857. ((equal stars "") "*") ; before first heading
  18858. (org-odd-levels-only "**") ; inside heading, odd
  18859. (t "*"))) ; inside heading, oddeven
  18860. (rpl (concat stars add-stars " "))
  18861. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18862. (while (< (point) (if (equal nstars '(4)) lend end))
  18863. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18864. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18865. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18866. (forward-line)))))))
  18867. (unless toggled (message "Cannot toggle heading from here"))))
  18868. (defun org-meta-return (&optional arg)
  18869. "Insert a new heading or wrap a region in a table.
  18870. Calls `org-insert-heading', `org-insert-item' or
  18871. `org-table-wrap-region', depending on context. When called with
  18872. an argument, unconditionally call `org-insert-heading'."
  18873. (interactive "P")
  18874. (org-check-before-invisible-edit 'insert)
  18875. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18876. (call-interactively (cond (arg #'org-insert-heading)
  18877. ((org-at-table-p) #'org-table-wrap-region)
  18878. ((org-in-item-p) #'org-insert-item)
  18879. (t #'org-insert-heading)))))
  18880. ;;; Menu entries
  18881. (defsubst org-in-subtree-not-table-p ()
  18882. "Are we in a subtree and not in a table?"
  18883. (and (not (org-before-first-heading-p))
  18884. (not (org-at-table-p))))
  18885. ;; Define the Org mode menus
  18886. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18887. '("Tbl"
  18888. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18889. ["Next Field" org-cycle (org-at-table-p)]
  18890. ["Previous Field" org-shifttab (org-at-table-p)]
  18891. ["Next Row" org-return (org-at-table-p)]
  18892. "--"
  18893. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18894. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18895. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18896. "--"
  18897. ("Column"
  18898. ["Move Column Left" org-metaleft (org-at-table-p)]
  18899. ["Move Column Right" org-metaright (org-at-table-p)]
  18900. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18901. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18902. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18903. ("Row"
  18904. ["Move Row Up" org-metaup (org-at-table-p)]
  18905. ["Move Row Down" org-metadown (org-at-table-p)]
  18906. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18907. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18908. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18909. "--"
  18910. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18911. ("Rectangle"
  18912. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18913. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18914. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18915. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18916. "--"
  18917. ("Calculate"
  18918. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18919. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18920. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18921. "--"
  18922. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18923. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18924. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18925. "--"
  18926. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18927. "--"
  18928. ["Sum Column/Rectangle" org-table-sum
  18929. (or (org-at-table-p) (org-region-active-p))]
  18930. ["Which Column?" org-table-current-column (org-at-table-p)])
  18931. ["Debug Formulas"
  18932. org-table-toggle-formula-debugger
  18933. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18934. ["Show Col/Row Numbers"
  18935. org-table-toggle-coordinate-overlays
  18936. :style toggle
  18937. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18938. "--"
  18939. ["Create" org-table-create (not (org-at-table-p))]
  18940. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18941. ["Import from File" org-table-import (not (org-at-table-p))]
  18942. ["Export to File" org-table-export (org-at-table-p)]
  18943. "--"
  18944. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18945. "--"
  18946. ("Plot"
  18947. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18948. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18949. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18950. '("Org"
  18951. ("Show/Hide"
  18952. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18953. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18954. ["Sparse Tree..." org-sparse-tree t]
  18955. ["Reveal Context" org-reveal t]
  18956. ["Show All" org-show-all t]
  18957. "--"
  18958. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18959. "--"
  18960. ["New Heading" org-insert-heading t]
  18961. ("Navigate Headings"
  18962. ["Up" outline-up-heading t]
  18963. ["Next" outline-next-visible-heading t]
  18964. ["Previous" outline-previous-visible-heading t]
  18965. ["Next Same Level" outline-forward-same-level t]
  18966. ["Previous Same Level" outline-backward-same-level t]
  18967. "--"
  18968. ["Jump" org-goto t])
  18969. ("Edit Structure"
  18970. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18971. "--"
  18972. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18973. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18974. "--"
  18975. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18976. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18977. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18978. "--"
  18979. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18980. "--"
  18981. ["Copy visible text" org-copy-visible t]
  18982. "--"
  18983. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18984. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18985. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18986. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18987. "--"
  18988. ["Sort Region/Children" org-sort t]
  18989. "--"
  18990. ["Convert to odd levels" org-convert-to-odd-levels t]
  18991. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18992. ("Editing"
  18993. ["Emphasis..." org-emphasize t]
  18994. ["Edit Source Example" org-edit-special t]
  18995. "--"
  18996. ["Footnote new/jump" org-footnote-action t]
  18997. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18998. ("Archive"
  18999. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19000. "--"
  19001. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19002. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19003. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19004. )
  19005. "--"
  19006. ("Hyperlinks"
  19007. ["Store Link (Global)" org-store-link t]
  19008. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19009. ["Insert Link" org-insert-link t]
  19010. ["Follow Link" org-open-at-point t]
  19011. "--"
  19012. ["Next link" org-next-link t]
  19013. ["Previous link" org-previous-link t]
  19014. "--"
  19015. ["Descriptive Links"
  19016. org-toggle-link-display
  19017. :style radio
  19018. :selected org-descriptive-links
  19019. ]
  19020. ["Literal Links"
  19021. org-toggle-link-display
  19022. :style radio
  19023. :selected (not org-descriptive-links)])
  19024. "--"
  19025. ("TODO Lists"
  19026. ["TODO/DONE/-" org-todo t]
  19027. ("Select keyword"
  19028. ["Next keyword" org-shiftright (org-at-heading-p)]
  19029. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19030. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19031. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19032. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19033. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19034. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19035. "--"
  19036. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19037. :selected org-enforce-todo-dependencies :style toggle :active t]
  19038. "Settings for tree at point"
  19039. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19040. :selected (org-entry-get nil "ORDERED")
  19041. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19042. ["Do Children parallel" org-toggle-ordered-property :style radio
  19043. :selected (not (org-entry-get nil "ORDERED"))
  19044. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19045. "--"
  19046. ["Set Priority" org-priority t]
  19047. ["Priority Up" org-shiftup t]
  19048. ["Priority Down" org-shiftdown t]
  19049. "--"
  19050. ["Get news from all feeds" org-feed-update-all t]
  19051. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19052. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19053. ("TAGS and Properties"
  19054. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19055. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19056. "--"
  19057. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19058. ["Column view of properties" org-columns t]
  19059. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19060. ("Dates and Scheduling"
  19061. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19062. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19063. ("Change Date"
  19064. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19065. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19066. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19067. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19068. ["Compute Time Range" org-evaluate-time-range t]
  19069. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19070. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19071. "--"
  19072. ["Custom time format" org-toggle-time-stamp-overlays
  19073. :style radio :selected org-display-custom-times]
  19074. "--"
  19075. ["Goto Calendar" org-goto-calendar t]
  19076. ["Date from Calendar" org-date-from-calendar t]
  19077. "--"
  19078. ["Start/Restart Timer" org-timer-start t]
  19079. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19080. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19081. ["Insert Timer String" org-timer t]
  19082. ["Insert Timer Item" org-timer-item t])
  19083. ("Logging work"
  19084. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19085. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19086. ["Clock out" org-clock-out t]
  19087. ["Clock cancel" org-clock-cancel t]
  19088. "--"
  19089. ["Mark as default task" org-clock-mark-default-task t]
  19090. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19091. ["Goto running clock" org-clock-goto t]
  19092. "--"
  19093. ["Display times" org-clock-display t]
  19094. ["Create clock table" org-clock-report t]
  19095. "--"
  19096. ["Record DONE time"
  19097. (progn (setq org-log-done (not org-log-done))
  19098. (message "Switching to %s will %s record a timestamp"
  19099. (car org-done-keywords)
  19100. (if org-log-done "automatically" "not")))
  19101. :style toggle :selected org-log-done])
  19102. "--"
  19103. ["Agenda Command..." org-agenda t]
  19104. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19105. ("File List for Agenda")
  19106. ("Special views current file"
  19107. ["TODO Tree" org-show-todo-tree t]
  19108. ["Check Deadlines" org-check-deadlines t]
  19109. ["Tags/Property tree" org-match-sparse-tree t])
  19110. "--"
  19111. ["Export/Publish..." org-export-dispatch t]
  19112. ("LaTeX"
  19113. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19114. :style toggle :selected org-cdlatex-mode]
  19115. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19116. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19117. ["Modify math symbol" org-cdlatex-math-modify
  19118. (org-inside-LaTeX-fragment-p)]
  19119. ["Insert citation" org-reftex-citation t])
  19120. "--"
  19121. ("MobileOrg"
  19122. ["Push Files and Views" org-mobile-push t]
  19123. ["Get Captured and Flagged" org-mobile-pull t]
  19124. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19125. "--"
  19126. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19127. "--"
  19128. ("Documentation"
  19129. ["Show Version" org-version t]
  19130. ["Info Documentation" org-info t])
  19131. ("Customize"
  19132. ["Browse Org Group" org-customize t]
  19133. "--"
  19134. ["Expand This Menu" org-create-customize-menu
  19135. (fboundp 'customize-menu-create)])
  19136. ["Send bug report" org-submit-bug-report t]
  19137. "--"
  19138. ("Refresh/Reload"
  19139. ["Refresh setup current buffer" org-mode-restart t]
  19140. ["Reload Org (after update)" org-reload t]
  19141. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19142. ))
  19143. (defun org-info (&optional node)
  19144. "Read documentation for Org in the info system.
  19145. With optional NODE, go directly to that node."
  19146. (interactive)
  19147. (info (format "(org)%s" (or node ""))))
  19148. ;;;###autoload
  19149. (defun org-submit-bug-report ()
  19150. "Submit a bug report on Org via mail.
  19151. Don't hesitate to report any problems or inaccurate documentation.
  19152. If you don't have setup sending mail from (X)Emacs, please copy the
  19153. output buffer into your mail program, as it gives us important
  19154. information about your Org version and configuration."
  19155. (interactive)
  19156. (require 'reporter)
  19157. (defvar reporter-prompt-for-summary-p)
  19158. (org-load-modules-maybe)
  19159. (org-require-autoloaded-modules)
  19160. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19161. (reporter-submit-bug-report
  19162. "emacs-orgmode@gnu.org"
  19163. (org-version nil 'full)
  19164. (let (list)
  19165. (save-window-excursion
  19166. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19167. (delete-other-windows)
  19168. (erase-buffer)
  19169. (insert "You are about to submit a bug report to the Org mailing list.
  19170. We would like to add your full Org and Outline configuration to the
  19171. bug report. This greatly simplifies the work of the maintainer and
  19172. other experts on the mailing list.
  19173. HOWEVER, some variables you have customized may contain private
  19174. information. The names of customers, colleagues, or friends, might
  19175. appear in the form of file names, tags, todo states, or search strings.
  19176. If you answer yes to the prompt, you might want to check and remove
  19177. such private information before sending the email.")
  19178. (add-text-properties (point-min) (point-max) '(face org-warning))
  19179. (when (yes-or-no-p "Include your Org configuration ")
  19180. (mapatoms
  19181. (lambda (v)
  19182. (and (boundp v)
  19183. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19184. (or (and (symbol-value v)
  19185. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19186. (and
  19187. (get v 'custom-type) (get v 'standard-value)
  19188. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19189. (push v list)))))
  19190. (kill-buffer (get-buffer "*Warn about privacy*"))
  19191. list))
  19192. nil nil
  19193. "Remember to cover the basics, that is, what you expected to happen and
  19194. what in fact did happen. You don't know how to make a good report? See
  19195. https://orgmode.org/manual/Feedback.html#Feedback
  19196. Your bug report will be posted to the Org mailing list.
  19197. ------------------------------------------------------------------------")
  19198. (save-excursion
  19199. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19200. (replace-match "\\1Bug: \\3 [\\2]")))))
  19201. (defun org-install-agenda-files-menu ()
  19202. (let ((bl (buffer-list)))
  19203. (save-excursion
  19204. (while bl
  19205. (set-buffer (pop bl))
  19206. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19207. (when (derived-mode-p 'org-mode)
  19208. (easy-menu-change
  19209. '("Org") "File List for Agenda"
  19210. (append
  19211. (list
  19212. ["Edit File List" (org-edit-agenda-file-list) t]
  19213. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19214. ["Remove Current File from List" org-remove-file t]
  19215. ["Cycle through agenda files" org-cycle-agenda-files t]
  19216. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19217. "--")
  19218. (mapcar 'org-file-menu-entry
  19219. ;; Prevent initialization from failing.
  19220. (ignore-errors (org-agenda-files t)))))))))
  19221. ;;;; Documentation
  19222. (defun org-require-autoloaded-modules ()
  19223. (interactive)
  19224. (mapc #'require
  19225. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19226. org-table org-timer)))
  19227. ;;;###autoload
  19228. (defun org-reload (&optional uncompiled)
  19229. "Reload all Org Lisp files.
  19230. With prefix arg UNCOMPILED, load the uncompiled versions."
  19231. (interactive "P")
  19232. (require 'loadhist)
  19233. (let* ((org-dir (org-find-library-dir "org"))
  19234. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19235. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19236. (remove-re (format "\\`%s\\'"
  19237. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19238. (feats (delete-dups
  19239. (mapcar 'file-name-sans-extension
  19240. (mapcar 'file-name-nondirectory
  19241. (delq nil
  19242. (mapcar 'feature-file
  19243. features))))))
  19244. (lfeat (append
  19245. (sort
  19246. (setq feats
  19247. (delq nil (mapcar
  19248. (lambda (f)
  19249. (if (and (string-match feature-re f)
  19250. (not (string-match remove-re f)))
  19251. f nil))
  19252. feats)))
  19253. 'string-lessp)
  19254. (list "org-version" "org")))
  19255. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19256. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19257. load-uncore load-misses)
  19258. (setq load-misses
  19259. (delq 't
  19260. (mapcar (lambda (f)
  19261. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19262. (and (string= org-dir contrib-dir)
  19263. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19264. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19265. (add-to-list 'load-uncore f 'append)
  19266. 't)
  19267. f))
  19268. lfeat)))
  19269. (when load-uncore
  19270. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19271. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19272. (if load-misses
  19273. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19274. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19275. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19276. ;;;###autoload
  19277. (defun org-customize ()
  19278. "Call the customize function with org as argument."
  19279. (interactive)
  19280. (org-load-modules-maybe)
  19281. (org-require-autoloaded-modules)
  19282. (customize-browse 'org))
  19283. (defun org-create-customize-menu ()
  19284. "Create a full customization menu for Org mode, insert it into the menu."
  19285. (interactive)
  19286. (org-load-modules-maybe)
  19287. (org-require-autoloaded-modules)
  19288. (if (fboundp 'customize-menu-create)
  19289. (progn
  19290. (easy-menu-change
  19291. '("Org") "Customize"
  19292. `(["Browse Org group" org-customize t]
  19293. "--"
  19294. ,(customize-menu-create 'org)
  19295. ["Set" Custom-set t]
  19296. ["Save" Custom-save t]
  19297. ["Reset to Current" Custom-reset-current t]
  19298. ["Reset to Saved" Custom-reset-saved t]
  19299. ["Reset to Standard Settings" Custom-reset-standard t]))
  19300. (message "\"Org\"-menu now contains full customization menu"))
  19301. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19302. ;;;; Miscellaneous stuff
  19303. ;;; Generally useful functions
  19304. (defun org-link-display-format (s)
  19305. "Replace links in string S with their description.
  19306. If there is no description, use the link target."
  19307. (save-match-data
  19308. (replace-regexp-in-string
  19309. org-bracket-link-analytic-regexp
  19310. (lambda (m)
  19311. (if (match-end 5) (match-string 5 m)
  19312. (concat (match-string 1 m) (match-string 3 m))))
  19313. s nil t)))
  19314. (defun org-toggle-link-display ()
  19315. "Toggle the literal or descriptive display of links."
  19316. (interactive)
  19317. (if org-descriptive-links
  19318. (progn (org-remove-from-invisibility-spec '(org-link))
  19319. (org-restart-font-lock)
  19320. (setq org-descriptive-links nil))
  19321. (progn (add-to-invisibility-spec '(org-link))
  19322. (org-restart-font-lock)
  19323. (setq org-descriptive-links t))))
  19324. (defun org-in-clocktable-p ()
  19325. "Check if the cursor is in a clocktable."
  19326. (let ((pos (point)) start)
  19327. (save-excursion
  19328. (end-of-line 1)
  19329. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19330. (setq start (match-beginning 0))
  19331. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19332. (>= (match-end 0) pos)
  19333. start))))
  19334. (defun org-in-verbatim-emphasis ()
  19335. (save-match-data
  19336. (and (org-in-regexp org-verbatim-re 2)
  19337. (>= (point) (match-beginning 3))
  19338. (<= (point) (match-end 4)))))
  19339. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19340. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19341. (if (and marker (marker-buffer marker)
  19342. (buffer-live-p (marker-buffer marker)))
  19343. (progn
  19344. (pop-to-buffer-same-window (marker-buffer marker))
  19345. (when (or (> marker (point-max)) (< marker (point-min)))
  19346. (widen))
  19347. (goto-char marker)
  19348. (org-show-context 'org-goto))
  19349. (if bookmark
  19350. (bookmark-jump bookmark)
  19351. (error "Cannot find location"))))
  19352. (defun org-quote-csv-field (s)
  19353. "Quote field for inclusion in CSV material."
  19354. (if (string-match "[\",]" s)
  19355. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19356. s))
  19357. (defun org-force-self-insert (N)
  19358. "Needed to enforce self-insert under remapping."
  19359. (interactive "p")
  19360. (self-insert-command N))
  19361. (defun org-fill-template (template alist)
  19362. "Find each %key of ALIST in TEMPLATE and replace it."
  19363. (let ((case-fold-search nil))
  19364. (dolist (entry (sort (copy-sequence alist)
  19365. (lambda (a b) (< (length (car a)) (length (car b))))))
  19366. (setq template
  19367. (replace-regexp-in-string
  19368. (concat "%" (regexp-quote (car entry)))
  19369. (or (cdr entry) "") template t t)))
  19370. template))
  19371. (defun org-quote-vert (s)
  19372. "Replace \"|\" with \"\\vert\"."
  19373. (while (string-match "|" s)
  19374. (setq s (replace-match "\\vert" t t s)))
  19375. s)
  19376. (defun org-uuidgen-p (s)
  19377. "Is S an ID created by UUIDGEN?"
  19378. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19379. (defun org-in-src-block-p (&optional inside)
  19380. "Whether point is in a code source block.
  19381. When INSIDE is non-nil, don't consider we are within a src block
  19382. when point is at #+BEGIN_SRC or #+END_SRC."
  19383. (let ((case-fold-search t))
  19384. (or (and (eq (get-char-property (point) 'src-block) t))
  19385. (and (not inside)
  19386. (save-match-data
  19387. (save-excursion
  19388. (beginning-of-line)
  19389. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19390. (defun org-context ()
  19391. "Return a list of contexts of the current cursor position.
  19392. If several contexts apply, all are returned.
  19393. Each context entry is a list with a symbol naming the context, and
  19394. two positions indicating start and end of the context. Possible
  19395. contexts are:
  19396. :headline anywhere in a headline
  19397. :headline-stars on the leading stars in a headline
  19398. :todo-keyword on a TODO keyword (including DONE) in a headline
  19399. :tags on the TAGS in a headline
  19400. :priority on the priority cookie in a headline
  19401. :item on the first line of a plain list item
  19402. :item-bullet on the bullet/number of a plain list item
  19403. :checkbox on the checkbox in a plain list item
  19404. :table in an Org table
  19405. :table-special on a special filed in a table
  19406. :table-table in a table.el table
  19407. :clocktable in a clocktable
  19408. :src-block in a source block
  19409. :link on a hyperlink
  19410. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19411. :target on a <<target>>
  19412. :radio-target on a <<<radio-target>>>
  19413. :latex-fragment on a LaTeX fragment
  19414. :latex-preview on a LaTeX fragment with overlaid preview image
  19415. This function expects the position to be visible because it uses font-lock
  19416. faces as a help to recognize the following contexts: :table-special, :link,
  19417. and :keyword."
  19418. (let* ((f (get-text-property (point) 'face))
  19419. (faces (if (listp f) f (list f)))
  19420. (case-fold-search t)
  19421. (p (point)) clist o)
  19422. ;; First the large context
  19423. (cond
  19424. ((org-at-heading-p t)
  19425. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19426. (when (progn
  19427. (beginning-of-line 1)
  19428. (looking-at org-todo-line-tags-regexp))
  19429. (push (org-point-in-group p 1 :headline-stars) clist)
  19430. (push (org-point-in-group p 2 :todo-keyword) clist)
  19431. (push (org-point-in-group p 4 :tags) clist))
  19432. (goto-char p)
  19433. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19434. (when (looking-at "\\[#[A-Z0-9]\\]")
  19435. (push (org-point-in-group p 0 :priority) clist)))
  19436. ((org-at-item-p)
  19437. (push (org-point-in-group p 2 :item-bullet) clist)
  19438. (push (list :item (point-at-bol)
  19439. (save-excursion (org-end-of-item) (point)))
  19440. clist)
  19441. (and (org-at-item-checkbox-p)
  19442. (push (org-point-in-group p 0 :checkbox) clist)))
  19443. ((org-at-table-p)
  19444. (push (list :table (org-table-begin) (org-table-end)) clist)
  19445. (when (memq 'org-formula faces)
  19446. (push (list :table-special
  19447. (previous-single-property-change p 'face)
  19448. (next-single-property-change p 'face)) clist)))
  19449. ((org-at-table-p 'any)
  19450. (push (list :table-table) clist)))
  19451. (goto-char p)
  19452. (let ((case-fold-search t))
  19453. ;; New the "medium" contexts: clocktables, source blocks
  19454. (cond ((org-in-clocktable-p)
  19455. (push (list :clocktable
  19456. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19457. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19458. (match-beginning 1))
  19459. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19460. (match-end 0))) clist))
  19461. ((org-in-src-block-p)
  19462. (push (list :src-block
  19463. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19464. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19465. (match-beginning 1))
  19466. (and (search-forward "#+END_SRC" nil t)
  19467. (match-beginning 0))) clist))))
  19468. (goto-char p)
  19469. ;; Now the small context
  19470. (cond
  19471. ((org-at-timestamp-p)
  19472. (push (org-point-in-group p 0 :timestamp) clist))
  19473. ((memq 'org-link faces)
  19474. (push (list :link
  19475. (previous-single-property-change p 'face)
  19476. (next-single-property-change p 'face)) clist))
  19477. ((memq 'org-special-keyword faces)
  19478. (push (list :keyword
  19479. (previous-single-property-change p 'face)
  19480. (next-single-property-change p 'face)) clist))
  19481. ((org-at-target-p)
  19482. (push (org-point-in-group p 0 :target) clist)
  19483. (goto-char (1- (match-beginning 0)))
  19484. (when (looking-at org-radio-target-regexp)
  19485. (push (org-point-in-group p 0 :radio-target) clist))
  19486. (goto-char p))
  19487. ((setq o (cl-some
  19488. (lambda (o)
  19489. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19490. o))
  19491. (overlays-at (point))))
  19492. (push (list :latex-fragment
  19493. (overlay-start o) (overlay-end o)) clist)
  19494. (push (list :latex-preview
  19495. (overlay-start o) (overlay-end o)) clist))
  19496. ((org-inside-LaTeX-fragment-p)
  19497. ;; FIXME: positions wrong.
  19498. (push (list :latex-fragment (point) (point)) clist)))
  19499. (setq clist (nreverse (delq nil clist)))
  19500. clist))
  19501. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19502. "Non-nil when point is between matches of START-RE and END-RE.
  19503. Also return a non-nil value when point is on one of the matches.
  19504. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19505. buffer positions. Default values are the positions of headlines
  19506. surrounding the point.
  19507. The functions returns a cons cell whose car (resp. cdr) is the
  19508. position before START-RE (resp. after END-RE)."
  19509. (save-match-data
  19510. (let ((pos (point))
  19511. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19512. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19513. beg end)
  19514. (save-excursion
  19515. ;; Point is on a block when on START-RE or if START-RE can be
  19516. ;; found before it...
  19517. (and (or (org-in-regexp start-re)
  19518. (re-search-backward start-re limit-up t))
  19519. (setq beg (match-beginning 0))
  19520. ;; ... and END-RE after it...
  19521. (goto-char (match-end 0))
  19522. (re-search-forward end-re limit-down t)
  19523. (> (setq end (match-end 0)) pos)
  19524. ;; ... without another START-RE in-between.
  19525. (goto-char (match-beginning 0))
  19526. (not (re-search-backward start-re (1+ beg) t))
  19527. ;; Return value.
  19528. (cons beg end))))))
  19529. (defun org-in-block-p (names)
  19530. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19531. NAMES is a list of strings containing names of blocks.
  19532. Return first block name matched, or nil. Beware that in case of
  19533. nested blocks, the returned name may not belong to the closest
  19534. block from point."
  19535. (save-match-data
  19536. (catch 'exit
  19537. (let ((case-fold-search t)
  19538. (lim-up (save-excursion (outline-previous-heading)))
  19539. (lim-down (save-excursion (outline-next-heading))))
  19540. (dolist (name names)
  19541. (let ((n (regexp-quote name)))
  19542. (when (org-between-regexps-p
  19543. (concat "^[ \t]*#\\+begin_" n)
  19544. (concat "^[ \t]*#\\+end_" n)
  19545. lim-up lim-down)
  19546. (throw 'exit n)))))
  19547. nil)))
  19548. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19549. "Call `multi-occur' with buffers for all agenda files."
  19550. (interactive "sOrg-files matching: ")
  19551. (let* ((files (org-agenda-files))
  19552. (tnames (mapcar #'file-truename files))
  19553. (extra org-agenda-text-search-extra-files))
  19554. (when (eq (car extra) 'agenda-archives)
  19555. (setq extra (cdr extra))
  19556. (setq files (org-add-archive-files files)))
  19557. (dolist (f extra)
  19558. (unless (member (file-truename f) tnames)
  19559. (unless (member f files) (setq files (append files (list f))))
  19560. (setq tnames (append tnames (list (file-truename f))))))
  19561. (multi-occur
  19562. (mapcar (lambda (x)
  19563. (with-current-buffer
  19564. ;; FIXME: Why not just (find-file-noselect x)?
  19565. ;; Is it to avoid the "revert buffer" prompt?
  19566. (or (get-file-buffer x) (find-file-noselect x))
  19567. (widen)
  19568. (current-buffer)))
  19569. files)
  19570. regexp)))
  19571. (add-hook 'occur-mode-find-occurrence-hook
  19572. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19573. (defun org-occur-link-in-agenda-files ()
  19574. "Create a link and search for it in the agendas.
  19575. The link is not stored in `org-stored-links', it is just created
  19576. for the search purpose."
  19577. (interactive)
  19578. (let ((link (condition-case nil
  19579. (org-store-link nil)
  19580. (error "Unable to create a link to here"))))
  19581. (org-occur-in-agenda-files (regexp-quote link))))
  19582. (defun org-back-over-empty-lines ()
  19583. "Move backwards over whitespace, to the beginning of the first empty line.
  19584. Returns the number of empty lines passed."
  19585. (let ((pos (point)))
  19586. (if (cdr (assq 'heading org-blank-before-new-entry))
  19587. (skip-chars-backward " \t\n\r")
  19588. (unless (eobp)
  19589. (forward-line -1)))
  19590. (beginning-of-line 2)
  19591. (goto-char (min (point) pos))
  19592. (count-lines (point) pos)))
  19593. (defun org-switch-to-buffer-other-window (&rest args)
  19594. "Switch to buffer in a second window on the current frame.
  19595. In particular, do not allow pop-up frames.
  19596. Returns the newly created buffer."
  19597. (org-no-popups
  19598. (apply 'switch-to-buffer-other-window args)))
  19599. (defun org-replace-escapes (string table)
  19600. "Replace %-escapes in STRING with values in TABLE.
  19601. TABLE is an association list with keys like \"%a\" and string values.
  19602. The sequences in STRING may contain normal field width and padding information,
  19603. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19604. so values can contain further %-escapes if they are define later in TABLE."
  19605. (let ((tbl (copy-alist table))
  19606. (case-fold-search nil)
  19607. (pchg 0)
  19608. re rpl)
  19609. (dolist (e tbl)
  19610. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19611. (when (and (cdr e) (string-match re (cdr e)))
  19612. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19613. (safe "SREF"))
  19614. (add-text-properties 0 3 (list 'sref sref) safe)
  19615. (setcdr e (replace-match safe t t (cdr e)))))
  19616. (while (string-match re string)
  19617. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19618. (cdr e)))
  19619. (setq string (replace-match rpl t t string))))
  19620. (while (setq pchg (next-property-change pchg string))
  19621. (let ((sref (get-text-property pchg 'sref string)))
  19622. (when (and sref (string-match "SREF" string pchg))
  19623. (setq string (replace-match sref t t string)))))
  19624. string))
  19625. ;;; TODO: Only called once, from ox-odt which should probably use
  19626. ;;; org-export-inline-image-p or something.
  19627. (defun org-file-image-p (file)
  19628. "Return non-nil if FILE is an image."
  19629. (save-match-data
  19630. (string-match (image-file-name-regexp) file)))
  19631. (defun org-get-cursor-date (&optional with-time)
  19632. "Return the date at cursor in as a time.
  19633. This works in the calendar and in the agenda, anywhere else it just
  19634. returns the current time.
  19635. If WITH-TIME is non-nil, returns the time of the event at point (in
  19636. the agenda) or the current time of the day."
  19637. (let (date day defd tp hod mod)
  19638. (when with-time
  19639. (setq tp (get-text-property (point) 'time))
  19640. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19641. (setq hod (string-to-number (match-string 1 tp))
  19642. mod (string-to-number (match-string 2 tp))))
  19643. (or tp (let ((now (decode-time)))
  19644. (setq hod (nth 2 now)
  19645. mod (nth 1 now)))))
  19646. (cond
  19647. ((eq major-mode 'calendar-mode)
  19648. (setq date (calendar-cursor-to-date)
  19649. defd (encode-time 0 (or mod 0) (or hod 0)
  19650. (nth 1 date) (nth 0 date) (nth 2 date))))
  19651. ((eq major-mode 'org-agenda-mode)
  19652. (setq day (get-text-property (point) 'day))
  19653. (when day
  19654. (setq date (calendar-gregorian-from-absolute day)
  19655. defd (encode-time 0 (or mod 0) (or hod 0)
  19656. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19657. (or defd (current-time))))
  19658. (defun org-mark-subtree (&optional up)
  19659. "Mark the current subtree.
  19660. This puts point at the start of the current subtree, and mark at
  19661. the end. If a numeric prefix UP is given, move up into the
  19662. hierarchy of headlines by UP levels before marking the subtree."
  19663. (interactive "P")
  19664. (org-with-limited-levels
  19665. (cond ((org-at-heading-p) (beginning-of-line))
  19666. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19667. (t (outline-previous-visible-heading 1))))
  19668. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19669. (if (called-interactively-p 'any)
  19670. (call-interactively 'org-mark-element)
  19671. (org-mark-element)))
  19672. ;;; Indentation
  19673. (defvar org-element-greater-elements)
  19674. (defun org--get-expected-indentation (element contentsp)
  19675. "Expected indentation column for current line, according to ELEMENT.
  19676. ELEMENT is an element containing point. CONTENTSP is non-nil
  19677. when indentation is to be computed according to contents of
  19678. ELEMENT."
  19679. (let ((type (org-element-type element))
  19680. (start (org-element-property :begin element))
  19681. (post-affiliated (org-element-property :post-affiliated element)))
  19682. (org-with-wide-buffer
  19683. (cond
  19684. (contentsp
  19685. (cl-case type
  19686. ((diary-sexp footnote-definition) 0)
  19687. ((headline inlinetask nil)
  19688. (if (not org-adapt-indentation) 0
  19689. (let ((level (org-current-level)))
  19690. (if level (1+ level) 0))))
  19691. ((item plain-list) (org-list-item-body-column post-affiliated))
  19692. (t
  19693. (goto-char start)
  19694. (org-get-indentation))))
  19695. ((memq type '(headline inlinetask nil))
  19696. (if (org-match-line "[ \t]*$")
  19697. (org--get-expected-indentation element t)
  19698. 0))
  19699. ((memq type '(diary-sexp footnote-definition)) 0)
  19700. ;; First paragraph of a footnote definition or an item.
  19701. ;; Indent like parent.
  19702. ((< (line-beginning-position) start)
  19703. (org--get-expected-indentation
  19704. (org-element-property :parent element) t))
  19705. ;; At first line: indent according to previous sibling, if any,
  19706. ;; ignoring footnote definitions and inline tasks, or parent's
  19707. ;; contents.
  19708. ((= (line-beginning-position) start)
  19709. (catch 'exit
  19710. (while t
  19711. (if (= (point-min) start) (throw 'exit 0)
  19712. (goto-char (1- start))
  19713. (let* ((previous (org-element-at-point))
  19714. (parent previous))
  19715. (while (and parent (<= (org-element-property :end parent) start))
  19716. (setq previous parent
  19717. parent (org-element-property :parent parent)))
  19718. (cond
  19719. ((not previous) (throw 'exit 0))
  19720. ((> (org-element-property :end previous) start)
  19721. (throw 'exit (org--get-expected-indentation previous t)))
  19722. ((memq (org-element-type previous)
  19723. '(footnote-definition inlinetask))
  19724. (setq start (org-element-property :begin previous)))
  19725. (t (goto-char (org-element-property :begin previous))
  19726. (throw 'exit
  19727. (if (bolp) (org-get-indentation)
  19728. ;; At first paragraph in an item or
  19729. ;; a footnote definition.
  19730. (org--get-expected-indentation
  19731. (org-element-property :parent previous) t))))))))))
  19732. ;; Otherwise, move to the first non-blank line above.
  19733. (t
  19734. (beginning-of-line)
  19735. (let ((pos (point)))
  19736. (skip-chars-backward " \r\t\n")
  19737. (cond
  19738. ;; Two blank lines end a footnote definition or a plain
  19739. ;; list. When we indent an empty line after them, the
  19740. ;; containing list or footnote definition is over, so it
  19741. ;; qualifies as a previous sibling. Therefore, we indent
  19742. ;; like its first line.
  19743. ((and (memq type '(footnote-definition plain-list))
  19744. (> (count-lines (point) pos) 2))
  19745. (goto-char start)
  19746. (org-get-indentation))
  19747. ;; Line above is the first one of a paragraph at the
  19748. ;; beginning of an item or a footnote definition. Indent
  19749. ;; like parent.
  19750. ((< (line-beginning-position) start)
  19751. (org--get-expected-indentation
  19752. (org-element-property :parent element) t))
  19753. ;; Line above is the beginning of an element, i.e., point
  19754. ;; was originally on the blank lines between element's start
  19755. ;; and contents.
  19756. ((= (line-beginning-position) post-affiliated)
  19757. (org--get-expected-indentation element t))
  19758. ;; POS is after contents in a greater element. Indent like
  19759. ;; the beginning of the element.
  19760. ((and (memq type org-element-greater-elements)
  19761. (let ((cend (org-element-property :contents-end element)))
  19762. (and cend (<= cend pos))))
  19763. ;; As a special case, if point is at the end of a footnote
  19764. ;; definition or an item, indent like the very last element
  19765. ;; within. If that last element is an item, indent like
  19766. ;; its contents.
  19767. (if (memq type '(footnote-definition item plain-list))
  19768. (let ((last (org-element-at-point)))
  19769. (goto-char pos)
  19770. (org--get-expected-indentation
  19771. last (eq (org-element-type last) 'item)))
  19772. (goto-char start)
  19773. (org-get-indentation)))
  19774. ;; In any other case, indent like the current line.
  19775. (t (org-get-indentation)))))))))
  19776. (defun org--align-node-property ()
  19777. "Align node property at point.
  19778. Alignment is done according to `org-property-format', which see."
  19779. (when (save-excursion
  19780. (beginning-of-line)
  19781. (looking-at org-property-re))
  19782. (replace-match
  19783. (concat (match-string 4)
  19784. (org-trim
  19785. (format org-property-format (match-string 1) (match-string 3))))
  19786. t t)))
  19787. (defun org-indent-line ()
  19788. "Indent line depending on context.
  19789. Indentation is done according to the following rules:
  19790. - Footnote definitions, diary sexps, headlines and inline tasks
  19791. have to start at column 0.
  19792. - On the very first line of an element, consider, in order, the
  19793. next rules until one matches:
  19794. 1. If there's a sibling element before, ignoring footnote
  19795. definitions and inline tasks, indent like its first line.
  19796. 2. If element has a parent, indent like its contents. More
  19797. precisely, if parent is an item, indent after the
  19798. description part, if any, or the bullet (see
  19799. `org-list-description-max-indent'). Else, indent like
  19800. parent's first line.
  19801. 3. Otherwise, indent relatively to current level, if
  19802. `org-adapt-indentation' is non-nil, or to left margin.
  19803. - On a blank line at the end of an element, indent according to
  19804. the type of the element. More precisely
  19805. 1. If element is a plain list, an item, or a footnote
  19806. definition, indent like the very last element within.
  19807. 2. If element is a paragraph, indent like its last non blank
  19808. line.
  19809. 3. Otherwise, indent like its very first line.
  19810. - In the code part of a source block, use language major mode
  19811. to indent current line if `org-src-tab-acts-natively' is
  19812. non-nil. If it is nil, do nothing.
  19813. - Otherwise, indent like the first non-blank line above.
  19814. The function doesn't indent an item as it could break the whole
  19815. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19816. `\\[org-shiftmetaright]'.
  19817. Also align node properties according to `org-property-format'."
  19818. (interactive)
  19819. (cond
  19820. ((org-at-heading-p) 'noindent)
  19821. (t
  19822. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19823. (type (org-element-type element)))
  19824. (cond ((and (memq type '(plain-list item))
  19825. (= (line-beginning-position)
  19826. (org-element-property :post-affiliated element)))
  19827. 'noindent)
  19828. ((and (eq type 'latex-environment)
  19829. (>= (point) (org-element-property :post-affiliated element))
  19830. (< (point) (org-with-wide-buffer
  19831. (goto-char (org-element-property :end element))
  19832. (skip-chars-backward " \r\t\n")
  19833. (line-beginning-position 2))))
  19834. 'noindent)
  19835. ((and (eq type 'src-block)
  19836. org-src-tab-acts-natively
  19837. (> (line-beginning-position)
  19838. (org-element-property :post-affiliated element))
  19839. (< (line-beginning-position)
  19840. (org-with-wide-buffer
  19841. (goto-char (org-element-property :end element))
  19842. (skip-chars-backward " \r\t\n")
  19843. (line-beginning-position))))
  19844. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19845. (t
  19846. (let ((column (org--get-expected-indentation element nil)))
  19847. ;; Preserve current column.
  19848. (if (<= (current-column) (current-indentation))
  19849. (indent-line-to column)
  19850. (save-excursion (indent-line-to column))))
  19851. ;; Align node property. Also preserve current column.
  19852. (when (eq type 'node-property)
  19853. (let ((column (current-column)))
  19854. (org--align-node-property)
  19855. (org-move-to-column column)))))))))
  19856. (defun org-indent-region (start end)
  19857. "Indent each non-blank line in the region.
  19858. Called from a program, START and END specify the region to
  19859. indent. The function will not indent contents of example blocks,
  19860. verse blocks and export blocks as leading white spaces are
  19861. assumed to be significant there."
  19862. (interactive "r")
  19863. (save-excursion
  19864. (goto-char start)
  19865. (skip-chars-forward " \r\t\n")
  19866. (unless (eobp) (beginning-of-line))
  19867. (let ((indent-to
  19868. (lambda (ind pos)
  19869. ;; Set IND as indentation for all lines between point and
  19870. ;; POS. Blank lines are ignored. Leave point after POS
  19871. ;; once done.
  19872. (let ((limit (copy-marker pos)))
  19873. (while (< (point) limit)
  19874. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19875. (forward-line))
  19876. (set-marker limit nil))))
  19877. (end (copy-marker end)))
  19878. (while (< (point) end)
  19879. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19880. (let* ((element (org-element-at-point))
  19881. (type (org-element-type element))
  19882. (element-end (copy-marker (org-element-property :end element)))
  19883. (ind (org--get-expected-indentation element nil)))
  19884. (cond
  19885. ;; Element indented as a single block. Example blocks
  19886. ;; preserving indentation are a special case since the
  19887. ;; "contents" must not be indented whereas the block
  19888. ;; boundaries can.
  19889. ((or (memq type '(export-block latex-environment))
  19890. (and (eq type 'example-block)
  19891. (not
  19892. (or org-src-preserve-indentation
  19893. (org-element-property :preserve-indent element)))))
  19894. (let ((offset (- ind (org-get-indentation))))
  19895. (unless (zerop offset)
  19896. (indent-rigidly (org-element-property :begin element)
  19897. (org-element-property :end element)
  19898. offset)))
  19899. (goto-char element-end))
  19900. ;; Elements indented line wise. Be sure to exclude
  19901. ;; example blocks (preserving indentation) and source
  19902. ;; blocks from this category as they are treated
  19903. ;; specially later.
  19904. ((or (memq type '(paragraph table table-row))
  19905. (not (or (org-element-property :contents-begin element)
  19906. (memq type '(example-block src-block)))))
  19907. (when (eq type 'node-property)
  19908. (org--align-node-property)
  19909. (beginning-of-line))
  19910. (funcall indent-to ind (min element-end end)))
  19911. ;; Elements consisting of three parts: before the
  19912. ;; contents, the contents, and after the contents. The
  19913. ;; contents are treated specially, according to the
  19914. ;; element type, or not indented at all. Other parts are
  19915. ;; indented as a single block.
  19916. (t
  19917. (let* ((post (copy-marker
  19918. (org-element-property :post-affiliated element)))
  19919. (cbeg
  19920. (copy-marker
  19921. (cond
  19922. ((not (org-element-property :contents-begin element))
  19923. ;; Fake contents for source blocks.
  19924. (org-with-wide-buffer
  19925. (goto-char post)
  19926. (line-beginning-position 2)))
  19927. ((memq type '(footnote-definition item plain-list))
  19928. ;; Contents in these elements could start on
  19929. ;; the same line as the beginning of the
  19930. ;; element. Make sure we start indenting
  19931. ;; from the second line.
  19932. (org-with-wide-buffer
  19933. (goto-char post)
  19934. (end-of-line)
  19935. (skip-chars-forward " \r\t\n")
  19936. (if (eobp) (point) (line-beginning-position))))
  19937. (t (org-element-property :contents-begin element)))))
  19938. (cend (copy-marker
  19939. (or (org-element-property :contents-end element)
  19940. ;; Fake contents for source blocks.
  19941. (org-with-wide-buffer
  19942. (goto-char element-end)
  19943. (skip-chars-backward " \r\t\n")
  19944. (line-beginning-position)))
  19945. t)))
  19946. ;; Do not change items indentation individually as it
  19947. ;; might break the list as a whole. On the other
  19948. ;; hand, when at a plain list, indent it as a whole.
  19949. (cond ((eq type 'plain-list)
  19950. (let ((offset (- ind (org-get-indentation))))
  19951. (unless (zerop offset)
  19952. (indent-rigidly (org-element-property :begin element)
  19953. (org-element-property :end element)
  19954. offset))
  19955. (goto-char cbeg)))
  19956. ((eq type 'item) (goto-char cbeg))
  19957. (t (funcall indent-to ind (min cbeg end))))
  19958. (when (< (point) end)
  19959. (cl-case type
  19960. ((example-block verse-block))
  19961. (src-block
  19962. ;; In a source block, indent source code
  19963. ;; according to language major mode, but only if
  19964. ;; `org-src-tab-acts-natively' is non-nil.
  19965. (when (and (< (point) end) org-src-tab-acts-natively)
  19966. (ignore-errors
  19967. (org-babel-do-in-edit-buffer
  19968. (indent-region (point-min) (point-max))))))
  19969. (t (org-indent-region (point) (min cend end))))
  19970. (goto-char (min cend end))
  19971. (when (< (point) end)
  19972. (funcall indent-to ind (min element-end end))))
  19973. (set-marker post nil)
  19974. (set-marker cbeg nil)
  19975. (set-marker cend nil))))
  19976. (set-marker element-end nil))))
  19977. (set-marker end nil))))
  19978. (defun org-indent-drawer ()
  19979. "Indent the drawer at point."
  19980. (interactive)
  19981. (unless (save-excursion
  19982. (beginning-of-line)
  19983. (looking-at-p org-drawer-regexp))
  19984. (user-error "Not at a drawer"))
  19985. (let ((element (org-element-at-point)))
  19986. (unless (memq (org-element-type element) '(drawer property-drawer))
  19987. (user-error "Not at a drawer"))
  19988. (org-with-wide-buffer
  19989. (org-indent-region (org-element-property :begin element)
  19990. (org-element-property :end element))))
  19991. (message "Drawer at point indented"))
  19992. (defun org-indent-block ()
  19993. "Indent the block at point."
  19994. (interactive)
  19995. (unless (save-excursion
  19996. (beginning-of-line)
  19997. (let ((case-fold-search t))
  19998. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19999. (user-error "Not at a block"))
  20000. (let ((element (org-element-at-point)))
  20001. (unless (memq (org-element-type element)
  20002. '(comment-block center-block dynamic-block example-block
  20003. export-block quote-block special-block
  20004. src-block verse-block))
  20005. (user-error "Not at a block"))
  20006. (org-with-wide-buffer
  20007. (org-indent-region (org-element-property :begin element)
  20008. (org-element-property :end element))))
  20009. (message "Block at point indented"))
  20010. ;;; Filling
  20011. ;; We use our own fill-paragraph and auto-fill functions.
  20012. ;; `org-fill-paragraph' relies on adaptive filling and context
  20013. ;; checking. Appropriate `fill-prefix' is computed with
  20014. ;; `org-adaptive-fill-function'.
  20015. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20016. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20017. ;; `org-adaptive-fill-function' value. Internally,
  20018. ;; `org-comment-line-break-function' breaks the line.
  20019. ;; `org-setup-filling' installs filling and auto-filling related
  20020. ;; variables during `org-mode' initialization.
  20021. (defun org-setup-filling ()
  20022. (require 'org-element)
  20023. ;; Prevent auto-fill from inserting unwanted new items.
  20024. (when (boundp 'fill-nobreak-predicate)
  20025. (setq-local
  20026. fill-nobreak-predicate
  20027. (org-uniquify
  20028. (append fill-nobreak-predicate
  20029. '(org-fill-line-break-nobreak-p
  20030. org-fill-n-macro-as-item-nobreak-p
  20031. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20032. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20033. (setq-local paragraph-start paragraph-ending)
  20034. (setq-local paragraph-separate paragraph-ending))
  20035. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20036. (setq-local auto-fill-inhibit-regexp nil)
  20037. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20038. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20039. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20040. (defun org-fill-line-break-nobreak-p ()
  20041. "Non-nil when a new line at point would create an Org line break."
  20042. (save-excursion
  20043. (skip-chars-backward "[ \t]")
  20044. (skip-chars-backward "\\\\")
  20045. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20046. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20047. "Non-nil when a new line at point would split a timestamp."
  20048. (and (org-at-timestamp-p 'lax)
  20049. (not (looking-at org-ts-regexp-both))))
  20050. (defun org-fill-n-macro-as-item-nobreak-p ()
  20051. "Non-nil when a new line at point would create a new list."
  20052. ;; During export, a "n" macro followed by a dot or a closing
  20053. ;; parenthesis can end up being parsed as a new list item.
  20054. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20055. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20056. (defun org-adaptive-fill-function ()
  20057. "Compute a fill prefix for the current line.
  20058. Return fill prefix, as a string, or nil if current line isn't
  20059. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20060. matches in paragraphs or comments, use it."
  20061. (org-with-wide-buffer
  20062. (unless (org-at-heading-p)
  20063. (let* ((p (line-beginning-position))
  20064. (element (save-excursion
  20065. (beginning-of-line)
  20066. (org-element-at-point)))
  20067. (type (org-element-type element))
  20068. (post-affiliated (org-element-property :post-affiliated element)))
  20069. (unless (< p post-affiliated)
  20070. (cl-case type
  20071. (comment
  20072. (save-excursion
  20073. (beginning-of-line)
  20074. (looking-at "[ \t]*")
  20075. (concat (match-string 0) "# ")))
  20076. (footnote-definition "")
  20077. ((item plain-list)
  20078. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20079. (paragraph
  20080. ;; Fill prefix is usually the same as the current line,
  20081. ;; unless the paragraph is at the beginning of an item.
  20082. (let ((parent (org-element-property :parent element)))
  20083. (save-excursion
  20084. (beginning-of-line)
  20085. (cond ((eq (org-element-type parent) 'item)
  20086. (make-string (org-list-item-body-column
  20087. (org-element-property :begin parent))
  20088. ?\s))
  20089. ((and adaptive-fill-regexp
  20090. ;; Locally disable
  20091. ;; `adaptive-fill-function' to let
  20092. ;; `fill-context-prefix' handle
  20093. ;; `adaptive-fill-regexp' variable.
  20094. (let (adaptive-fill-function)
  20095. (fill-context-prefix
  20096. post-affiliated
  20097. (org-element-property :end element)))))
  20098. ((looking-at "[ \t]+") (match-string 0))
  20099. (t "")))))
  20100. (comment-block
  20101. ;; Only fill contents if P is within block boundaries.
  20102. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20103. (forward-line)
  20104. (point)))
  20105. (cend (save-excursion
  20106. (goto-char (org-element-property :end element))
  20107. (skip-chars-backward " \r\t\n")
  20108. (line-beginning-position))))
  20109. (when (and (>= p cbeg) (< p cend))
  20110. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20111. (match-string 0)
  20112. ""))))))))))
  20113. (defun org-fill-element (&optional justify)
  20114. "Fill element at point, when applicable.
  20115. This function only applies to comment blocks, comments, example
  20116. blocks and paragraphs. Also, as a special case, re-align table
  20117. when point is at one.
  20118. If JUSTIFY is non-nil (interactively, with prefix argument),
  20119. justify as well. If `sentence-end-double-space' is non-nil, then
  20120. period followed by one space does not end a sentence, so don't
  20121. break a line there. The variable `fill-column' controls the
  20122. width for filling.
  20123. For convenience, when point is at a plain list, an item or
  20124. a footnote definition, try to fill the first paragraph within."
  20125. (with-syntax-table org-mode-transpose-word-syntax-table
  20126. ;; Move to end of line in order to get the first paragraph within
  20127. ;; a plain list or a footnote definition.
  20128. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20129. ;; First check if point is in a blank line at the beginning of
  20130. ;; the buffer. In that case, ignore filling.
  20131. (cl-case (org-element-type element)
  20132. ;; Use major mode filling function is src blocks.
  20133. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20134. ;; Align Org tables, leave table.el tables as-is.
  20135. (table-row (org-table-align) t)
  20136. (table
  20137. (when (eq (org-element-property :type element) 'org)
  20138. (save-excursion
  20139. (goto-char (org-element-property :post-affiliated element))
  20140. (org-table-align)))
  20141. t)
  20142. (paragraph
  20143. ;; Paragraphs may contain `line-break' type objects.
  20144. (let ((beg (max (point-min)
  20145. (org-element-property :contents-begin element)))
  20146. (end (min (point-max)
  20147. (org-element-property :contents-end element))))
  20148. ;; Do nothing if point is at an affiliated keyword.
  20149. (if (< (line-end-position) beg) t
  20150. ;; Fill paragraph, taking line breaks into account.
  20151. (save-excursion
  20152. (goto-char beg)
  20153. (let ((cuts (list beg)))
  20154. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20155. (when (eq 'line-break
  20156. (org-element-type
  20157. (save-excursion (backward-char)
  20158. (org-element-context))))
  20159. (push (point) cuts)))
  20160. (dolist (c (delq end cuts))
  20161. (fill-region-as-paragraph c end justify)
  20162. (setq end c))))
  20163. t)))
  20164. ;; Contents of `comment-block' type elements should be
  20165. ;; filled as plain text, but only if point is within block
  20166. ;; markers.
  20167. (comment-block
  20168. (let* ((case-fold-search t)
  20169. (beg (save-excursion
  20170. (goto-char (org-element-property :begin element))
  20171. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20172. (forward-line)
  20173. (point)))
  20174. (end (save-excursion
  20175. (goto-char (org-element-property :end element))
  20176. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20177. (line-beginning-position))))
  20178. (if (or (< (point) beg) (> (point) end)) t
  20179. (fill-region-as-paragraph
  20180. (save-excursion (end-of-line)
  20181. (re-search-backward "^[ \t]*$" beg 'move)
  20182. (line-beginning-position))
  20183. (save-excursion (beginning-of-line)
  20184. (re-search-forward "^[ \t]*$" end 'move)
  20185. (line-beginning-position))
  20186. justify))))
  20187. ;; Fill comments.
  20188. (comment
  20189. (let ((begin (org-element-property :post-affiliated element))
  20190. (end (org-element-property :end element)))
  20191. (when (and (>= (point) begin) (<= (point) end))
  20192. (let ((begin (save-excursion
  20193. (end-of-line)
  20194. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20195. (progn (forward-line) (point))
  20196. begin)))
  20197. (end (save-excursion
  20198. (end-of-line)
  20199. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20200. (1- (line-beginning-position))
  20201. (skip-chars-backward " \r\t\n")
  20202. (line-end-position)))))
  20203. ;; Do not fill comments when at a blank line.
  20204. (when (> end begin)
  20205. (let ((fill-prefix
  20206. (save-excursion
  20207. (beginning-of-line)
  20208. (looking-at "[ \t]*#")
  20209. (let ((comment-prefix (match-string 0)))
  20210. (goto-char (match-end 0))
  20211. (if (looking-at adaptive-fill-regexp)
  20212. (concat comment-prefix (match-string 0))
  20213. (concat comment-prefix " "))))))
  20214. (save-excursion
  20215. (fill-region-as-paragraph begin end justify))))))
  20216. t))
  20217. ;; Ignore every other element.
  20218. (otherwise t)))))
  20219. (defun org-fill-paragraph (&optional justify region)
  20220. "Fill element at point, when applicable.
  20221. This function only applies to comment blocks, comments, example
  20222. blocks and paragraphs. Also, as a special case, re-align table
  20223. when point is at one.
  20224. For convenience, when point is at a plain list, an item or
  20225. a footnote definition, try to fill the first paragraph within.
  20226. If JUSTIFY is non-nil (interactively, with prefix argument),
  20227. justify as well. If `sentence-end-double-space' is non-nil, then
  20228. period followed by one space does not end a sentence, so don't
  20229. break a line there. The variable `fill-column' controls the
  20230. width for filling.
  20231. The REGION argument is non-nil if called interactively; in that
  20232. case, if Transient Mark mode is enabled and the mark is active,
  20233. fill each of the elements in the active region, instead of just
  20234. filling the current element."
  20235. (interactive (progn
  20236. (barf-if-buffer-read-only)
  20237. (list (if current-prefix-arg 'full) t)))
  20238. (cond
  20239. ((and region transient-mark-mode mark-active
  20240. (not (eq (region-beginning) (region-end))))
  20241. (let ((origin (point-marker))
  20242. (start (region-beginning)))
  20243. (unwind-protect
  20244. (progn
  20245. (goto-char (region-end))
  20246. (while (> (point) start)
  20247. (org-backward-paragraph)
  20248. (org-fill-element justify)))
  20249. (goto-char origin)
  20250. (set-marker origin nil))))
  20251. (t (org-fill-element justify))))
  20252. (defun org-auto-fill-function ()
  20253. "Auto-fill function."
  20254. ;; Check if auto-filling is meaningful.
  20255. (let ((fc (current-fill-column)))
  20256. (when (and fc (> (current-column) fc))
  20257. (let* ((fill-prefix (org-adaptive-fill-function))
  20258. ;; Enforce empty fill prefix, if required. Otherwise, it
  20259. ;; will be computed again.
  20260. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20261. (when fill-prefix (do-auto-fill))))))
  20262. (defun org-comment-line-break-function (&optional soft)
  20263. "Break line at point and indent, continuing comment if within one.
  20264. The inserted newline is marked hard if variable
  20265. `use-hard-newlines' is true, unless optional argument SOFT is
  20266. non-nil."
  20267. (if soft (insert-and-inherit ?\n) (newline 1))
  20268. (save-excursion (forward-char -1) (delete-horizontal-space))
  20269. (delete-horizontal-space)
  20270. (indent-to-left-margin)
  20271. (insert-before-markers-and-inherit fill-prefix))
  20272. ;;; Fixed Width Areas
  20273. (defun org-toggle-fixed-width ()
  20274. "Toggle fixed-width markup.
  20275. Add or remove fixed-width markup on current line, whenever it
  20276. makes sense. Return an error otherwise.
  20277. If a region is active and if it contains only fixed-width areas
  20278. or blank lines, remove all fixed-width markup in it. If the
  20279. region contains anything else, convert all non-fixed-width lines
  20280. to fixed-width ones.
  20281. Blank lines at the end of the region are ignored unless the
  20282. region only contains such lines."
  20283. (interactive)
  20284. (if (not (org-region-active-p))
  20285. ;; No region:
  20286. ;;
  20287. ;; Remove fixed width marker only in a fixed-with element.
  20288. ;;
  20289. ;; Add fixed width maker in paragraphs, in blank lines after
  20290. ;; elements or at the beginning of a headline or an inlinetask,
  20291. ;; and before any one-line elements (e.g., a clock).
  20292. (progn
  20293. (beginning-of-line)
  20294. (let* ((element (org-element-at-point))
  20295. (type (org-element-type element)))
  20296. (cond
  20297. ((and (eq type 'fixed-width)
  20298. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20299. (replace-match
  20300. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20301. ((and (memq type '(babel-call clock comment diary-sexp headline
  20302. horizontal-rule keyword paragraph
  20303. planning))
  20304. (<= (org-element-property :post-affiliated element) (point)))
  20305. (skip-chars-forward " \t")
  20306. (insert ": "))
  20307. ((and (looking-at-p "[ \t]*$")
  20308. (or (eq type 'inlinetask)
  20309. (save-excursion
  20310. (skip-chars-forward " \r\t\n")
  20311. (<= (org-element-property :end element) (point)))))
  20312. (delete-region (point) (line-end-position))
  20313. (org-indent-line)
  20314. (insert ": "))
  20315. (t (user-error "Cannot insert a fixed-width line here")))))
  20316. ;; Region active.
  20317. (let* ((begin (save-excursion
  20318. (goto-char (region-beginning))
  20319. (line-beginning-position)))
  20320. (end (copy-marker
  20321. (save-excursion
  20322. (goto-char (region-end))
  20323. (unless (eolp) (beginning-of-line))
  20324. (if (save-excursion (re-search-backward "\\S-" begin t))
  20325. (progn (skip-chars-backward " \r\t\n") (point))
  20326. (point)))))
  20327. (all-fixed-width-p
  20328. (catch 'not-all-p
  20329. (save-excursion
  20330. (goto-char begin)
  20331. (skip-chars-forward " \r\t\n")
  20332. (when (eobp) (throw 'not-all-p nil))
  20333. (while (< (point) end)
  20334. (let ((element (org-element-at-point)))
  20335. (if (eq (org-element-type element) 'fixed-width)
  20336. (goto-char (org-element-property :end element))
  20337. (throw 'not-all-p nil))))
  20338. t))))
  20339. (if all-fixed-width-p
  20340. (save-excursion
  20341. (goto-char begin)
  20342. (while (< (point) end)
  20343. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20344. (replace-match
  20345. "" nil nil nil
  20346. (if (= (line-end-position) (match-end 0)) 0 1)))
  20347. (forward-line)))
  20348. (let ((min-ind (point-max)))
  20349. ;; Find minimum indentation across all lines.
  20350. (save-excursion
  20351. (goto-char begin)
  20352. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20353. (setq min-ind 0)
  20354. (catch 'zerop
  20355. (while (< (point) end)
  20356. (unless (looking-at-p "[ \t]*$")
  20357. (let ((ind (org-get-indentation)))
  20358. (setq min-ind (min min-ind ind))
  20359. (when (zerop ind) (throw 'zerop t))))
  20360. (forward-line)))))
  20361. ;; Loop over all lines and add fixed-width markup everywhere
  20362. ;; but in fixed-width lines.
  20363. (save-excursion
  20364. (goto-char begin)
  20365. (while (< (point) end)
  20366. (cond
  20367. ((org-at-heading-p)
  20368. (insert ": ")
  20369. (forward-line)
  20370. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20371. (insert ":")
  20372. (forward-line)))
  20373. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20374. (let* ((element (org-element-at-point))
  20375. (element-end (org-element-property :end element)))
  20376. (if (eq (org-element-type element) 'fixed-width)
  20377. (progn (goto-char element-end)
  20378. (skip-chars-backward " \r\t\n")
  20379. (forward-line))
  20380. (let ((limit (min end element-end)))
  20381. (while (< (point) limit)
  20382. (org-move-to-column min-ind t)
  20383. (insert ": ")
  20384. (forward-line))))))
  20385. (t
  20386. (org-move-to-column min-ind t)
  20387. (insert ": ")
  20388. (forward-line)))))))
  20389. (set-marker end nil))))
  20390. ;;; Blocks
  20391. (defun org-block-map (function &optional start end)
  20392. "Call FUNCTION at the head of all source blocks in the current buffer.
  20393. Optional arguments START and END can be used to limit the range."
  20394. (let ((start (or start (point-min)))
  20395. (end (or end (point-max))))
  20396. (save-excursion
  20397. (goto-char start)
  20398. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20399. (save-excursion
  20400. (save-match-data
  20401. (goto-char (match-beginning 0))
  20402. (funcall function)))))))
  20403. (defun org-next-block (arg &optional backward block-regexp)
  20404. "Jump to the next block.
  20405. With a prefix argument ARG, jump forward ARG many blocks.
  20406. When BACKWARD is non-nil, jump to the previous block.
  20407. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20408. Match data is set according to this regexp when the function
  20409. returns.
  20410. Return point at beginning of the opening line of found block.
  20411. Throw an error if no block is found."
  20412. (interactive "p")
  20413. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20414. (case-fold-search t)
  20415. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20416. (count (or arg 1))
  20417. (origin (point))
  20418. last-element)
  20419. (if backward (beginning-of-line) (end-of-line))
  20420. (while (and (> count 0) (funcall search-fn re nil t))
  20421. (let ((element (save-excursion
  20422. (goto-char (match-beginning 0))
  20423. (save-match-data (org-element-at-point)))))
  20424. (when (and (memq (org-element-type element)
  20425. '(center-block comment-block dynamic-block
  20426. example-block export-block quote-block
  20427. special-block src-block verse-block))
  20428. (<= (match-beginning 0)
  20429. (org-element-property :post-affiliated element)))
  20430. (setq last-element element)
  20431. (cl-decf count))))
  20432. (if (= count 0)
  20433. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20434. (save-match-data (org-show-context)))
  20435. (goto-char origin)
  20436. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20437. (defun org-previous-block (arg &optional block-regexp)
  20438. "Jump to the previous block.
  20439. With a prefix argument ARG, jump backward ARG many source blocks.
  20440. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20441. (interactive "p")
  20442. (org-next-block arg t block-regexp))
  20443. ;;; Comments
  20444. ;; Org comments syntax is quite complex. It requires the entire line
  20445. ;; to be just a comment. Also, even with the right syntax at the
  20446. ;; beginning of line, some elements (e.g., verse-block or
  20447. ;; example-block) don't accept comments. Usual Emacs comment commands
  20448. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20449. ;; Org still relies on `comment-dwim', but cannot trust
  20450. ;; `comment-only-p'. So, `comment-region-function' and
  20451. ;; `uncomment-region-function' both point
  20452. ;; to`org-comment-or-uncomment-region'. Eventually,
  20453. ;; `org-insert-comment' takes care of insertion of comments at the
  20454. ;; beginning of line.
  20455. ;; `org-setup-comments-handling' install comments related variables
  20456. ;; during `org-mode' initialization.
  20457. (defun org-setup-comments-handling ()
  20458. (interactive)
  20459. (setq-local comment-use-syntax nil)
  20460. (setq-local comment-start "# ")
  20461. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20462. (setq-local comment-insert-comment-function 'org-insert-comment)
  20463. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20464. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20465. (defun org-insert-comment ()
  20466. "Insert an empty comment above current line.
  20467. If the line is empty, insert comment at its beginning. When
  20468. point is within a source block, comment according to the related
  20469. major mode."
  20470. (if (let ((element (org-element-at-point)))
  20471. (and (eq (org-element-type element) 'src-block)
  20472. (< (save-excursion
  20473. (goto-char (org-element-property :post-affiliated element))
  20474. (line-end-position))
  20475. (point))
  20476. (> (save-excursion
  20477. (goto-char (org-element-property :end element))
  20478. (skip-chars-backward " \r\t\n")
  20479. (line-beginning-position))
  20480. (point))))
  20481. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20482. (beginning-of-line)
  20483. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20484. (open-line 1))
  20485. (org-indent-line)
  20486. (insert "# ")))
  20487. (defvar comment-empty-lines) ; From newcomment.el.
  20488. (defun org-comment-or-uncomment-region (beg end &rest _)
  20489. "Comment or uncomment each non-blank line in the region.
  20490. Uncomment each non-blank line between BEG and END if it only
  20491. contains commented lines. Otherwise, comment them. If region is
  20492. strictly within a source block, use appropriate comment syntax."
  20493. (if (let ((element (org-element-at-point)))
  20494. (and (eq (org-element-type element) 'src-block)
  20495. (< (save-excursion
  20496. (goto-char (org-element-property :post-affiliated element))
  20497. (line-end-position))
  20498. beg)
  20499. (>= (save-excursion
  20500. (goto-char (org-element-property :end element))
  20501. (skip-chars-backward " \r\t\n")
  20502. (line-beginning-position))
  20503. end)))
  20504. ;; Translate region boundaries for the Org buffer to the source
  20505. ;; buffer.
  20506. (let ((offset (- end beg)))
  20507. (save-excursion
  20508. (goto-char beg)
  20509. (org-babel-do-in-edit-buffer
  20510. (comment-or-uncomment-region (point) (+ offset (point))))))
  20511. (save-restriction
  20512. ;; Restrict region
  20513. (narrow-to-region (save-excursion (goto-char beg)
  20514. (skip-chars-forward " \r\t\n" end)
  20515. (line-beginning-position))
  20516. (save-excursion (goto-char end)
  20517. (skip-chars-backward " \r\t\n" beg)
  20518. (line-end-position)))
  20519. (let ((uncommentp
  20520. ;; UNCOMMENTP is non-nil when every non blank line between
  20521. ;; BEG and END is a comment.
  20522. (save-excursion
  20523. (goto-char (point-min))
  20524. (while (and (not (eobp))
  20525. (let ((element (org-element-at-point)))
  20526. (and (eq (org-element-type element) 'comment)
  20527. (goto-char (min (point-max)
  20528. (org-element-property
  20529. :end element)))))))
  20530. (eobp))))
  20531. (if uncommentp
  20532. ;; Only blank lines and comments in region: uncomment it.
  20533. (save-excursion
  20534. (goto-char (point-min))
  20535. (while (not (eobp))
  20536. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20537. (replace-match "" nil nil nil 1))
  20538. (forward-line)))
  20539. ;; Comment each line in region.
  20540. (let ((min-indent (point-max)))
  20541. ;; First find the minimum indentation across all lines.
  20542. (save-excursion
  20543. (goto-char (point-min))
  20544. (while (and (not (eobp)) (not (zerop min-indent)))
  20545. (unless (looking-at "[ \t]*$")
  20546. (setq min-indent (min min-indent (current-indentation))))
  20547. (forward-line)))
  20548. ;; Then loop over all lines.
  20549. (save-excursion
  20550. (goto-char (point-min))
  20551. (while (not (eobp))
  20552. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20553. ;; Don't get fooled by invisible text (e.g. link path)
  20554. ;; when moving to column MIN-INDENT.
  20555. (let ((buffer-invisibility-spec nil))
  20556. (org-move-to-column min-indent t))
  20557. (insert comment-start))
  20558. (forward-line)))))))))
  20559. (defun org-comment-dwim (_arg)
  20560. "Call the comment command you mean.
  20561. Call `org-toggle-comment' if on a heading, otherwise call
  20562. `comment-dwim', within a source edit buffer if needed."
  20563. (interactive "*P")
  20564. (cond ((org-at-heading-p)
  20565. (call-interactively #'org-toggle-comment))
  20566. ((org-in-src-block-p)
  20567. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20568. (t (call-interactively #'comment-dwim))))
  20569. ;;; Timestamps API
  20570. ;; This section contains tools to operate on, or create, timestamp
  20571. ;; objects, as returned by, e.g. `org-element-context'.
  20572. (defun org-timestamp-from-string (s)
  20573. "Convert Org timestamp S, as a string, into a timestamp object.
  20574. Return nil if S is not a valid timestamp string."
  20575. (when (org-string-nw-p s)
  20576. (with-temp-buffer
  20577. (save-excursion (insert s))
  20578. (org-element-timestamp-parser))))
  20579. (defun org-timestamp-from-time (time &optional with-time inactive)
  20580. "Convert a time value into a timestamp object.
  20581. TIME is an Emacs internal time representation, as returned, e.g.,
  20582. by `current-time'.
  20583. When optional argument WITH-TIME is non-nil, return a timestamp
  20584. object with a time part, i.e., with hours and minutes.
  20585. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20586. return an active timestamp."
  20587. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20588. (org-element-create 'timestamp
  20589. (list :type (if inactive 'inactive 'active)
  20590. :year-start year
  20591. :month-start month
  20592. :day-start day
  20593. :hour-start (and with-time hour)
  20594. :minute-start (and with-time minute)))))
  20595. (defun org-timestamp-to-time (timestamp &optional end)
  20596. "Convert TIMESTAMP object into an Emacs internal time value.
  20597. Use end of date range or time range when END is non-nil.
  20598. Otherwise, use its start."
  20599. (apply #'encode-time
  20600. (cons 0
  20601. (mapcar
  20602. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20603. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20604. '(:minute-start :hour-start :day-start :month-start
  20605. :year-start))))))
  20606. (defun org-timestamp-has-time-p (timestamp)
  20607. "Non-nil when TIMESTAMP has a time specified."
  20608. (org-element-property :hour-start timestamp))
  20609. (defun org-timestamp-format (timestamp format &optional end utc)
  20610. "Format a TIMESTAMP object into a string.
  20611. FORMAT is a format specifier to be passed to
  20612. `format-time-string'.
  20613. When optional argument END is non-nil, use end of date-range or
  20614. time-range, if possible.
  20615. When optional argument UTC is non-nil, time is be expressed as
  20616. Universal Time."
  20617. (format-time-string format (org-timestamp-to-time timestamp end)
  20618. (and utc t)))
  20619. (defun org-timestamp-split-range (timestamp &optional end)
  20620. "Extract a TIMESTAMP object from a date or time range.
  20621. END, when non-nil, means extract the end of the range.
  20622. Otherwise, extract its start.
  20623. Return a new timestamp object."
  20624. (let ((type (org-element-property :type timestamp)))
  20625. (if (memq type '(active inactive diary)) timestamp
  20626. (let ((split-ts (org-element-copy timestamp)))
  20627. ;; Set new type.
  20628. (org-element-put-property
  20629. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20630. ;; Copy start properties over end properties if END is
  20631. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20632. (let ((p-alist '((:minute-start . :minute-end)
  20633. (:hour-start . :hour-end)
  20634. (:day-start . :day-end)
  20635. (:month-start . :month-end)
  20636. (:year-start . :year-end))))
  20637. (dolist (p-cell p-alist)
  20638. (org-element-put-property
  20639. split-ts
  20640. (funcall (if end #'car #'cdr) p-cell)
  20641. (org-element-property
  20642. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20643. ;; Eventually refresh `:raw-value'.
  20644. (org-element-put-property split-ts :raw-value nil)
  20645. (org-element-put-property
  20646. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20647. (defun org-timestamp-translate (timestamp &optional boundary)
  20648. "Translate TIMESTAMP object to custom format.
  20649. Format string is defined in `org-time-stamp-custom-formats',
  20650. which see.
  20651. When optional argument BOUNDARY is non-nil, it is either the
  20652. symbol `start' or `end'. In this case, only translate the
  20653. starting or ending part of TIMESTAMP if it is a date or time
  20654. range. Otherwise, translate both parts.
  20655. Return timestamp as-is if `org-display-custom-times' is nil or if
  20656. it has a `diary' type."
  20657. (let ((type (org-element-property :type timestamp)))
  20658. (if (or (not org-display-custom-times) (eq type 'diary))
  20659. (org-element-interpret-data timestamp)
  20660. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20661. org-time-stamp-custom-formats)))
  20662. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20663. (concat (org-timestamp-format timestamp fmt)
  20664. "--"
  20665. (org-timestamp-format timestamp fmt t))
  20666. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20667. ;;; Other stuff
  20668. (defvar reftex-docstruct-symbol)
  20669. (defvar org--rds)
  20670. (defun org-reftex-citation ()
  20671. "Use reftex-citation to insert a citation into the buffer.
  20672. This looks for a line like
  20673. #+BIBLIOGRAPHY: foo plain option:-d
  20674. and derives from it that foo.bib is the bibliography file relevant
  20675. for this document. It then installs the necessary environment for RefTeX
  20676. to work in this buffer and calls `reftex-citation' to insert a citation
  20677. into the buffer.
  20678. Export of such citations to both LaTeX and HTML is handled by the contributed
  20679. package ox-bibtex by Taru Karttunen."
  20680. (interactive)
  20681. (let ((reftex-docstruct-symbol 'org--rds)
  20682. org--rds bib)
  20683. (org-with-wide-buffer
  20684. (let ((case-fold-search t)
  20685. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20686. (if (not (save-excursion
  20687. (or (re-search-forward re nil t)
  20688. (re-search-backward re nil t))))
  20689. (user-error "No bibliography defined in file")
  20690. (setq bib (concat (match-string 1) ".bib")
  20691. org--rds (list (list 'bib bib))))))
  20692. (call-interactively 'reftex-citation)))
  20693. ;;;; Functions extending outline functionality
  20694. (defun org-beginning-of-line (&optional n)
  20695. "Go to the beginning of the current visible line.
  20696. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20697. symbol `reversed', on the first attempt move to where the
  20698. headline text starts, and only move to beginning of line when the
  20699. cursor is already before the start of the text of the headline.
  20700. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20701. start of the text on the second attempt.
  20702. With argument N not nil or 1, move forward N - 1 lines first."
  20703. (interactive "^p")
  20704. (let ((origin (point))
  20705. (special (pcase org-special-ctrl-a/e
  20706. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20707. deactivate-mark)
  20708. ;; First move to a visible line.
  20709. (if (bound-and-true-p visual-line-mode)
  20710. (beginning-of-visual-line n)
  20711. (move-beginning-of-line n)
  20712. ;; `move-beginning-of-line' may leave point after invisible
  20713. ;; characters if line starts with such of these (e.g., with
  20714. ;; a link at column 0). Really move to the beginning of the
  20715. ;; current visible line.
  20716. (beginning-of-line))
  20717. (cond
  20718. ;; No special behavior. Point is already at the beginning of
  20719. ;; a line, logical or visual.
  20720. ((not special))
  20721. ;; `beginning-of-visual-line' left point before logical beginning
  20722. ;; of line: point is at the beginning of a visual line. Bail
  20723. ;; out.
  20724. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20725. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20726. ;; At a headline, special position is before the title, but
  20727. ;; after any TODO keyword or priority cookie.
  20728. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20729. (line-end-position)))
  20730. (bol (point)))
  20731. (if (eq special 'reversed)
  20732. (when (and (= origin bol) (eq last-command this-command))
  20733. (goto-char refpos))
  20734. (when (or (> origin refpos) (= origin bol))
  20735. (goto-char refpos)))))
  20736. ((and (looking-at org-list-full-item-re)
  20737. (memq (org-element-type (save-match-data (org-element-at-point)))
  20738. '(item plain-list)))
  20739. ;; Set special position at first white space character after
  20740. ;; bullet, and check-box, if any.
  20741. (let ((after-bullet
  20742. (let ((box (match-end 3)))
  20743. (cond ((not box) (match-end 1))
  20744. ((eq (char-after box) ?\s) (1+ box))
  20745. (t box)))))
  20746. (if (eq special 'reversed)
  20747. (when (and (= (point) origin) (eq last-command this-command))
  20748. (goto-char after-bullet))
  20749. (when (or (> origin after-bullet) (= (point) origin))
  20750. (goto-char after-bullet)))))
  20751. ;; No special context. Point is already at beginning of line.
  20752. (t nil))))
  20753. (defun org-end-of-line (&optional n)
  20754. "Go to the end of the line, but before ellipsis, if any.
  20755. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20756. symbol `reversed', ignore tags on the first attempt, and only
  20757. move to after the tags when the cursor is already beyond the end
  20758. of the headline.
  20759. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20760. on the second attempt.
  20761. With argument N not nil or 1, move forward N - 1 lines first."
  20762. (interactive "^p")
  20763. (let ((origin (point))
  20764. (special (pcase org-special-ctrl-a/e
  20765. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20766. deactivate-mark)
  20767. ;; First move to a visible line.
  20768. (if (bound-and-true-p visual-line-mode)
  20769. (beginning-of-visual-line n)
  20770. (move-beginning-of-line n))
  20771. (cond
  20772. ;; At a headline, with tags.
  20773. ((and special
  20774. (save-excursion
  20775. (beginning-of-line)
  20776. (let ((case-fold-search nil))
  20777. (looking-at org-complex-heading-regexp)))
  20778. (match-end 5))
  20779. (let ((tags (save-excursion
  20780. (goto-char (match-beginning 5))
  20781. (skip-chars-backward " \t")
  20782. (point)))
  20783. (visual-end (and (bound-and-true-p visual-line-mode)
  20784. (save-excursion
  20785. (end-of-visual-line)
  20786. (point)))))
  20787. ;; If `end-of-visual-line' brings us before end of line or
  20788. ;; even tags, i.e., the headline spans over multiple visual
  20789. ;; lines, move there.
  20790. (cond ((and visual-end
  20791. (< visual-end tags)
  20792. (<= origin visual-end))
  20793. (goto-char visual-end))
  20794. ((eq special 'reversed)
  20795. (if (and (= origin (line-end-position))
  20796. (eq this-command last-command))
  20797. (goto-char tags)
  20798. (end-of-line)))
  20799. (t
  20800. (if (or (< origin tags) (= origin (line-end-position)))
  20801. (goto-char tags)
  20802. (end-of-line))))))
  20803. ((bound-and-true-p visual-line-mode)
  20804. (let ((bol (line-beginning-position)))
  20805. (end-of-visual-line)
  20806. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20807. ;; end of a line, backtrack and use `end-of-line' instead.
  20808. (when (/= bol (line-beginning-position))
  20809. (goto-char bol)
  20810. (end-of-line))))
  20811. (t (end-of-line)))))
  20812. (defun org-backward-sentence (&optional _arg)
  20813. "Go to beginning of sentence, or beginning of table field.
  20814. This will call `backward-sentence' or `org-table-beginning-of-field',
  20815. depending on context."
  20816. (interactive)
  20817. (let* ((element (org-element-at-point))
  20818. (contents-begin (org-element-property :contents-begin element))
  20819. (table (org-element-lineage element '(table) t)))
  20820. (if (and table
  20821. (> (point) contents-begin)
  20822. (<= (point) (org-element-property :contents-end table)))
  20823. (call-interactively #'org-table-beginning-of-field)
  20824. (save-restriction
  20825. (when (and contents-begin
  20826. (< (point-min) contents-begin)
  20827. (> (point) contents-begin))
  20828. (narrow-to-region contents-begin
  20829. (org-element-property :contents-end element)))
  20830. (call-interactively #'backward-sentence)))))
  20831. (defun org-forward-sentence (&optional _arg)
  20832. "Go to end of sentence, or end of table field.
  20833. This will call `forward-sentence' or `org-table-end-of-field',
  20834. depending on context."
  20835. (interactive)
  20836. (if (and (org-at-heading-p)
  20837. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20838. (save-restriction
  20839. (narrow-to-region (line-beginning-position) (line-end-position))
  20840. (call-interactively #'forward-sentence))
  20841. (let* ((element (org-element-at-point))
  20842. (contents-end (org-element-property :contents-end element))
  20843. (table (org-element-lineage element '(table) t)))
  20844. (if (and table
  20845. (>= (point) (org-element-property :contents-begin table))
  20846. (< (point) contents-end))
  20847. (call-interactively #'org-table-end-of-field)
  20848. (save-restriction
  20849. (when (and contents-end
  20850. (> (point-max) contents-end)
  20851. ;; Skip blank lines between elements.
  20852. (< (org-element-property :end element)
  20853. (save-excursion (goto-char contents-end)
  20854. (skip-chars-forward " \r\t\n"))))
  20855. (narrow-to-region (org-element-property :contents-begin element)
  20856. contents-end))
  20857. ;; End of heading is considered as the end of a sentence.
  20858. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20859. (call-interactively #'forward-sentence)))))))
  20860. (defun org-kill-line (&optional _arg)
  20861. "Kill line, to tags or end of line."
  20862. (interactive)
  20863. (cond
  20864. ((or (not org-special-ctrl-k)
  20865. (bolp)
  20866. (not (org-at-heading-p)))
  20867. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  20868. org-ctrl-k-protect-subtree
  20869. (or (eq org-ctrl-k-protect-subtree 'error)
  20870. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20871. (user-error
  20872. (substitute-command-keys
  20873. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20874. (call-interactively
  20875. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20876. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  20877. (kill-region (point) (match-beginning 1))
  20878. (org-set-tags nil t))
  20879. (t (kill-region (point) (point-at-eol)))))
  20880. (defun org-yank (&optional arg)
  20881. "Yank. If the kill is a subtree, treat it specially.
  20882. This command will look at the current kill and check if is a single
  20883. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20884. cursor is at the beginning of a line or after the stars of a currently
  20885. empty headline, then the yank is handled specially. How exactly depends
  20886. on the value of the following variables.
  20887. `org-yank-folded-subtrees'
  20888. By default, this variable is non-nil, which results in
  20889. subtree(s) being folded after insertion, except if doing so
  20890. would swallow text after the yanked text.
  20891. `org-yank-adjusted-subtrees'
  20892. When non-nil (the default value is nil), the subtree will be
  20893. promoted or demoted in order to fit into the local outline tree
  20894. structure, which means that the level will be adjusted so that it
  20895. becomes the smaller one of the two *visible* surrounding headings.
  20896. Any prefix to this command will cause `yank' to be called directly with
  20897. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20898. will just
  20899. plainly yank the text as it is.
  20900. \[1] The test checks if the first non-white line is a heading
  20901. and if there are no other headings with fewer stars."
  20902. (interactive "P")
  20903. (org-yank-generic 'yank arg))
  20904. (defun org-yank-generic (command arg)
  20905. "Perform some yank-like command.
  20906. This function implements the behavior described in the `org-yank'
  20907. documentation. However, it has been generalized to work for any
  20908. interactive command with similar behavior."
  20909. ;; pretend to be command COMMAND
  20910. (setq this-command command)
  20911. (if arg
  20912. (call-interactively command)
  20913. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20914. (and (org-kill-is-subtree-p)
  20915. (or (bolp)
  20916. (and (looking-at "[ \t]*$")
  20917. (string-match
  20918. "\\`\\*+\\'"
  20919. (buffer-substring (point-at-bol) (point)))))))
  20920. swallowp)
  20921. (cond
  20922. ((and subtreep org-yank-folded-subtrees)
  20923. (let ((beg (point))
  20924. end)
  20925. (if (and subtreep org-yank-adjusted-subtrees)
  20926. (org-paste-subtree nil nil 'for-yank)
  20927. (call-interactively command))
  20928. (setq end (point))
  20929. (goto-char beg)
  20930. (when (and (bolp) subtreep
  20931. (not (setq swallowp
  20932. (org-yank-folding-would-swallow-text beg end))))
  20933. (org-with-limited-levels
  20934. (or (looking-at org-outline-regexp)
  20935. (re-search-forward org-outline-regexp-bol end t))
  20936. (while (and (< (point) end) (looking-at org-outline-regexp))
  20937. (outline-hide-subtree)
  20938. (org-cycle-show-empty-lines 'folded)
  20939. (condition-case nil
  20940. (outline-forward-same-level 1)
  20941. (error (goto-char end))))))
  20942. (when swallowp
  20943. (message
  20944. "Inserted text not folded because that would swallow text"))
  20945. (goto-char end)
  20946. (skip-chars-forward " \t\n\r")
  20947. (beginning-of-line 1)
  20948. (push-mark beg 'nomsg)))
  20949. ((and subtreep org-yank-adjusted-subtrees)
  20950. (let ((beg (point-at-bol)))
  20951. (org-paste-subtree nil nil 'for-yank)
  20952. (push-mark beg 'nomsg)))
  20953. (t
  20954. (call-interactively command))))))
  20955. (defun org-yank-folding-would-swallow-text (beg end)
  20956. "Would hide-subtree at BEG swallow any text after END?"
  20957. (let (level)
  20958. (org-with-limited-levels
  20959. (save-excursion
  20960. (goto-char beg)
  20961. (when (or (looking-at org-outline-regexp)
  20962. (re-search-forward org-outline-regexp-bol end t))
  20963. (setq level (org-outline-level)))
  20964. (goto-char end)
  20965. (skip-chars-forward " \t\r\n\v\f")
  20966. (not (or (eobp)
  20967. (and (bolp) (looking-at-p org-outline-regexp)
  20968. (<= (org-outline-level) level))))))))
  20969. (defun org-back-to-heading (&optional invisible-ok)
  20970. "Call `outline-back-to-heading', but provide a better error message."
  20971. (condition-case nil
  20972. (outline-back-to-heading invisible-ok)
  20973. (error (error "Before first headline at position %d in buffer %s"
  20974. (point) (current-buffer)))))
  20975. (defun org-before-first-heading-p ()
  20976. "Before first heading?"
  20977. (save-excursion
  20978. (end-of-line)
  20979. (null (re-search-backward org-outline-regexp-bol nil t))))
  20980. (defun org-at-heading-p (&optional ignored)
  20981. (outline-on-heading-p t))
  20982. (defun org-in-commented-heading-p (&optional no-inheritance)
  20983. "Non-nil if point is under a commented heading.
  20984. This function also checks ancestors of the current headline,
  20985. unless optional argument NO-INHERITANCE is non-nil."
  20986. (cond
  20987. ((org-before-first-heading-p) nil)
  20988. ((let ((headline (nth 4 (org-heading-components))))
  20989. (and headline
  20990. (let ((case-fold-search nil))
  20991. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  20992. headline)))))
  20993. (no-inheritance nil)
  20994. (t
  20995. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  20996. (defun org-at-comment-p nil
  20997. "Is cursor in a commented line?"
  20998. (save-excursion
  20999. (save-match-data
  21000. (beginning-of-line)
  21001. (looking-at "^[ \t]*# "))))
  21002. (defun org-at-drawer-p nil
  21003. "Is cursor at a drawer keyword?"
  21004. (save-excursion
  21005. (move-beginning-of-line 1)
  21006. (looking-at org-drawer-regexp)))
  21007. (defun org-at-block-p nil
  21008. "Is cursor at a block keyword?"
  21009. (save-excursion
  21010. (move-beginning-of-line 1)
  21011. (looking-at org-block-regexp)))
  21012. (defun org-point-at-end-of-empty-headline ()
  21013. "If point is at the end of an empty headline, return t, else nil.
  21014. If the heading only contains a TODO keyword, it is still still considered
  21015. empty."
  21016. (let ((case-fold-search nil))
  21017. (and (looking-at "[ \t]*$")
  21018. org-todo-line-regexp
  21019. (save-excursion
  21020. (beginning-of-line)
  21021. (looking-at org-todo-line-regexp)
  21022. (string= (match-string 3) "")))))
  21023. (defun org-at-heading-or-item-p ()
  21024. (or (org-at-heading-p) (org-at-item-p)))
  21025. (defun org-at-target-p ()
  21026. (or (org-in-regexp org-radio-target-regexp)
  21027. (org-in-regexp org-target-regexp)))
  21028. ;; Compatibility alias with Org versions < 7.8.03
  21029. (defalias 'org-on-target-p 'org-at-target-p)
  21030. (defun org-up-heading-all (arg)
  21031. "Move to the heading line of which the present line is a subheading.
  21032. This function considers both visible and invisible heading lines.
  21033. With argument, move up ARG levels."
  21034. (outline-up-heading arg t))
  21035. (defun org-up-heading-safe ()
  21036. "Move to the heading line of which the present line is a subheading.
  21037. This version will not throw an error. It will return the level of the
  21038. headline found, or nil if no higher level is found.
  21039. Also, this function will be a lot faster than `outline-up-heading',
  21040. because it relies on stars being the outline starters. This can really
  21041. make a significant difference in outlines with very many siblings."
  21042. (when (ignore-errors (org-back-to-heading t))
  21043. (let ((level-up (1- (funcall outline-level))))
  21044. (and (> level-up 0)
  21045. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21046. (funcall outline-level)))))
  21047. (defun org-first-sibling-p ()
  21048. "Is this heading the first child of its parents?"
  21049. (interactive)
  21050. (let ((re org-outline-regexp-bol)
  21051. level l)
  21052. (unless (org-at-heading-p t)
  21053. (user-error "Not at a heading"))
  21054. (setq level (funcall outline-level))
  21055. (save-excursion
  21056. (if (not (re-search-backward re nil t))
  21057. t
  21058. (setq l (funcall outline-level))
  21059. (< l level)))))
  21060. (defun org-goto-sibling (&optional previous)
  21061. "Goto the next sibling, even if it is invisible.
  21062. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21063. when a sibling was found. When none is found, return nil and don't
  21064. move point."
  21065. (let ((fun (if previous 're-search-backward 're-search-forward))
  21066. (pos (point))
  21067. (re org-outline-regexp-bol)
  21068. level l)
  21069. (when (ignore-errors (org-back-to-heading t))
  21070. (setq level (funcall outline-level))
  21071. (catch 'exit
  21072. (or previous (forward-char 1))
  21073. (while (funcall fun re nil t)
  21074. (setq l (funcall outline-level))
  21075. (when (< l level) (goto-char pos) (throw 'exit nil))
  21076. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21077. (goto-char pos)
  21078. nil))))
  21079. (defun org-show-siblings ()
  21080. "Show all siblings of the current headline."
  21081. (save-excursion
  21082. (while (org-goto-sibling) (org-flag-heading nil)))
  21083. (save-excursion
  21084. (while (org-goto-sibling 'previous)
  21085. (org-flag-heading nil))))
  21086. (defun org-goto-first-child ()
  21087. "Goto the first child, even if it is invisible.
  21088. Return t when a child was found. Otherwise don't move point and
  21089. return nil."
  21090. (let (level (pos (point)) (re org-outline-regexp-bol))
  21091. (when (ignore-errors (org-back-to-heading t))
  21092. (setq level (outline-level))
  21093. (forward-char 1)
  21094. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21095. (progn (goto-char (match-beginning 0)) t)
  21096. (goto-char pos) nil))))
  21097. (defun org-show-hidden-entry ()
  21098. "Show an entry where even the heading is hidden."
  21099. (save-excursion
  21100. (org-show-entry)))
  21101. (defun org-flag-heading (flag &optional entry)
  21102. "Flag the current heading. FLAG non-nil means make invisible.
  21103. When ENTRY is non-nil, show the entire entry."
  21104. (save-excursion
  21105. (org-back-to-heading t)
  21106. ;; Check if we should show the entire entry
  21107. (if (not entry)
  21108. (org-flag-region
  21109. (line-end-position 0) (line-end-position) flag 'outline)
  21110. (org-show-entry)
  21111. (save-excursion
  21112. (and (outline-next-heading)
  21113. (org-flag-heading nil))))))
  21114. (defun org-get-next-sibling ()
  21115. "Move to next heading of the same level, and return point.
  21116. If there is no such heading, return nil.
  21117. This is like outline-next-sibling, but invisible headings are ok."
  21118. (let ((level (funcall outline-level)))
  21119. (outline-next-heading)
  21120. (while (and (not (eobp)) (> (funcall outline-level) level))
  21121. (outline-next-heading))
  21122. (unless (or (eobp) (< (funcall outline-level) level))
  21123. (point))))
  21124. (defun org-get-last-sibling ()
  21125. "Move to previous heading of the same level, and return point.
  21126. If there is no such heading, return nil."
  21127. (let ((opoint (point))
  21128. (level (funcall outline-level)))
  21129. (outline-previous-heading)
  21130. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21131. (while (and (> (funcall outline-level) level)
  21132. (not (bobp)))
  21133. (outline-previous-heading))
  21134. (unless (< (funcall outline-level) level)
  21135. (point)))))
  21136. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21137. "Goto to the end of a subtree."
  21138. ;; This contains an exact copy of the original function, but it uses
  21139. ;; `org-back-to-heading', to make it work also in invisible
  21140. ;; trees. And is uses an invisible-ok argument.
  21141. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21142. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21143. ;; with many children and grandchildren etc, this can be much faster
  21144. ;; than the outline version.
  21145. (org-back-to-heading invisible-ok)
  21146. (let ((first t)
  21147. (level (funcall outline-level)))
  21148. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21149. ;; A true heading (not a plain list item), in Org
  21150. ;; This means we can easily find the end by looking
  21151. ;; only for the right number of stars. Using a regexp to do
  21152. ;; this is so much faster than using a Lisp loop.
  21153. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21154. (forward-char 1)
  21155. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21156. ;; something else, do it the slow way
  21157. (while (and (not (eobp))
  21158. (or first (> (funcall outline-level) level)))
  21159. (setq first nil)
  21160. (outline-next-heading)))
  21161. (unless to-heading
  21162. (when (memq (preceding-char) '(?\n ?\^M))
  21163. ;; Go to end of line before heading
  21164. (forward-char -1)
  21165. (when (memq (preceding-char) '(?\n ?\^M))
  21166. ;; leave blank line before heading
  21167. (forward-char -1)))))
  21168. (point))
  21169. (defun org-end-of-meta-data (&optional full)
  21170. "Skip planning line and properties drawer in current entry.
  21171. When optional argument FULL is non-nil, also skip empty lines,
  21172. clocking lines and regular drawers at the beginning of the
  21173. entry."
  21174. (org-back-to-heading t)
  21175. (forward-line)
  21176. (when (looking-at-p org-planning-line-re) (forward-line))
  21177. (when (looking-at org-property-drawer-re)
  21178. (goto-char (match-end 0))
  21179. (forward-line))
  21180. (when (and full (not (org-at-heading-p)))
  21181. (catch 'exit
  21182. (let ((end (save-excursion (outline-next-heading) (point)))
  21183. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21184. (while (not (eobp))
  21185. (cond ((looking-at-p org-drawer-regexp)
  21186. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21187. (forward-line)
  21188. (throw 'exit t)))
  21189. ((looking-at-p re) (forward-line))
  21190. (t (throw 'exit t))))))))
  21191. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21192. "Move forward to the ARG'th subheading at same level as this one.
  21193. Stop at the first and last subheadings of a superior heading.
  21194. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21195. non-nil it will also look at invisible ones."
  21196. (interactive "p")
  21197. (let ((backward? (and arg (< arg 0))))
  21198. (if (org-before-first-heading-p)
  21199. (if backward? (goto-char (point-min)) (outline-next-heading))
  21200. (org-back-to-heading invisible-ok)
  21201. (unless backward? (end-of-line)) ;do not match current headline
  21202. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21203. (f (if backward? #'re-search-backward #'re-search-forward))
  21204. (count (if arg (abs arg) 1))
  21205. (result (point)))
  21206. (while (and (> count 0)
  21207. (funcall f org-outline-regexp-bol nil 'move))
  21208. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21209. (cond ((< l level) (setq count 0))
  21210. ((and (= l level)
  21211. (or invisible-ok
  21212. (not (org-invisible-p
  21213. (line-beginning-position)))))
  21214. (cl-decf count)
  21215. (when (= l level) (setq result (point)))))))
  21216. (goto-char result))
  21217. (beginning-of-line))))
  21218. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21219. "Move backward to the ARG'th subheading at same level as this one.
  21220. Stop at the first and last subheadings of a superior heading."
  21221. (interactive "p")
  21222. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21223. (defun org-next-visible-heading (arg)
  21224. "Move to the next visible heading.
  21225. This function wraps `outline-next-visible-heading' with
  21226. `org-with-limited-levels' in order to skip over inline tasks and
  21227. respect customization of `org-odd-levels-only'."
  21228. (interactive "p")
  21229. (org-with-limited-levels
  21230. (outline-next-visible-heading arg)))
  21231. (defun org-previous-visible-heading (arg)
  21232. "Move to the previous visible heading.
  21233. This function wraps `outline-previous-visible-heading' with
  21234. `org-with-limited-levels' in order to skip over inline tasks and
  21235. respect customization of `org-odd-levels-only'."
  21236. (interactive "p")
  21237. (org-with-limited-levels
  21238. (outline-previous-visible-heading arg)))
  21239. (defun org-forward-paragraph ()
  21240. "Move forward to beginning of next paragraph or equivalent.
  21241. The function moves point to the beginning of the next visible
  21242. structural element, which can be a paragraph, a table, a list
  21243. item, etc. It also provides some special moves for convenience:
  21244. - On an affiliated keyword, jump to the beginning of the
  21245. relative element.
  21246. - On an item or a footnote definition, move to the second
  21247. element inside, if any.
  21248. - On a table or a property drawer, jump after it.
  21249. - On a verse or source block, stop after blank lines."
  21250. (interactive)
  21251. (unless (eobp)
  21252. (let* ((deactivate-mark nil)
  21253. (element (org-element-at-point))
  21254. (type (org-element-type element))
  21255. (post-affiliated (org-element-property :post-affiliated element))
  21256. (contents-begin (org-element-property :contents-begin element))
  21257. (contents-end (org-element-property :contents-end element))
  21258. (end (let ((end (org-element-property :end element)) (parent element))
  21259. (while (and (setq parent (org-element-property :parent parent))
  21260. (= (org-element-property :contents-end parent) end))
  21261. (setq end (org-element-property :end parent)))
  21262. end)))
  21263. (cond ((not element)
  21264. (skip-chars-forward " \r\t\n")
  21265. (or (eobp) (beginning-of-line)))
  21266. ;; On affiliated keywords, move to element's beginning.
  21267. ((< (point) post-affiliated)
  21268. (goto-char post-affiliated))
  21269. ;; At a table row, move to the end of the table. Similarly,
  21270. ;; at a node property, move to the end of the property
  21271. ;; drawer.
  21272. ((memq type '(node-property table-row))
  21273. (goto-char (org-element-property
  21274. :end (org-element-property :parent element))))
  21275. ((memq type '(property-drawer table)) (goto-char end))
  21276. ;; Consider blank lines as separators in verse and source
  21277. ;; blocks to ease editing.
  21278. ((memq type '(src-block verse-block))
  21279. (when (eq type 'src-block)
  21280. (setq contents-end
  21281. (save-excursion (goto-char end)
  21282. (skip-chars-backward " \r\t\n")
  21283. (line-beginning-position))))
  21284. (beginning-of-line)
  21285. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21286. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21287. (goto-char end)
  21288. (skip-chars-forward " \r\t\n")
  21289. (if (= (point) contents-end) (goto-char end)
  21290. (beginning-of-line))))
  21291. ;; With no contents, just skip element.
  21292. ((not contents-begin) (goto-char end))
  21293. ;; If contents are invisible, skip the element altogether.
  21294. ((org-invisible-p (line-end-position))
  21295. (cl-case type
  21296. (headline
  21297. (org-with-limited-levels (outline-next-visible-heading 1)))
  21298. ;; At a plain list, make sure we move to the next item
  21299. ;; instead of skipping the whole list.
  21300. (plain-list (forward-char)
  21301. (org-forward-paragraph))
  21302. (otherwise (goto-char end))))
  21303. ((>= (point) contents-end) (goto-char end))
  21304. ((>= (point) contents-begin)
  21305. ;; This can only happen on paragraphs and plain lists.
  21306. (cl-case type
  21307. (paragraph (goto-char end))
  21308. ;; At a plain list, try to move to second element in
  21309. ;; first item, if possible.
  21310. (plain-list (end-of-line)
  21311. (org-forward-paragraph))))
  21312. ;; When contents start on the middle of a line (e.g. in
  21313. ;; items and footnote definitions), try to reach first
  21314. ;; element starting after current line.
  21315. ((> (line-end-position) contents-begin)
  21316. (end-of-line)
  21317. (org-forward-paragraph))
  21318. (t (goto-char contents-begin))))))
  21319. (defun org-backward-paragraph ()
  21320. "Move backward to start of previous paragraph or equivalent.
  21321. The function moves point to the beginning of the current
  21322. structural element, which can be a paragraph, a table, a list
  21323. item, etc., or to the beginning of the previous visible one if
  21324. point is already there. It also provides some special moves for
  21325. convenience:
  21326. - On an affiliated keyword, jump to the first one.
  21327. - On a table or a property drawer, move to its beginning.
  21328. - On comment, example, export, src and verse blocks, stop
  21329. before blank lines."
  21330. (interactive)
  21331. (unless (bobp)
  21332. (let* ((deactivate-mark nil)
  21333. (element (org-element-at-point))
  21334. (type (org-element-type element))
  21335. (contents-end (org-element-property :contents-end element))
  21336. (post-affiliated (org-element-property :post-affiliated element))
  21337. (begin (org-element-property :begin element))
  21338. (special? ;blocks handled specially
  21339. (memq type '(comment-block example-block export-block src-block
  21340. verse-block)))
  21341. (contents-begin
  21342. (if special?
  21343. ;; These types have no proper contents. Fake line
  21344. ;; below the block opening line as contents beginning.
  21345. (save-excursion (goto-char begin) (line-beginning-position 2))
  21346. (org-element-property :contents-begin element))))
  21347. (cond
  21348. ((not element) (goto-char (point-min)))
  21349. ((= (point) begin)
  21350. (backward-char)
  21351. (org-backward-paragraph))
  21352. ((<= (point) post-affiliated) (goto-char begin))
  21353. ;; Special behavior: on a table or a property drawer, move to
  21354. ;; its beginning.
  21355. ((memq type '(node-property table-row))
  21356. (goto-char (org-element-property
  21357. :post-affiliated (org-element-property :parent element))))
  21358. (special?
  21359. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21360. ;; Inside a verse block, see blank lines as paragraph
  21361. ;; separators.
  21362. (let ((origin (point)))
  21363. (skip-chars-backward " \r\t\n" contents-begin)
  21364. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21365. (skip-chars-forward " \r\t\n" origin)
  21366. (if (= (point) origin) (goto-char contents-begin)
  21367. (beginning-of-line))))))
  21368. ((eq type 'paragraph) (goto-char contents-begin)
  21369. ;; When at first paragraph in an item or a footnote definition,
  21370. ;; move directly to beginning of line.
  21371. (let ((parent-contents
  21372. (org-element-property
  21373. :contents-begin (org-element-property :parent element))))
  21374. (when (and parent-contents (= parent-contents contents-begin))
  21375. (beginning-of-line))))
  21376. ;; At the end of a greater element, move to the beginning of
  21377. ;; the last element within.
  21378. ((and contents-end (>= (point) contents-end))
  21379. (goto-char (1- contents-end))
  21380. (org-backward-paragraph))
  21381. (t (goto-char (or post-affiliated begin))))
  21382. ;; Ensure we never leave point invisible.
  21383. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21384. (defun org-forward-element ()
  21385. "Move forward by one element.
  21386. Move to the next element at the same level, when possible."
  21387. (interactive)
  21388. (cond ((eobp) (user-error "Cannot move further down"))
  21389. ((org-with-limited-levels (org-at-heading-p))
  21390. (let ((origin (point)))
  21391. (goto-char (org-end-of-subtree nil t))
  21392. (unless (org-with-limited-levels (org-at-heading-p))
  21393. (goto-char origin)
  21394. (user-error "Cannot move further down"))))
  21395. (t
  21396. (let* ((elem (org-element-at-point))
  21397. (end (org-element-property :end elem))
  21398. (parent (org-element-property :parent elem)))
  21399. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21400. (goto-char (org-element-property :end parent)))
  21401. ((integer-or-marker-p end) (goto-char end))
  21402. (t (message "No element at point")))))))
  21403. (defun org-backward-element ()
  21404. "Move backward by one element.
  21405. Move to the previous element at the same level, when possible."
  21406. (interactive)
  21407. (cond ((bobp) (user-error "Cannot move further up"))
  21408. ((org-with-limited-levels (org-at-heading-p))
  21409. ;; At a headline, move to the previous one, if any, or stay
  21410. ;; here.
  21411. (let ((origin (point)))
  21412. (org-with-limited-levels (org-backward-heading-same-level 1))
  21413. ;; When current headline has no sibling above, move to its
  21414. ;; parent.
  21415. (when (= (point) origin)
  21416. (or (org-with-limited-levels (org-up-heading-safe))
  21417. (progn (goto-char origin)
  21418. (user-error "Cannot move further up"))))))
  21419. (t
  21420. (let* ((elem (org-element-at-point))
  21421. (beg (org-element-property :begin elem)))
  21422. (cond
  21423. ;; Move to beginning of current element if point isn't
  21424. ;; there already.
  21425. ((null beg) (message "No element at point"))
  21426. ((/= (point) beg) (goto-char beg))
  21427. (t (goto-char beg)
  21428. (skip-chars-backward " \r\t\n")
  21429. (unless (bobp)
  21430. (let ((prev (org-element-at-point)))
  21431. (goto-char (org-element-property :begin prev))
  21432. (while (and (setq prev (org-element-property :parent prev))
  21433. (<= (org-element-property :end prev) beg))
  21434. (goto-char (org-element-property :begin prev)))))))))))
  21435. (defun org-up-element ()
  21436. "Move to upper element."
  21437. (interactive)
  21438. (if (org-with-limited-levels (org-at-heading-p))
  21439. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21440. (let* ((elem (org-element-at-point))
  21441. (parent (org-element-property :parent elem)))
  21442. (if parent (goto-char (org-element-property :begin parent))
  21443. (if (org-with-limited-levels (org-before-first-heading-p))
  21444. (user-error "No surrounding element")
  21445. (org-with-limited-levels (org-back-to-heading)))))))
  21446. (defun org-down-element ()
  21447. "Move to inner element."
  21448. (interactive)
  21449. (let ((element (org-element-at-point)))
  21450. (cond
  21451. ((memq (org-element-type element) '(plain-list table))
  21452. (goto-char (org-element-property :contents-begin element))
  21453. (forward-char))
  21454. ((memq (org-element-type element) org-element-greater-elements)
  21455. ;; If contents are hidden, first disclose them.
  21456. (when (org-invisible-p (line-end-position)) (org-cycle))
  21457. (goto-char (or (org-element-property :contents-begin element)
  21458. (user-error "No content for this element"))))
  21459. (t (user-error "No inner element")))))
  21460. (defun org-drag-element-backward ()
  21461. "Move backward element at point."
  21462. (interactive)
  21463. (let ((elem (or (org-element-at-point)
  21464. (user-error "No element at point"))))
  21465. (if (eq (org-element-type elem) 'headline)
  21466. ;; Preserve point when moving a whole tree, even if point was
  21467. ;; on blank lines below the headline.
  21468. (let ((offset (skip-chars-backward " \t\n")))
  21469. (unwind-protect (org-move-subtree-up)
  21470. (forward-char (- offset))))
  21471. (let ((prev-elem
  21472. (save-excursion
  21473. (goto-char (org-element-property :begin elem))
  21474. (skip-chars-backward " \r\t\n")
  21475. (unless (bobp)
  21476. (let* ((beg (org-element-property :begin elem))
  21477. (prev (org-element-at-point))
  21478. (up prev))
  21479. (while (and (setq up (org-element-property :parent up))
  21480. (<= (org-element-property :end up) beg))
  21481. (setq prev up))
  21482. prev)))))
  21483. ;; Error out if no previous element or previous element is
  21484. ;; a parent of the current one.
  21485. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21486. (user-error "Cannot drag element backward")
  21487. (let ((pos (point)))
  21488. (org-element-swap-A-B prev-elem elem)
  21489. (goto-char (+ (org-element-property :begin prev-elem)
  21490. (- pos (org-element-property :begin elem))))))))))
  21491. (defun org-drag-element-forward ()
  21492. "Move forward element at point."
  21493. (interactive)
  21494. (let* ((pos (point))
  21495. (elem (or (org-element-at-point)
  21496. (user-error "No element at point"))))
  21497. (when (= (point-max) (org-element-property :end elem))
  21498. (user-error "Cannot drag element forward"))
  21499. (goto-char (org-element-property :end elem))
  21500. (let ((next-elem (org-element-at-point)))
  21501. (when (or (org-element-nested-p elem next-elem)
  21502. (and (eq (org-element-type next-elem) 'headline)
  21503. (not (eq (org-element-type elem) 'headline))))
  21504. (goto-char pos)
  21505. (user-error "Cannot drag element forward"))
  21506. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21507. ;; body's length (without final blanks) and by the length of
  21508. ;; blanks between ELEM and NEXT-ELEM.
  21509. (let ((size-next (- (save-excursion
  21510. (goto-char (org-element-property :end next-elem))
  21511. (skip-chars-backward " \r\t\n")
  21512. (forward-line)
  21513. ;; Small correction if buffer doesn't end
  21514. ;; with a newline character.
  21515. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21516. (org-element-property :begin next-elem)))
  21517. (size-blank (- (org-element-property :end elem)
  21518. (save-excursion
  21519. (goto-char (org-element-property :end elem))
  21520. (skip-chars-backward " \r\t\n")
  21521. (forward-line)
  21522. (point)))))
  21523. (org-element-swap-A-B elem next-elem)
  21524. (goto-char (+ pos size-next size-blank))))))
  21525. (defun org-drag-line-forward (arg)
  21526. "Drag the line at point ARG lines forward."
  21527. (interactive "p")
  21528. (dotimes (_ (abs arg))
  21529. (let ((c (current-column)))
  21530. (if (< 0 arg)
  21531. (progn
  21532. (beginning-of-line 2)
  21533. (transpose-lines 1)
  21534. (beginning-of-line 0))
  21535. (transpose-lines 1)
  21536. (beginning-of-line -1))
  21537. (org-move-to-column c))))
  21538. (defun org-drag-line-backward (arg)
  21539. "Drag the line at point ARG lines backward."
  21540. (interactive "p")
  21541. (org-drag-line-forward (- arg)))
  21542. (defun org-mark-element ()
  21543. "Put point at beginning of this element, mark at end.
  21544. Interactively, if this command is repeated or (in Transient Mark
  21545. mode) if the mark is active, it marks the next element after the
  21546. ones already marked."
  21547. (interactive)
  21548. (let (deactivate-mark)
  21549. (if (and (called-interactively-p 'any)
  21550. (or (and (eq last-command this-command) (mark t))
  21551. (and transient-mark-mode mark-active)))
  21552. (set-mark
  21553. (save-excursion
  21554. (goto-char (mark))
  21555. (goto-char (org-element-property :end (org-element-at-point)))))
  21556. (let ((element (org-element-at-point)))
  21557. (end-of-line)
  21558. (push-mark (org-element-property :end element) t t)
  21559. (goto-char (org-element-property :begin element))))))
  21560. (defun org-narrow-to-element ()
  21561. "Narrow buffer to current element."
  21562. (interactive)
  21563. (let ((elem (org-element-at-point)))
  21564. (cond
  21565. ((eq (car elem) 'headline)
  21566. (narrow-to-region
  21567. (org-element-property :begin elem)
  21568. (org-element-property :end elem)))
  21569. ((memq (car elem) org-element-greater-elements)
  21570. (narrow-to-region
  21571. (org-element-property :contents-begin elem)
  21572. (org-element-property :contents-end elem)))
  21573. (t
  21574. (narrow-to-region
  21575. (org-element-property :begin elem)
  21576. (org-element-property :end elem))))))
  21577. (defun org-transpose-element ()
  21578. "Transpose current and previous elements, keeping blank lines between.
  21579. Point is moved after both elements."
  21580. (interactive)
  21581. (org-skip-whitespace)
  21582. (let ((end (org-element-property :end (org-element-at-point))))
  21583. (org-drag-element-backward)
  21584. (goto-char end)))
  21585. (defun org-unindent-buffer ()
  21586. "Un-indent the visible part of the buffer.
  21587. Relative indentation (between items, inside blocks, etc.) isn't
  21588. modified."
  21589. (interactive)
  21590. (unless (eq major-mode 'org-mode)
  21591. (user-error "Cannot un-indent a buffer not in Org mode"))
  21592. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21593. (unindent-tree
  21594. (lambda (contents)
  21595. (dolist (element (reverse contents))
  21596. (if (memq (org-element-type element) '(headline section))
  21597. (funcall unindent-tree (org-element-contents element))
  21598. (save-excursion
  21599. (save-restriction
  21600. (narrow-to-region
  21601. (org-element-property :begin element)
  21602. (org-element-property :end element))
  21603. (org-do-remove-indentation))))))))
  21604. (funcall unindent-tree (org-element-contents parse-tree))))
  21605. (defun org-make-options-regexp (kwds &optional extra)
  21606. "Make a regular expression for keyword lines.
  21607. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21608. when non-nil, is a regexp matching keywords names."
  21609. (concat "^[ \t]*#\\+\\("
  21610. (regexp-opt kwds)
  21611. (and extra (concat (and kwds "\\|") extra))
  21612. "\\):[ \t]*\\(.*\\)"))
  21613. ;;; Finish up
  21614. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21615. (lambda () (add-hook 'change-major-mode-hook
  21616. 'org-show-all 'append 'local)))
  21617. (provide 'org)
  21618. (run-hooks 'org-load-hook)
  21619. ;;; org.el ends here