org.el 897 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.2
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (eval-and-compile (require 'org-macs))
  84. (require 'org-compat)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function 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-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  105. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  106. (declare-function org-archive-subtree-default "org-archive" ())
  107. (declare-function org-archive-to-archive-sibling "org-archive" ())
  108. (declare-function org-attach "org-attach" ())
  109. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  110. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  111. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  112. (declare-function org-clock-cancel "org-clock" ())
  113. (declare-function org-clock-display "org-clock" (&optional arg))
  114. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  115. (declare-function org-clock-goto "org-clock" (&optional select))
  116. (declare-function org-clock-in "org-clock" (&optional select start-time))
  117. (declare-function org-clock-in-last "org-clock" (&optional arg))
  118. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  119. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  120. (declare-function org-clock-report "org-clock" (&optional arg))
  121. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  122. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  123. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  124. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  125. (declare-function org-clock-update-time-maybe "org-clock" ())
  126. (declare-function org-clocking-buffer "org-clock" ())
  127. (declare-function org-clocktable-shift "org-clock" (dir n))
  128. (declare-function org-columns-insert-dblock "org-colview" ())
  129. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  130. (declare-function org-element-at-point "org-element" ())
  131. (declare-function org-element-cache-refresh "org-element" (pos))
  132. (declare-function org-element-cache-reset "org-element" (&optional all))
  133. (declare-function org-element-contents "org-element" (element))
  134. (declare-function org-element-context "org-element" (&optional element))
  135. (declare-function org-element-copy "org-element" (datum))
  136. (declare-function org-element-create "org-element" (type &optional props &rest children))
  137. (declare-function org-element-interpret-data "org-element" (data))
  138. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  139. (declare-function org-element-link-parser "org-element" ())
  140. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  141. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  142. (declare-function org-element-property "org-element" (property element))
  143. (declare-function org-element-put-property "org-element" (element property value))
  144. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  145. (declare-function org-element-timestamp-parser "org-element" ())
  146. (declare-function org-element-type "org-element" (element))
  147. (declare-function org-element-update-syntax "org-element" ())
  148. (declare-function org-export-dispatch "ox" (&optional arg))
  149. (declare-function org-export-get-backend "ox" (name))
  150. (declare-function org-export-get-backend "ox" (name))
  151. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  152. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  153. (declare-function org-feed-goto-inbox "org-feed" (feed))
  154. (declare-function org-feed-update-all "org-feed" ())
  155. (declare-function org-goto "org-goto" (&optional alternative-interface))
  156. (declare-function org-goto "org-goto" (&optional alternative-interface))
  157. (declare-function org-id-find-id-file "org-id" (id))
  158. (declare-function org-id-get-create "org-id" (&optional force))
  159. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  160. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  161. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  162. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  163. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  164. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  165. (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
  166. (declare-function org-table-align "org-table" ())
  167. (declare-function org-table-begin "org-table" (&optional table-type))
  168. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  169. (declare-function org-table-blank-field "org-table" ())
  170. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  171. (declare-function org-table-copy-down "org-table" (N))
  172. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  173. (declare-function org-table-create-or-convert-from-region "org-table" (arg))
  174. (declare-function org-table-create-with-table.el "org-table" ())
  175. (declare-function org-table-cut-region "org-table" (beg end))
  176. (declare-function org-table-edit-field "org-table" (arg))
  177. (declare-function org-table-end "org-table" (&optional table-type))
  178. (declare-function org-table-end-of-field "org-table" (&optional n))
  179. (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
  180. (declare-function org-table-field-info "org-table" (arg))
  181. (declare-function org-table-insert-row "org-table" (&optional arg))
  182. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  183. (declare-function org-table-maybe-eval-formula "org-table" ())
  184. (declare-function org-table-maybe-recalculate-line "org-table" ())
  185. (declare-function org-table-next-row "org-table" ())
  186. (declare-function org-table-paste-rectangle "org-table" ())
  187. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  188. (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
  189. (declare-function org-table-shrink "org-table" (&optional begin end))
  190. (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
  191. (declare-function org-table-sum "org-table" (&optional beg end nlast))
  192. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  193. (declare-function org-table-toggle-coordinate-overlays "org-table" ())
  194. (declare-function org-table-toggle-formula-debugger "org-table" ())
  195. (declare-function org-table-wrap-region "org-table" (arg))
  196. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  197. (declare-function org-timer "org-timer" (&optional restart no-insert))
  198. (declare-function org-timer-item "org-timer" (&optional arg))
  199. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  200. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  201. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  202. (declare-function org-timer-start "org-timer" (&optional offset))
  203. (declare-function org-timer-stop "org-timer" ())
  204. (declare-function org-timer-stop "org-timer" ())
  205. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  206. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  207. (declare-function orgtbl-mode "org-table" (&optional arg))
  208. (defvar ffap-url-regexp)
  209. (defvar org-element-paragraph-separate)
  210. (defvar org-indent-indentation-per-level)
  211. ;; load languages based on value of `org-babel-load-languages'
  212. (defvar org-babel-load-languages)
  213. ;;;###autoload
  214. (defun org-babel-do-load-languages (sym value)
  215. "Load the languages defined in `org-babel-load-languages'."
  216. (set-default sym value)
  217. (dolist (pair org-babel-load-languages)
  218. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  219. (if active
  220. (require (intern (concat "ob-" lang)))
  221. (fmakunbound
  222. (intern (concat "org-babel-execute:" lang)))
  223. (fmakunbound
  224. (intern (concat "org-babel-expand-body:" lang)))))))
  225. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  226. ;;;###autoload
  227. (defun org-babel-load-file (file &optional compile)
  228. "Load Emacs Lisp source code blocks in the Org FILE.
  229. This function exports the source code using `org-babel-tangle'
  230. and then loads the resulting file using `load-file'. With prefix
  231. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  232. file to byte-code before it is loaded."
  233. (interactive "fFile to load: \nP")
  234. (let* ((age (lambda (file)
  235. (float-time
  236. (time-subtract (current-time)
  237. (nth 5 (or (file-attributes (file-truename file))
  238. (file-attributes file)))))))
  239. (base-name (file-name-sans-extension file))
  240. (exported-file (concat base-name ".el")))
  241. ;; tangle if the Org file is newer than the elisp file
  242. (unless (and (file-exists-p exported-file)
  243. (> (funcall age file) (funcall age exported-file)))
  244. ;; Tangle-file traversal returns reversed list of tangled files
  245. ;; and we want to evaluate the first target.
  246. (setq exported-file
  247. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  248. (message "%s %s"
  249. (if compile
  250. (progn (byte-compile-file exported-file 'load)
  251. "Compiled and loaded")
  252. (progn (load-file exported-file) "Loaded"))
  253. exported-file)))
  254. (defcustom org-babel-load-languages '((emacs-lisp . t))
  255. "Languages which can be evaluated in Org buffers.
  256. \\<org-mode-map>
  257. This list can be used to load support for any of the languages
  258. below. Each language will depend on a different set of system
  259. executables and/or Emacs modes.
  260. When a language is \"loaded\", code blocks in that language can
  261. be evaluated with `org-babel-execute-src-block', which is bound
  262. by default to \\[org-ctrl-c-ctrl-c].
  263. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  264. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  265. default, only Emacs Lisp is loaded, since it has no specific
  266. requirement."
  267. :group 'org-babel
  268. :set 'org-babel-do-load-languages
  269. :version "24.1"
  270. :type '(alist :tag "Babel Languages"
  271. :key-type
  272. (choice
  273. (const :tag "Awk" awk)
  274. (const :tag "C" C)
  275. (const :tag "R" R)
  276. (const :tag "Asymptote" asymptote)
  277. (const :tag "Calc" calc)
  278. (const :tag "Clojure" clojure)
  279. (const :tag "CSS" css)
  280. (const :tag "Ditaa" ditaa)
  281. (const :tag "Dot" dot)
  282. (const :tag "Ebnf2ps" ebnf2ps)
  283. (const :tag "Emacs Lisp" emacs-lisp)
  284. (const :tag "Forth" forth)
  285. (const :tag "Fortran" fortran)
  286. (const :tag "Gnuplot" gnuplot)
  287. (const :tag "Haskell" haskell)
  288. (const :tag "hledger" hledger)
  289. (const :tag "IO" io)
  290. (const :tag "J" J)
  291. (const :tag "Java" java)
  292. (const :tag "Javascript" js)
  293. (const :tag "LaTeX" latex)
  294. (const :tag "Ledger" ledger)
  295. (const :tag "Lilypond" lilypond)
  296. (const :tag "Lisp" lisp)
  297. (const :tag "Makefile" makefile)
  298. (const :tag "Maxima" maxima)
  299. (const :tag "Matlab" matlab)
  300. (const :tag "Mscgen" mscgen)
  301. (const :tag "Ocaml" ocaml)
  302. (const :tag "Octave" octave)
  303. (const :tag "Org" org)
  304. (const :tag "Perl" perl)
  305. (const :tag "Pico Lisp" picolisp)
  306. (const :tag "PlantUML" plantuml)
  307. (const :tag "Python" python)
  308. (const :tag "Ruby" ruby)
  309. (const :tag "Sass" sass)
  310. (const :tag "Scala" scala)
  311. (const :tag "Scheme" scheme)
  312. (const :tag "Screen" screen)
  313. (const :tag "Shell Script" shell)
  314. (const :tag "Shen" shen)
  315. (const :tag "Sql" sql)
  316. (const :tag "Sqlite" sqlite)
  317. (const :tag "Stan" stan)
  318. (const :tag "Vala" vala))
  319. :value-type (boolean :tag "Activate" :value t)))
  320. ;;;; Customization variables
  321. (defcustom org-clone-delete-id nil
  322. "Remove ID property of clones of a subtree.
  323. When non-nil, clones of a subtree don't inherit the ID property.
  324. Otherwise they inherit the ID property with a new unique
  325. identifier."
  326. :type 'boolean
  327. :version "24.1"
  328. :group 'org-id)
  329. ;;; Version
  330. (org-check-version)
  331. ;;;###autoload
  332. (defun org-version (&optional here full message)
  333. "Show the Org version.
  334. Interactively, or when MESSAGE is non-nil, show it in echo area.
  335. With prefix argument, or when HERE is non-nil, insert it at point.
  336. In non-interactive uses, a reduced version string is output unless
  337. FULL is given."
  338. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  339. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  340. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  341. (load-suffixes (list ".el"))
  342. (org-install-dir
  343. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  344. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  345. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  346. (let* ((load-suffixes save-load-suffixes)
  347. (release (org-release))
  348. (git-version (org-git-version))
  349. (version (format "Org mode version %s (%s @ %s)"
  350. release
  351. git-version
  352. (if org-install-dir
  353. (if (string= org-dir org-install-dir)
  354. org-install-dir
  355. (concat "mixed installation! "
  356. org-install-dir
  357. " and "
  358. org-dir))
  359. "org-loaddefs.el can not be found!")))
  360. (version1 (if full version release)))
  361. (when here (insert version1))
  362. (when message (message "%s" version1))
  363. version1)))
  364. (defconst org-version (org-version))
  365. ;;; Syntax Constants
  366. ;;;; Block
  367. (defconst org-block-regexp
  368. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  369. "Regular expression for hiding blocks.")
  370. (defconst org-dblock-start-re
  371. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  372. "Matches the start line of a dynamic block, with parameters.")
  373. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  374. "Matches the end of a dynamic block.")
  375. ;;;; Clock and Planning
  376. (defconst org-clock-string "CLOCK:"
  377. "String used as prefix for timestamps clocking work hours on an item.")
  378. (defvar org-closed-string "CLOSED:"
  379. "String used as the prefix for timestamps logging closing a TODO entry.")
  380. (defvar org-deadline-string "DEADLINE:"
  381. "String to mark deadline entries.
  382. \\<org-mode-map>
  383. A deadline is this string, followed by a time stamp. It must be
  384. a word, terminated by a colon. You can insert a schedule keyword
  385. and a timestamp with `\\[org-deadline]'.")
  386. (defvar org-scheduled-string "SCHEDULED:"
  387. "String to mark scheduled TODO entries.
  388. \\<org-mode-map>
  389. A schedule is this string, followed by a time stamp. It must be
  390. a word, terminated by a colon. You can insert a schedule keyword
  391. and a timestamp with `\\[org-schedule]'.")
  392. (defconst org-ds-keyword-length
  393. (+ 2
  394. (apply #'max
  395. (mapcar #'length
  396. (list org-deadline-string org-scheduled-string
  397. org-clock-string org-closed-string))))
  398. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  399. (defconst org-planning-line-re
  400. (concat "^[ \t]*"
  401. (regexp-opt
  402. (list org-closed-string org-deadline-string org-scheduled-string)
  403. t))
  404. "Matches a line with planning info.
  405. Matched keyword is in group 1.")
  406. (defconst org-clock-line-re
  407. (concat "^[ \t]*" org-clock-string)
  408. "Matches a line with clock info.")
  409. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  410. "Matches the DEADLINE keyword.")
  411. (defconst org-deadline-time-regexp
  412. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  413. "Matches the DEADLINE keyword together with a time stamp.")
  414. (defconst org-deadline-time-hour-regexp
  415. (concat "\\<" org-deadline-string
  416. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  417. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  418. (defconst org-deadline-line-regexp
  419. (concat "\\<\\(" org-deadline-string "\\).*")
  420. "Matches the DEADLINE keyword and the rest of the line.")
  421. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  422. "Matches the SCHEDULED keyword.")
  423. (defconst org-scheduled-time-regexp
  424. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  425. "Matches the SCHEDULED keyword together with a time stamp.")
  426. (defconst org-scheduled-time-hour-regexp
  427. (concat "\\<" org-scheduled-string
  428. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  429. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  430. (defconst org-closed-time-regexp
  431. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  432. "Matches the CLOSED keyword together with a time stamp.")
  433. (defconst org-keyword-time-regexp
  434. (concat "\\<"
  435. (regexp-opt
  436. (list org-scheduled-string org-deadline-string org-closed-string
  437. org-clock-string)
  438. t)
  439. " *[[<]\\([^]>]+\\)[]>]")
  440. "Matches any of the 4 keywords, together with the time stamp.")
  441. (defconst org-keyword-time-not-clock-regexp
  442. (concat
  443. "\\<"
  444. (regexp-opt
  445. (list org-scheduled-string org-deadline-string org-closed-string) t)
  446. " *[[<]\\([^]>]+\\)[]>]")
  447. "Matches any of the 3 keywords, together with the time stamp.")
  448. (defconst org-maybe-keyword-time-regexp
  449. (concat "\\(\\<"
  450. (regexp-opt
  451. (list org-scheduled-string org-deadline-string org-closed-string
  452. org-clock-string)
  453. t)
  454. "\\)?"
  455. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  456. "\\|"
  457. "<%%([^\r\n>]*>\\)")
  458. "Matches a timestamp, possibly preceded by a keyword.")
  459. (defconst org-all-time-keywords
  460. (mapcar (lambda (w) (substring w 0 -1))
  461. (list org-scheduled-string org-deadline-string
  462. org-clock-string org-closed-string))
  463. "List of time keywords.")
  464. ;;;; Drawer
  465. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  466. "Matches first or last line of a hidden block.
  467. Group 1 contains drawer's name or \"END\".")
  468. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  469. "Regular expression matching the first line of a property drawer.")
  470. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  471. "Regular expression matching the last line of a property drawer.")
  472. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  473. "Regular expression matching the first line of a clock drawer.")
  474. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  475. "Regular expression matching the last line of a clock drawer.")
  476. (defconst org-property-drawer-re
  477. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  478. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  479. "[ \t]*:END:[ \t]*$")
  480. "Matches an entire property drawer.")
  481. (defconst org-clock-drawer-re
  482. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  483. org-clock-drawer-end-re "\\)\n?")
  484. "Matches an entire clock drawer.")
  485. ;;;; Headline
  486. (defconst org-heading-keyword-regexp-format
  487. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  488. "Printf format for a regexp matching a headline with some keyword.
  489. This regexp will match the headline of any node which has the
  490. exact keyword that is put into the format. The keyword isn't in
  491. any group by default, but the stars and the body are.")
  492. (defconst org-heading-keyword-maybe-regexp-format
  493. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  494. "Printf format for a regexp matching a headline, possibly with some keyword.
  495. This regexp can match any headline with the specified keyword, or
  496. without a keyword. The keyword isn't in any group by default,
  497. but the stars and the body are.")
  498. (defconst org-archive-tag "ARCHIVE"
  499. "The tag that marks a subtree as archived.
  500. An archived subtree does not open during visibility cycling, and does
  501. not contribute to the agenda listings.")
  502. (defconst org-tag-re "[[:alnum:]_@#%]+"
  503. "Regexp matching a single tag.")
  504. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  505. "Regexp matching the tag group at the end of a line, with leading spaces.
  506. Tags are stored in match group 1. Match group 2 stores the tags
  507. without the enclosing colons.")
  508. (defconst org-tag-line-re
  509. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  510. "Regexp matching tags in a headline.
  511. Tags are stored in match group 1. Match group 2 stores the tags
  512. without the enclosing colons.")
  513. (eval-and-compile
  514. (defconst org-comment-string "COMMENT"
  515. "Entries starting with this keyword will never be exported.
  516. \\<org-mode-map>
  517. An entry can be toggled between COMMENT and normal with
  518. `\\[org-toggle-comment]'."))
  519. ;;;; LaTeX Environments and Fragments
  520. (defconst org-latex-regexps
  521. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  522. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  523. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  524. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  525. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  526. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  527. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  528. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  529. "Regular expressions for matching embedded LaTeX.")
  530. ;;;; Node Property
  531. (defconst org-effort-property "Effort"
  532. "The property that is being used to keep track of effort estimates.
  533. Effort estimates given in this property need to have the format H:MM.")
  534. ;;;; Table
  535. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  536. "Detect an org-type or table-type table.")
  537. (defconst org-table-line-regexp "^[ \t]*|"
  538. "Detect an org-type table line.")
  539. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  540. "Detect an org-type table line.")
  541. (defconst org-table-hline-regexp "^[ \t]*|-"
  542. "Detect an org-type table hline.")
  543. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  544. "Detect a table-type table hline.")
  545. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  546. "Detect the first line outside a table when searching from within it.
  547. This works for both table types.")
  548. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  549. "Detect a #+TBLFM line.")
  550. ;;;; Timestamp
  551. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  552. "Regular expression for fast time stamp matching.")
  553. (defconst org-ts-regexp-inactive
  554. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  555. "Regular expression for fast inactive time stamp matching.")
  556. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  557. "Regular expression for fast time stamp matching.")
  558. (defconst org-ts-regexp0
  559. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  560. "Regular expression matching time strings for analysis.
  561. This one does not require the space after the date, so it can be used
  562. on a string that terminates immediately after the date.")
  563. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  564. "Regular expression matching time strings for analysis.")
  565. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  566. "Regular expression matching time stamps, with groups.")
  567. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  568. "Regular expression matching time stamps (also [..]), with groups.")
  569. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  570. "Regular expression matching a time stamp range.")
  571. (defconst org-tr-regexp-both
  572. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  573. "Regular expression matching a time stamp range.")
  574. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  575. org-ts-regexp "\\)?")
  576. "Regular expression matching a time stamp or time stamp range.")
  577. (defconst org-tsr-regexp-both
  578. (concat org-ts-regexp-both "\\(--?-?"
  579. org-ts-regexp-both "\\)?")
  580. "Regular expression matching a time stamp or time stamp range.
  581. The time stamps may be either active or inactive.")
  582. (defconst org-repeat-re
  583. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  584. "Regular expression for specifying repeated events.
  585. After a match, group 1 contains the repeat expression.")
  586. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  587. "Formats for `format-time-string' which are used for time stamps.")
  588. ;;; The custom variables
  589. (defgroup org nil
  590. "Outline-based notes management and organizer."
  591. :tag "Org"
  592. :group 'outlines
  593. :group 'calendar)
  594. (defcustom org-mode-hook nil
  595. "Mode hook for Org mode, run after the mode was turned on."
  596. :group 'org
  597. :type 'hook)
  598. (defcustom org-load-hook nil
  599. "Hook that is run after org.el has been loaded."
  600. :group 'org
  601. :type 'hook)
  602. (defcustom org-log-buffer-setup-hook nil
  603. "Hook that is run after an Org log buffer is created."
  604. :group 'org
  605. :version "24.1"
  606. :type 'hook)
  607. (defvar org-modules) ; defined below
  608. (defvar org-modules-loaded nil
  609. "Have the modules been loaded already?")
  610. (defun org-load-modules-maybe (&optional force)
  611. "Load all extensions listed in `org-modules'."
  612. (when (or force (not org-modules-loaded))
  613. (dolist (ext org-modules)
  614. (condition-case nil (require ext)
  615. (error (message "Problems while trying to load feature `%s'" ext))))
  616. (setq org-modules-loaded t)))
  617. (defun org-set-modules (var value)
  618. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  619. (set var value)
  620. (when (featurep 'org)
  621. (org-load-modules-maybe 'force)
  622. (org-element-cache-reset 'all)))
  623. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
  624. "Modules that should always be loaded together with org.el.
  625. If a description starts with <C>, the file is not part of Emacs
  626. and loading it will require that you have downloaded and properly
  627. installed the Org mode distribution.
  628. You can also use this system to load external packages (i.e. neither Org
  629. core modules, nor modules from the CONTRIB directory). Just add symbols
  630. to the end of the list. If the package is called org-xyz.el, then you need
  631. to add the symbol `xyz', and the package must have a call to:
  632. (provide \\='org-xyz)
  633. For export specific modules, see also `org-export-backends'."
  634. :group 'org
  635. :set 'org-set-modules
  636. :version "26.1"
  637. :package-version '(Org . "9.2")
  638. :type
  639. '(set :greedy t
  640. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  641. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  642. (const :tag " crypt: Encryption of subtrees" org-crypt)
  643. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  644. (const :tag " docview: Links to doc-view buffers" org-docview)
  645. (const :tag " eww: Store link to url of eww" org-eww)
  646. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  647. (const :tag " habit: Track your consistency with habits" org-habit)
  648. (const :tag " id: Global IDs for identifying entries" org-id)
  649. (const :tag " info: Links to Info nodes" org-info)
  650. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  651. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  652. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  653. (const :tag " mouse: Additional mouse support" org-mouse)
  654. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  655. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  656. (const :tag " tempo: Fast completion for structures" org-tempo)
  657. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  658. (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
  659. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  660. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  661. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  662. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  663. (const :tag "C collector: Collect properties into tables" org-collector)
  664. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  665. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  666. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  667. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  668. (const :tag "C eval: Include command output as text" org-eval)
  669. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  670. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  671. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  672. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  673. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  674. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  675. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  676. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  677. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  678. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  679. (const :tag "C notify: Notifications for Org-mode" org-notify)
  680. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  681. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  682. (const :tag "C registry: A registry for Org links" org-registry)
  683. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  684. (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
  685. (const :tag "C secretary: Team management with Org" org-secretary)
  686. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  687. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  688. (const :tag "C track: Keep up with Org mode development" org-track)
  689. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  690. (const :tag "C vm: Links to VM folders/messages" org-vm)
  691. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  692. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  693. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  694. (defvar org-export-registered-backends) ; From ox.el.
  695. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  696. (declare-function org-export-backend-name "ox" (backend) t)
  697. (defcustom org-export-backends '(ascii html icalendar latex odt)
  698. "List of export back-ends that should be always available.
  699. If a description starts with <C>, the file is not part of Emacs
  700. and loading it will require that you have downloaded and properly
  701. installed the Org mode distribution.
  702. Unlike to `org-modules', libraries in this list will not be
  703. loaded along with Org, but only once the export framework is
  704. needed.
  705. This variable needs to be set before org.el is loaded. If you
  706. need to make a change while Emacs is running, use the customize
  707. interface or run the following code, where VAL stands for the new
  708. value of the variable, after updating it:
  709. (progn
  710. (setq org-export-registered-backends
  711. (cl-remove-if-not
  712. (lambda (backend)
  713. (let ((name (org-export-backend-name backend)))
  714. (or (memq name val)
  715. (catch \\='parentp
  716. (dolist (b val)
  717. (and (org-export-derived-backend-p b name)
  718. (throw \\='parentp t)))))))
  719. org-export-registered-backends))
  720. (let ((new-list (mapcar #\\='org-export-backend-name
  721. org-export-registered-backends)))
  722. (dolist (backend val)
  723. (cond
  724. ((not (load (format \"ox-%s\" backend) t t))
  725. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  726. backend))
  727. ((not (memq backend new-list)) (push backend new-list))))
  728. (set-default \\='org-export-backends new-list)))
  729. Adding a back-end to this list will also pull the back-end it
  730. depends on, if any."
  731. :group 'org
  732. :group 'org-export
  733. :version "26.1"
  734. :package-version '(Org . "9.0")
  735. :initialize 'custom-initialize-set
  736. :set (lambda (var val)
  737. (if (not (featurep 'ox)) (set-default var val)
  738. ;; Any back-end not required anymore (not present in VAL and not
  739. ;; a parent of any back-end in the new value) is removed from the
  740. ;; list of registered back-ends.
  741. (setq org-export-registered-backends
  742. (cl-remove-if-not
  743. (lambda (backend)
  744. (let ((name (org-export-backend-name backend)))
  745. (or (memq name val)
  746. (catch 'parentp
  747. (dolist (b val)
  748. (and (org-export-derived-backend-p b name)
  749. (throw 'parentp t)))))))
  750. org-export-registered-backends))
  751. ;; Now build NEW-LIST of both new back-ends and required
  752. ;; parents.
  753. (let ((new-list (mapcar #'org-export-backend-name
  754. org-export-registered-backends)))
  755. (dolist (backend val)
  756. (cond
  757. ((not (load (format "ox-%s" backend) t t))
  758. (message "Problems while trying to load export back-end `%s'"
  759. backend))
  760. ((not (memq backend new-list)) (push backend new-list))))
  761. ;; Set VAR to that list with fixed dependencies.
  762. (set-default var new-list))))
  763. :type '(set :greedy t
  764. (const :tag " ascii Export buffer to ASCII format" ascii)
  765. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  766. (const :tag " html Export buffer to HTML format" html)
  767. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  768. (const :tag " latex Export buffer to LaTeX format" latex)
  769. (const :tag " man Export buffer to MAN format" man)
  770. (const :tag " md Export buffer to Markdown format" md)
  771. (const :tag " odt Export buffer to ODT format" odt)
  772. (const :tag " org Export buffer to Org format" org)
  773. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  774. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  775. (const :tag "C deck Export buffer to deck.js presentations" deck)
  776. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  777. (const :tag "C groff Export buffer to Groff format" groff)
  778. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  779. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  780. (const :tag "C s5 Export buffer to s5 presentations" s5)
  781. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  782. (eval-after-load 'ox
  783. '(dolist (backend org-export-backends)
  784. (condition-case nil (require (intern (format "ox-%s" backend)))
  785. (error (message "Problems while trying to load export back-end `%s'"
  786. backend)))))
  787. (defcustom org-support-shift-select nil
  788. "Non-nil means make shift-cursor commands select text when possible.
  789. \\<org-mode-map>\
  790. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  791. start selecting a region, or enlarge regions started in this way.
  792. In Org mode, in special contexts, these same keys are used for
  793. other purposes, important enough to compete with shift selection.
  794. Org tries to balance these needs by supporting `shift-select-mode'
  795. outside these special contexts, under control of this variable.
  796. The default of this variable is nil, to avoid confusing behavior. Shifted
  797. cursor keys will then execute Org commands in the following contexts:
  798. - on a headline, changing TODO state (left/right) and priority (up/down)
  799. - on a time stamp, changing the time
  800. - in a plain list item, changing the bullet type
  801. - in a property definition line, switching between allowed values
  802. - in the BEGIN line of a clock table (changing the time block).
  803. Outside these contexts, the commands will throw an error.
  804. When this variable is t and the cursor is not in a special
  805. context, Org mode will support shift-selection for making and
  806. enlarging regions. To make this more effective, the bullet
  807. cycling will no longer happen anywhere in an item line, but only
  808. if the cursor is exactly on the bullet.
  809. If you set this variable to the symbol `always', then the keys
  810. will not be special in headlines, property lines, and item lines,
  811. to make shift selection work there as well. If this is what you
  812. want, you can use the following alternative commands:
  813. `\\[org-todo]' and `\\[org-priority]' \
  814. to change TODO state and priority,
  815. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  816. can be used to switch TODO sets,
  817. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  818. and properties can be edited by hand or in column view.
  819. However, when the cursor is on a timestamp, shift-cursor commands
  820. will still edit the time stamp - this is just too good to give up."
  821. :group 'org
  822. :type '(choice
  823. (const :tag "Never" nil)
  824. (const :tag "When outside special context" t)
  825. (const :tag "Everywhere except timestamps" always)))
  826. (defcustom org-loop-over-headlines-in-active-region nil
  827. "Shall some commands act upon headlines in the active region?
  828. When set to t, some commands will be performed in all headlines
  829. within the active region.
  830. When set to `start-level', some commands will be performed in all
  831. headlines within the active region, provided that these headlines
  832. are of the same level than the first one.
  833. When set to a string, those commands will be performed on the
  834. matching headlines within the active region. Such string must be
  835. a tags/property/todo match as it is used in the agenda tags view.
  836. The list of commands is: `org-schedule', `org-deadline',
  837. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  838. `org-archive-to-archive-sibling'. The archiving commands skip
  839. already archived entries."
  840. :type '(choice (const :tag "Don't loop" nil)
  841. (const :tag "All headlines in active region" t)
  842. (const :tag "In active region, headlines at the same level than the first one" start-level)
  843. (string :tag "Tags/Property/Todo matcher"))
  844. :version "24.1"
  845. :group 'org-todo
  846. :group 'org-archive)
  847. (defcustom org-startup-folded t
  848. "Non-nil means entering Org mode will switch to OVERVIEW.
  849. This can also be configured on a per-file basis by adding one of
  850. the following lines anywhere in the buffer:
  851. #+STARTUP: fold (or `overview', this is equivalent)
  852. #+STARTUP: nofold (or `showall', this is equivalent)
  853. #+STARTUP: content
  854. #+STARTUP: showeverything
  855. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  856. to ignore this option when Org opens agenda files for the first
  857. time."
  858. :group 'org-startup
  859. :type '(choice
  860. (const :tag "nofold: show all" nil)
  861. (const :tag "fold: overview" t)
  862. (const :tag "content: all headlines" content)
  863. (const :tag "show everything, even drawers" showeverything)))
  864. (defcustom org-startup-truncated t
  865. "Non-nil means entering Org mode will set `truncate-lines'.
  866. This is useful since some lines containing links can be very long and
  867. uninteresting. Also tables look terrible when wrapped.
  868. The variable `org-startup-truncated' allows to configure
  869. truncation for Org mode different to the other modes that use the
  870. variable `truncate-lines' and as a shortcut instead of putting
  871. the variable `truncate-lines' into the `org-mode-hook'. If one
  872. wants to configure truncation for Org mode not statically but
  873. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  874. the variable `truncate-lines' has to be used because in such a
  875. case it is too late to set the variable `org-startup-truncated'."
  876. :group 'org-startup
  877. :type 'boolean)
  878. (defcustom org-startup-indented nil
  879. "Non-nil means turn on `org-indent-mode' on startup.
  880. This can also be configured on a per-file basis by adding one of
  881. the following lines anywhere in the buffer:
  882. #+STARTUP: indent
  883. #+STARTUP: noindent"
  884. :group 'org-structure
  885. :type '(choice
  886. (const :tag "Not" nil)
  887. (const :tag "Globally (slow on startup in large files)" t)))
  888. (defcustom org-use-sub-superscripts t
  889. "Non-nil means interpret \"_\" and \"^\" for display.
  890. If you want to control how Org exports those characters, see
  891. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  892. used to be an alias for `org-export-with-sub-superscripts' in
  893. Org <8.0, it is not anymore.
  894. When this option is turned on, you can use TeX-like syntax for
  895. sub- and superscripts within the buffer. Several characters after
  896. \"_\" or \"^\" will be considered as a single item - so grouping
  897. with {} is normally not needed. For example, the following things
  898. will be parsed as single sub- or superscripts:
  899. 10^24 or 10^tau several digits will be considered 1 item.
  900. 10^-12 or 10^-tau a leading sign with digits or a word
  901. x^2-y^3 will be read as x^2 - y^3, because items are
  902. terminated by almost any nonword/nondigit char.
  903. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  904. Still, ambiguity is possible. So when in doubt, use {} to enclose
  905. the sub/superscript. If you set this variable to the symbol `{}',
  906. the braces are *required* in order to trigger interpretations as
  907. sub/superscript. This can be helpful in documents that need \"_\"
  908. frequently in plain text."
  909. :group 'org-startup
  910. :version "24.4"
  911. :package-version '(Org . "8.0")
  912. :type '(choice
  913. (const :tag "Always interpret" t)
  914. (const :tag "Only with braces" {})
  915. (const :tag "Never interpret" nil)))
  916. (defcustom org-startup-with-beamer-mode nil
  917. "Non-nil means turn on `org-beamer-mode' on startup.
  918. This can also be configured on a per-file basis by adding one of
  919. the following lines anywhere in the buffer:
  920. #+STARTUP: beamer"
  921. :group 'org-startup
  922. :version "24.1"
  923. :type 'boolean)
  924. (defcustom org-startup-align-all-tables nil
  925. "Non-nil means align all tables when visiting a file.
  926. This can also be configured on a per-file basis by adding one of
  927. the following lines anywhere in the buffer:
  928. #+STARTUP: align
  929. #+STARTUP: noalign"
  930. :group 'org-startup
  931. :type 'boolean)
  932. (defcustom org-startup-shrink-all-tables nil
  933. "Non-nil means shrink all table columns with a width cookie.
  934. This can also be configured on a per-file basis by adding one of
  935. the following lines anywhere in the buffer:
  936. #+STARTUP: shrink"
  937. :group 'org-startup
  938. :type 'boolean
  939. :version "27.1"
  940. :package-version '(Org . "9.2")
  941. :safe #'booleanp)
  942. (defcustom org-startup-with-inline-images nil
  943. "Non-nil means show inline images when loading a new Org file.
  944. This can also be configured on a per-file basis by adding one of
  945. the following lines anywhere in the buffer:
  946. #+STARTUP: inlineimages
  947. #+STARTUP: noinlineimages"
  948. :group 'org-startup
  949. :version "24.1"
  950. :type 'boolean)
  951. (defcustom org-startup-with-latex-preview nil
  952. "Non-nil means preview LaTeX fragments when loading a new Org file.
  953. This can also be configured on a per-file basis by adding one of
  954. the following lines anywhere in the buffer:
  955. #+STARTUP: latexpreview
  956. #+STARTUP: nolatexpreview"
  957. :group 'org-startup
  958. :version "24.4"
  959. :package-version '(Org . "8.0")
  960. :type 'boolean)
  961. (defcustom org-insert-mode-line-in-empty-file nil
  962. "Non-nil means insert the first line setting Org mode in empty files.
  963. When the function `org-mode' is called interactively in an empty file, this
  964. normally means that the file name does not automatically trigger Org mode.
  965. To ensure that the file will always be in Org mode in the future, a
  966. line enforcing Org mode will be inserted into the buffer, if this option
  967. has been set."
  968. :group 'org-startup
  969. :type 'boolean)
  970. (defcustom org-replace-disputed-keys nil
  971. "Non-nil means use alternative key bindings for some keys.
  972. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  973. These keys are also used by other packages like Shift Select mode,
  974. CUA mode or Windmove. If you want to use Org mode together with
  975. one of these other modes, or more generally if you would like to
  976. move some Org mode commands to other keys, set this variable and
  977. configure the keys with the variable `org-disputed-keys'.
  978. This option is only relevant at load-time of Org mode, and must be set
  979. *before* org.el is loaded. Changing it requires a restart of Emacs to
  980. become effective."
  981. :group 'org-startup
  982. :type 'boolean)
  983. (defcustom org-use-extra-keys nil
  984. "Non-nil means use extra key sequence definitions for certain commands.
  985. This happens automatically if `window-system' is nil. This
  986. variable lets you do the same manually. You must set it before
  987. loading Org."
  988. :group 'org-startup
  989. :type 'boolean)
  990. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  991. (defcustom org-disputed-keys
  992. '(([(shift up)] . [(meta p)])
  993. ([(shift down)] . [(meta n)])
  994. ([(shift left)] . [(meta -)])
  995. ([(shift right)] . [(meta +)])
  996. ([(control shift right)] . [(meta shift +)])
  997. ([(control shift left)] . [(meta shift -)]))
  998. "Keys for which Org mode and other modes compete.
  999. This is an alist, cars are the default keys, second element specifies
  1000. the alternative to use when `org-replace-disputed-keys' is t.
  1001. Keys can be specified in any syntax supported by `define-key'.
  1002. The value of this option takes effect only at Org mode startup,
  1003. therefore you'll have to restart Emacs to apply it after changing."
  1004. :group 'org-startup
  1005. :type 'alist)
  1006. (defun org-key (key)
  1007. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  1008. Or return the original if not disputed."
  1009. (when org-replace-disputed-keys
  1010. (let* ((nkey (key-description key))
  1011. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  1012. org-disputed-keys)))
  1013. (setq key (if x (cdr x) key))))
  1014. key)
  1015. (defun org-defkey (keymap key def)
  1016. "Define a key, possibly translated, as returned by `org-key'."
  1017. (define-key keymap (org-key key) def))
  1018. (defcustom org-ellipsis nil
  1019. "The ellipsis to use in the Org mode outline.
  1020. When nil, just use the standard three dots. When a non-empty string,
  1021. use that string instead.
  1022. The change affects only Org mode (which will then use its own display table).
  1023. Changing this requires executing `\\[org-mode]' in a buffer to become
  1024. effective."
  1025. :group 'org-startup
  1026. :type '(choice (const :tag "Default" nil)
  1027. (string :tag "String" :value "...#"))
  1028. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  1029. (defvar org-display-table nil
  1030. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  1031. (defgroup org-keywords nil
  1032. "Keywords in Org mode."
  1033. :tag "Org Keywords"
  1034. :group 'org)
  1035. (defcustom org-closed-keep-when-no-todo nil
  1036. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1037. :group 'org-todo
  1038. :group 'org-keywords
  1039. :version "24.4"
  1040. :package-version '(Org . "8.0")
  1041. :type 'boolean)
  1042. (defgroup org-structure nil
  1043. "Options concerning the general structure of Org files."
  1044. :tag "Org Structure"
  1045. :group 'org)
  1046. (defgroup org-reveal-location nil
  1047. "Options about how to make context of a location visible."
  1048. :tag "Org Reveal Location"
  1049. :group 'org-structure)
  1050. (defcustom org-show-context-detail '((agenda . local)
  1051. (bookmark-jump . lineage)
  1052. (isearch . lineage)
  1053. (default . ancestors))
  1054. "Alist between context and visibility span when revealing a location.
  1055. \\<org-mode-map>Some actions may move point into invisible
  1056. locations. As a consequence, Org always expose a neighborhood
  1057. around point. How much is shown depends on the initial action,
  1058. or context. Valid contexts are
  1059. agenda when exposing an entry from the agenda
  1060. org-goto when using the command `org-goto' (`\\[org-goto]')
  1061. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1062. tags-tree when constructing a sparse tree based on tags matches
  1063. link-search when exposing search matches associated with a link
  1064. mark-goto when exposing the jump goal of a mark
  1065. bookmark-jump when exposing a bookmark location
  1066. isearch when exiting from an incremental search
  1067. default default for all contexts not set explicitly
  1068. Allowed visibility spans are
  1069. minimal show current headline; if point is not on headline,
  1070. also show entry
  1071. local show current headline, entry and next headline
  1072. ancestors show current headline and its direct ancestors; if
  1073. point is not on headline, also show entry
  1074. lineage show current headline, its direct ancestors and all
  1075. their children; if point is not on headline, also show
  1076. entry and first child
  1077. tree show current headline, its direct ancestors and all
  1078. their children; if point is not on headline, also show
  1079. entry and all children
  1080. canonical show current headline, its direct ancestors along with
  1081. their entries and children; if point is not located on
  1082. the headline, also show current entry and all children
  1083. As special cases, a nil or t value means show all contexts in
  1084. `minimal' or `canonical' view, respectively.
  1085. Some views can make displayed information very compact, but also
  1086. make it harder to edit the location of the match. In such
  1087. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1088. more context."
  1089. :group 'org-reveal-location
  1090. :version "26.1"
  1091. :package-version '(Org . "9.0")
  1092. :type '(choice
  1093. (const :tag "Canonical" t)
  1094. (const :tag "Minimal" nil)
  1095. (repeat :greedy t :tag "Individual contexts"
  1096. (cons
  1097. (choice :tag "Context"
  1098. (const agenda)
  1099. (const org-goto)
  1100. (const occur-tree)
  1101. (const tags-tree)
  1102. (const link-search)
  1103. (const mark-goto)
  1104. (const bookmark-jump)
  1105. (const isearch)
  1106. (const default))
  1107. (choice :tag "Detail level"
  1108. (const minimal)
  1109. (const local)
  1110. (const ancestors)
  1111. (const lineage)
  1112. (const tree)
  1113. (const canonical))))))
  1114. (defcustom org-indirect-buffer-display 'other-window
  1115. "How should indirect tree buffers be displayed?
  1116. This applies to indirect buffers created with the commands
  1117. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1118. Valid values are:
  1119. current-window Display in the current window
  1120. other-window Just display in another window.
  1121. dedicated-frame Create one new frame, and re-use it each time.
  1122. new-frame Make a new frame each time. Note that in this case
  1123. previously-made indirect buffers are kept, and you need to
  1124. kill these buffers yourself."
  1125. :group 'org-structure
  1126. :group 'org-agenda-windows
  1127. :type '(choice
  1128. (const :tag "In current window" current-window)
  1129. (const :tag "In current frame, other window" other-window)
  1130. (const :tag "Each time a new frame" new-frame)
  1131. (const :tag "One dedicated frame" dedicated-frame)))
  1132. (defcustom org-use-speed-commands nil
  1133. "Non-nil means activate single letter commands at beginning of a headline.
  1134. This may also be a function to test for appropriate locations where speed
  1135. commands should be active.
  1136. For example, to activate speed commands when the point is on any
  1137. star at the beginning of the headline, you can do this:
  1138. (setq org-use-speed-commands
  1139. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1140. :group 'org-structure
  1141. :type '(choice
  1142. (const :tag "Never" nil)
  1143. (const :tag "At beginning of headline stars" t)
  1144. (function)))
  1145. (defcustom org-speed-commands-user nil
  1146. "Alist of additional speed commands.
  1147. This list will be checked before `org-speed-commands-default'
  1148. when the variable `org-use-speed-commands' is non-nil
  1149. and when the cursor is at the beginning of a headline.
  1150. The car of each entry is a string with a single letter, which must
  1151. be assigned to `self-insert-command' in the global map.
  1152. The cdr is either a command to be called interactively, a function
  1153. to be called, or a form to be evaluated.
  1154. An entry that is just a list with a single string will be interpreted
  1155. as a descriptive headline that will be added when listing the speed
  1156. commands in the Help buffer using the `?' speed command."
  1157. :group 'org-structure
  1158. :type '(repeat :value ("k" . ignore)
  1159. (choice :value ("k" . ignore)
  1160. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1161. (cons :tag "Letter and Command"
  1162. (string :tag "Command letter")
  1163. (choice
  1164. (function)
  1165. (sexp))))))
  1166. (defcustom org-bookmark-names-plist
  1167. '(:last-capture "org-capture-last-stored"
  1168. :last-refile "org-refile-last-stored"
  1169. :last-capture-marker "org-capture-last-stored-marker")
  1170. "Names for bookmarks automatically set by some Org commands.
  1171. This can provide strings as names for a number of bookmarks Org sets
  1172. automatically. The following keys are currently implemented:
  1173. :last-capture
  1174. :last-capture-marker
  1175. :last-refile
  1176. When a key does not show up in the property list, the corresponding bookmark
  1177. is not set."
  1178. :group 'org-structure
  1179. :type 'plist)
  1180. (defgroup org-cycle nil
  1181. "Options concerning visibility cycling in Org mode."
  1182. :tag "Org Cycle"
  1183. :group 'org-structure)
  1184. (defcustom org-cycle-skip-children-state-if-no-children t
  1185. "Non-nil means skip CHILDREN state in entries that don't have any."
  1186. :group 'org-cycle
  1187. :type 'boolean)
  1188. (defcustom org-cycle-max-level nil
  1189. "Maximum level which should still be subject to visibility cycling.
  1190. Levels higher than this will, for cycling, be treated as text, not a headline.
  1191. When `org-odd-levels-only' is set, a value of N in this variable actually
  1192. means 2N-1 stars as the limiting headline.
  1193. When nil, cycle all levels.
  1194. Note that the limiting level of cycling is also influenced by
  1195. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1196. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1197. than its value."
  1198. :group 'org-cycle
  1199. :type '(choice
  1200. (const :tag "No limit" nil)
  1201. (integer :tag "Maximum level")))
  1202. (defcustom org-hide-block-startup nil
  1203. "Non-nil means entering Org mode will fold all blocks.
  1204. This can also be set in on a per-file basis with
  1205. #+STARTUP: hideblocks
  1206. #+STARTUP: showblocks"
  1207. :group 'org-startup
  1208. :group 'org-cycle
  1209. :type 'boolean)
  1210. (defcustom org-cycle-global-at-bob nil
  1211. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1212. This makes it possible to do global cycling without having to use `S-TAB'
  1213. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1214. line of the buffer
  1215. must not be a headline -- it may be empty or some other text.
  1216. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1217. sure the cursor stays at the beginning of the buffer.
  1218. When this option is nil, don't do anything special at the beginning of
  1219. the buffer."
  1220. :group 'org-cycle
  1221. :type 'boolean)
  1222. (defcustom org-cycle-level-after-item/entry-creation t
  1223. "Non-nil means cycle entry level or item indentation in new empty entries.
  1224. When the cursor is at the end of an empty headline, i.e., with only stars
  1225. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1226. and then all possible ancestor states, before returning to the original state.
  1227. This makes data entry extremely fast: M-RET to create a new headline,
  1228. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1229. When the cursor is at the end of an empty plain list item, one TAB will
  1230. make it a subitem, two or more tabs will back up to make this an item
  1231. higher up in the item hierarchy."
  1232. :group 'org-cycle
  1233. :type 'boolean)
  1234. (defcustom org-cycle-emulate-tab t
  1235. "Where should `org-cycle' emulate TAB.
  1236. nil Never
  1237. white Only in completely white lines
  1238. whitestart Only at the beginning of lines, before the first non-white char
  1239. t Everywhere except in headlines
  1240. exc-hl-bol Everywhere except at the start of a headline
  1241. If TAB is used in a place where it does not emulate TAB, the current subtree
  1242. visibility is cycled."
  1243. :group 'org-cycle
  1244. :type '(choice (const :tag "Never" nil)
  1245. (const :tag "Only in completely white lines" white)
  1246. (const :tag "Before first char in a line" whitestart)
  1247. (const :tag "Everywhere except in headlines" t)
  1248. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1249. (defcustom org-cycle-separator-lines 2
  1250. "Number of empty lines needed to keep an empty line between collapsed trees.
  1251. If you leave an empty line between the end of a subtree and the following
  1252. headline, this empty line is hidden when the subtree is folded.
  1253. Org mode will leave (exactly) one empty line visible if the number of
  1254. empty lines is equal or larger to the number given in this variable.
  1255. So the default 2 means at least 2 empty lines after the end of a subtree
  1256. are needed to produce free space between a collapsed subtree and the
  1257. following headline.
  1258. If the number is negative, and the number of empty lines is at least -N,
  1259. all empty lines are shown.
  1260. Special case: when 0, never leave empty lines in collapsed view."
  1261. :group 'org-cycle
  1262. :type 'integer)
  1263. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1264. (defcustom org-pre-cycle-hook nil
  1265. "Hook that is run before visibility cycling is happening.
  1266. The function(s) in this hook must accept a single argument which indicates
  1267. the new state that will be set right after running this hook. The
  1268. argument is a symbol. Before a global state change, it can have the values
  1269. `overview', `content', or `all'. Before a local state change, it can have
  1270. the values `folded', `children', or `subtree'."
  1271. :group 'org-cycle
  1272. :type 'hook)
  1273. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1274. org-cycle-show-empty-lines
  1275. org-optimize-window-after-visibility-change)
  1276. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1277. The function(s) in this hook must accept a single argument which indicates
  1278. the new state that was set by the most recent `org-cycle' command. The
  1279. argument is a symbol. After a global state change, it can have the values
  1280. `overview', `contents', or `all'. After a local state change, it can have
  1281. the values `folded', `children', or `subtree'."
  1282. :group 'org-cycle
  1283. :type 'hook
  1284. :version "26.1"
  1285. :package-version '(Org . "8.3"))
  1286. (defgroup org-edit-structure nil
  1287. "Options concerning structure editing in Org mode."
  1288. :tag "Org Edit Structure"
  1289. :group 'org-structure)
  1290. (defcustom org-odd-levels-only nil
  1291. "Non-nil means skip even levels and only use odd levels for the outline.
  1292. This has the effect that two stars are being added/taken away in
  1293. promotion/demotion commands. It also influences how levels are
  1294. handled by the exporters.
  1295. Changing it requires restart of `font-lock-mode' to become effective
  1296. for fontification also in regions already fontified.
  1297. You may also set this on a per-file basis by adding one of the following
  1298. lines to the buffer:
  1299. #+STARTUP: odd
  1300. #+STARTUP: oddeven"
  1301. :group 'org-edit-structure
  1302. :group 'org-appearance
  1303. :type 'boolean)
  1304. (defcustom org-adapt-indentation t
  1305. "Non-nil means adapt indentation to outline node level.
  1306. When this variable is set, Org assumes that you write outlines by
  1307. indenting text in each node to align with the headline (after the
  1308. stars). The following issues are influenced by this variable:
  1309. - The indentation is increased by one space in a demotion
  1310. command, and decreased by one in a promotion command. However,
  1311. in the latter case, if shifting some line in the entry body
  1312. would alter document structure (e.g., insert a new headline),
  1313. indentation is not changed at all.
  1314. - Property drawers and planning information is inserted indented
  1315. when this variable is set. When nil, they will not be indented.
  1316. - TAB indents a line relative to current level. The lines below
  1317. a headline will be indented when this variable is set.
  1318. Note that this is all about true indentation, by adding and
  1319. removing space characters. See also \"org-indent.el\" which does
  1320. level-dependent indentation in a virtual way, i.e. at display
  1321. time in Emacs."
  1322. :group 'org-edit-structure
  1323. :type 'boolean
  1324. :safe #'booleanp)
  1325. (defcustom org-special-ctrl-a/e nil
  1326. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1327. When t, `C-a' will bring back the cursor to the beginning of the
  1328. headline text, i.e. after the stars and after a possible TODO
  1329. keyword. In an item, this will be the position after bullet and
  1330. check-box, if any. When the cursor is already at that position,
  1331. another `C-a' will bring it to the beginning of the line.
  1332. `C-e' will jump to the end of the headline, ignoring the presence
  1333. of tags in the headline. A second `C-e' will then jump to the
  1334. true end of the line, after any tags. This also means that, when
  1335. this variable is non-nil, `C-e' also will never jump beyond the
  1336. end of the heading of a folded section, i.e. not after the
  1337. ellipses.
  1338. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1339. normally, going to the true line boundary first. Only a directly
  1340. following, identical keypress will bring the cursor to the
  1341. special positions.
  1342. This may also be a cons cell where the behavior for `C-a' and
  1343. `C-e' is set separately."
  1344. :group 'org-edit-structure
  1345. :type '(choice
  1346. (const :tag "off" nil)
  1347. (const :tag "on: after stars/bullet and before tags first" t)
  1348. (const :tag "reversed: true line boundary first" reversed)
  1349. (cons :tag "Set C-a and C-e separately"
  1350. (choice :tag "Special C-a"
  1351. (const :tag "off" nil)
  1352. (const :tag "on: after stars/bullet first" t)
  1353. (const :tag "reversed: before stars/bullet first" reversed))
  1354. (choice :tag "Special C-e"
  1355. (const :tag "off" nil)
  1356. (const :tag "on: before tags first" t)
  1357. (const :tag "reversed: after tags first" reversed)))))
  1358. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1359. (defcustom org-special-ctrl-k nil
  1360. "Non-nil means `C-k' will behave specially in headlines.
  1361. When nil, `C-k' will call the default `kill-line' command.
  1362. When t, the following will happen while the cursor is in the headline:
  1363. - When the cursor is at the beginning of a headline, kill the entire
  1364. line and possible the folded subtree below the line.
  1365. - When in the middle of the headline text, kill the headline up to the tags.
  1366. - When after the headline text, kill the tags."
  1367. :group 'org-edit-structure
  1368. :type 'boolean)
  1369. (defcustom org-ctrl-k-protect-subtree nil
  1370. "Non-nil means, do not delete a hidden subtree with C-k.
  1371. When set to the symbol `error', simply throw an error when C-k is
  1372. used to kill (part-of) a headline that has hidden text behind it.
  1373. Any other non-nil value will result in a query to the user, if it is
  1374. OK to kill that hidden subtree. When nil, kill without remorse."
  1375. :group 'org-edit-structure
  1376. :version "24.1"
  1377. :type '(choice
  1378. (const :tag "Do not protect hidden subtrees" nil)
  1379. (const :tag "Protect hidden subtrees with a security query" t)
  1380. (const :tag "Never kill a hidden subtree with C-k" error)))
  1381. (defcustom org-special-ctrl-o t
  1382. "Non-nil means, make `C-o' insert a row in tables."
  1383. :group 'org-edit-structure
  1384. :type 'boolean)
  1385. (defcustom org-catch-invisible-edits nil
  1386. "Check if in invisible region before inserting or deleting a character.
  1387. Valid values are:
  1388. nil Do not check, so just do invisible edits.
  1389. error Throw an error and do nothing.
  1390. show Make point visible, and do the requested edit.
  1391. show-and-error Make point visible, then throw an error and abort the edit.
  1392. smart Make point visible, and do insertion/deletion if it is
  1393. adjacent to visible text and the change feels predictable.
  1394. Never delete a previously invisible character or add in the
  1395. middle or right after an invisible region. Basically, this
  1396. allows insertion and backward-delete right before ellipses.
  1397. FIXME: maybe in this case we should not even show?"
  1398. :group 'org-edit-structure
  1399. :version "24.1"
  1400. :type '(choice
  1401. (const :tag "Do not check" nil)
  1402. (const :tag "Throw error when trying to edit" error)
  1403. (const :tag "Unhide, but do not do the edit" show-and-error)
  1404. (const :tag "Show invisible part and do the edit" show)
  1405. (const :tag "Be smart and do the right thing" smart)))
  1406. (defcustom org-yank-folded-subtrees t
  1407. "Non-nil means when yanking subtrees, fold them.
  1408. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1409. it starts with a heading and all other headings in it are either children
  1410. or siblings, then fold all the subtrees. However, do this only if no
  1411. text after the yank would be swallowed into a folded tree by this action."
  1412. :group 'org-edit-structure
  1413. :type 'boolean)
  1414. (defcustom org-yank-adjusted-subtrees nil
  1415. "Non-nil means when yanking subtrees, adjust the level.
  1416. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1417. this function for details."
  1418. :group 'org-edit-structure
  1419. :type 'boolean)
  1420. (defcustom org-M-RET-may-split-line '((default . t))
  1421. "Non-nil means M-RET will split the line at the cursor position.
  1422. When nil, it will go to the end of the line before making a
  1423. new line.
  1424. You may also set this option in a different way for different
  1425. contexts. Valid contexts are:
  1426. headline when creating a new headline
  1427. item when creating a new item
  1428. table in a table field
  1429. default the value to be used for all contexts not explicitly
  1430. customized"
  1431. :group 'org-structure
  1432. :group 'org-table
  1433. :type '(choice
  1434. (const :tag "Always" t)
  1435. (const :tag "Never" nil)
  1436. (repeat :greedy t :tag "Individual contexts"
  1437. (cons
  1438. (choice :tag "Context"
  1439. (const headline)
  1440. (const item)
  1441. (const table)
  1442. (const default))
  1443. (boolean)))))
  1444. (defcustom org-insert-heading-respect-content nil
  1445. "Non-nil means insert new headings after the current subtree.
  1446. \\<org-mode-map>
  1447. When nil, the new heading is created directly after the current line.
  1448. The commands `\\[org-insert-heading-respect-content]' and \
  1449. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1450. for the duration of the command."
  1451. :group 'org-structure
  1452. :type 'boolean)
  1453. (defcustom org-blank-before-new-entry '((heading . auto)
  1454. (plain-list-item . auto))
  1455. "Should `org-insert-heading' leave a blank line before new heading/item?
  1456. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1457. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1458. which case Org will look at the surrounding headings/items and try to
  1459. make an intelligent decision whether to insert a blank line or not."
  1460. :group 'org-edit-structure
  1461. :type '(list
  1462. (cons (const heading)
  1463. (choice (const :tag "Never" nil)
  1464. (const :tag "Always" t)
  1465. (const :tag "Auto" auto)))
  1466. (cons (const plain-list-item)
  1467. (choice (const :tag "Never" nil)
  1468. (const :tag "Always" t)
  1469. (const :tag "Auto" auto)))))
  1470. (defcustom org-insert-heading-hook nil
  1471. "Hook being run after inserting a new heading."
  1472. :group 'org-edit-structure
  1473. :type 'hook)
  1474. (defcustom org-enable-fixed-width-editor t
  1475. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1476. This currently only means they are never auto-wrapped.
  1477. When nil, such lines will be treated like ordinary lines."
  1478. :group 'org-edit-structure
  1479. :type 'boolean)
  1480. (defgroup org-sparse-trees nil
  1481. "Options concerning sparse trees in Org mode."
  1482. :tag "Org Sparse Trees"
  1483. :group 'org-structure)
  1484. (defcustom org-highlight-sparse-tree-matches t
  1485. "Non-nil means highlight all matches that define a sparse tree.
  1486. The highlights will automatically disappear the next time the buffer is
  1487. changed by an edit command."
  1488. :group 'org-sparse-trees
  1489. :type 'boolean)
  1490. (defcustom org-remove-highlights-with-change t
  1491. "Non-nil means any change to the buffer will remove temporary highlights.
  1492. \\<org-mode-map>\
  1493. Such highlights are created by `org-occur' and `org-clock-display'.
  1494. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1495. to get rid of the highlights.
  1496. The highlights created by `org-toggle-latex-fragment' always need
  1497. `\\[org-toggle-latex-fragment]' to be removed."
  1498. :group 'org-sparse-trees
  1499. :group 'org-time
  1500. :type 'boolean)
  1501. (defcustom org-occur-case-fold-search t
  1502. "Non-nil means `org-occur' should be case-insensitive.
  1503. If set to `smart' the search will be case-insensitive only if it
  1504. doesn't specify any upper case character."
  1505. :group 'org-sparse-trees
  1506. :version "26.1"
  1507. :type '(choice
  1508. (const :tag "Case-sensitive" nil)
  1509. (const :tag "Case-insensitive" t)
  1510. (const :tag "Case-insensitive for lower case searches only" smart)))
  1511. (defcustom org-occur-hook '(org-first-headline-recenter)
  1512. "Hook that is run after `org-occur' has constructed a sparse tree.
  1513. This can be used to recenter the window to show as much of the structure
  1514. as possible."
  1515. :group 'org-sparse-trees
  1516. :type 'hook)
  1517. (defgroup org-table nil
  1518. "Options concerning tables in Org mode."
  1519. :tag "Org Table"
  1520. :group 'org)
  1521. (defcustom org-self-insert-cluster-for-undo nil
  1522. "Non-nil means cluster self-insert commands for undo when possible.
  1523. If this is set, then, like in the Emacs command loop, 20 consecutive
  1524. characters will be undone together.
  1525. This is configurable, because there is some impact on typing performance."
  1526. :group 'org-table
  1527. :type 'boolean)
  1528. (defcustom org-table-tab-recognizes-table.el t
  1529. "Non-nil means TAB will automatically notice a table.el table.
  1530. When it sees such a table, it moves point into it and - if necessary -
  1531. calls `table-recognize-table'."
  1532. :group 'org-table-editing
  1533. :type 'boolean)
  1534. (defgroup org-link nil
  1535. "Options concerning links in Org mode."
  1536. :tag "Org Link"
  1537. :group 'org)
  1538. (defvar-local org-link-abbrev-alist-local nil
  1539. "Buffer-local version of `org-link-abbrev-alist', which see.
  1540. The value of this is taken from the #+LINK lines.")
  1541. (defcustom org-link-parameters
  1542. '(("doi" :follow org--open-doi-link)
  1543. ("elisp" :follow org--open-elisp-link)
  1544. ("file" :complete org-file-complete-link)
  1545. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1546. ("help" :follow org--open-help-link)
  1547. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1548. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1549. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1550. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1551. ("shell" :follow org--open-shell-link))
  1552. "An alist of properties that defines all the links in Org mode.
  1553. The key in each association is a string of the link type.
  1554. Subsequent optional elements make up a p-list of link properties.
  1555. :follow - A function that takes the link path as an argument.
  1556. :export - A function that takes the link path, description and
  1557. export-backend as arguments.
  1558. :store - A function responsible for storing the link. See the
  1559. function `org-store-link-functions'.
  1560. :complete - A function that inserts a link with completion. The
  1561. function takes one optional prefix arg.
  1562. :face - A face for the link, or a function that returns a face.
  1563. The function takes one argument which is the link path. The
  1564. default face is `org-link'.
  1565. :mouse-face - The mouse-face. The default is `highlight'.
  1566. :display - `full' will not fold the link in descriptive
  1567. display. Default is `org-link'.
  1568. :help-echo - A string or function that takes (window object position)
  1569. as arguments and returns a string.
  1570. :keymap - A keymap that is active on the link. The default is
  1571. `org-mouse-map'.
  1572. :htmlize-link - A function for the htmlize-link. Defaults
  1573. to (list :uri \"type:path\")
  1574. :activate-func - A function to run at the end of font-lock
  1575. activation. The function must accept (link-start link-end path bracketp)
  1576. as arguments."
  1577. :group 'org-link
  1578. :type '(alist :tag "Link display parameters"
  1579. :value-type plist)
  1580. :version "26.1"
  1581. :package-version '(Org . "9.1"))
  1582. (defun org-link-get-parameter (type key)
  1583. "Get TYPE link property for KEY.
  1584. TYPE is a string and KEY is a plist keyword."
  1585. (plist-get
  1586. (cdr (assoc type org-link-parameters))
  1587. key))
  1588. (defun org-link-set-parameters (type &rest parameters)
  1589. "Set link TYPE properties to PARAMETERS.
  1590. PARAMETERS should be :key val pairs."
  1591. (let ((data (assoc type org-link-parameters)))
  1592. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1593. (push (cons type parameters) org-link-parameters)
  1594. (org-make-link-regexps)
  1595. (org-element-update-syntax))))
  1596. (defun org-link-types ()
  1597. "Return a list of known link types."
  1598. (mapcar #'car org-link-parameters))
  1599. (defcustom org-link-abbrev-alist nil
  1600. "Alist of link abbreviations.
  1601. The car of each element is a string, to be replaced at the start of a link.
  1602. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1603. links in Org buffers can have an optional tag after a double colon, e.g.,
  1604. [[linkkey:tag][description]]
  1605. The `linkkey' must be a single word, starting with a letter, followed
  1606. by letters, numbers, `-' or `_'.
  1607. If REPLACE is a string, the tag will simply be appended to create the link.
  1608. If the string contains \"%s\", the tag will be inserted there. If the string
  1609. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1610. at that point (see the function `url-hexify-string'). If the string contains
  1611. the specifier \"%(my-function)\", then the custom function `my-function' will
  1612. be invoked: this function takes the tag as its only argument and must return
  1613. a string.
  1614. REPLACE may also be a function that will be called with the tag as the
  1615. only argument to create the link, which should be returned as a string.
  1616. See the manual for examples."
  1617. :group 'org-link
  1618. :type '(repeat
  1619. (cons
  1620. (string :tag "Protocol")
  1621. (choice
  1622. (string :tag "Format")
  1623. (function)))))
  1624. (defcustom org-descriptive-links t
  1625. "Non-nil means Org will display descriptive links.
  1626. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1627. \"Org Website\", hiding the link itself and just displaying its
  1628. description. When set to nil, Org will display the full links
  1629. literally.
  1630. You can interactively set the value of this variable by calling
  1631. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1632. :group 'org-link
  1633. :type 'boolean)
  1634. (defcustom org-link-file-path-type 'adaptive
  1635. "How the path name in file links should be stored.
  1636. Valid values are:
  1637. relative Relative to the current directory, i.e. the directory of the file
  1638. into which the link is being inserted.
  1639. absolute Absolute path, if possible with ~ for home directory.
  1640. noabbrev Absolute path, no abbreviation of home directory.
  1641. adaptive Use relative path for files in the current directory and sub-
  1642. directories of it. For other files, use an absolute path."
  1643. :group 'org-link
  1644. :type '(choice
  1645. (const relative)
  1646. (const absolute)
  1647. (const noabbrev)
  1648. (const adaptive)))
  1649. (defvaralias 'org-activate-links 'org-highlight-links)
  1650. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1651. "Types of links that should be highlighted in Org files.
  1652. This is a list of symbols, each one of them leading to the
  1653. highlighting of a certain link type.
  1654. You can still open links that are not highlighted.
  1655. In principle, it does not hurt to turn on highlighting for all
  1656. link types. There may be a small gain when turning off unused
  1657. link types. The types are:
  1658. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1659. angle Links in angular brackets that may contain whitespace like
  1660. <bbdb:Carsten Dominik>.
  1661. plain Plain links in normal text, no whitespace, like http://google.com.
  1662. radio Text that is matched by a radio target, see manual for details.
  1663. tag Tag settings in a headline (link to tag search).
  1664. date Time stamps (link to calendar).
  1665. footnote Footnote labels.
  1666. If you set this variable during an Emacs session, use `org-mode-restart'
  1667. in the Org buffer so that the change takes effect."
  1668. :group 'org-link
  1669. :group 'org-appearance
  1670. :type '(set :greedy t
  1671. (const :tag "Double bracket links" bracket)
  1672. (const :tag "Angular bracket links" angle)
  1673. (const :tag "Plain text links" plain)
  1674. (const :tag "Radio target matches" radio)
  1675. (const :tag "Tags" tag)
  1676. (const :tag "Timestamps" date)
  1677. (const :tag "Footnotes" footnote)))
  1678. (defcustom org-make-link-description-function nil
  1679. "Function to use for generating link descriptions from links.
  1680. This function must take two parameters: the first one is the
  1681. link, the second one is the description generated by
  1682. `org-insert-link'. The function should return the description to
  1683. use."
  1684. :group 'org-link
  1685. :type '(choice (const nil) (function)))
  1686. (defgroup org-link-store nil
  1687. "Options concerning storing links in Org mode."
  1688. :tag "Org Store Link"
  1689. :group 'org-link)
  1690. (defcustom org-url-hexify-p t
  1691. "When non-nil, hexify URL when creating a link."
  1692. :type 'boolean
  1693. :version "24.3"
  1694. :group 'org-link-store)
  1695. (defcustom org-email-link-description-format "Email %c: %.30s"
  1696. "Format of the description part of a link to an email or usenet message.
  1697. The following %-escapes will be replaced by corresponding information:
  1698. %F full \"From\" field
  1699. %f name, taken from \"From\" field, address if no name
  1700. %T full \"To\" field
  1701. %t first name in \"To\" field, address if no name
  1702. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1703. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1704. %s subject
  1705. %d date
  1706. %m message-id.
  1707. You may use normal field width specification between the % and the letter.
  1708. This is for example useful to limit the length of the subject.
  1709. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1710. :group 'org-link-store
  1711. :type 'string)
  1712. (defcustom org-from-is-user-regexp
  1713. (let (r1 r2)
  1714. (when (and user-mail-address (not (string= user-mail-address "")))
  1715. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1716. (when (and user-full-name (not (string= user-full-name "")))
  1717. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1718. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1719. "Regexp matched against the \"From:\" header of an email or usenet message.
  1720. It should match if the message is from the user him/herself."
  1721. :group 'org-link-store
  1722. :type 'regexp)
  1723. (defcustom org-context-in-file-links t
  1724. "Non-nil means file links from `org-store-link' contain context.
  1725. \\<org-mode-map>
  1726. A search string will be added to the file name with :: as separator
  1727. and used to find the context when the link is activated by the command
  1728. `org-open-at-point'. When this option is t, the entire active region
  1729. will be placed in the search string of the file link. If set to a
  1730. positive integer, only the first n lines of context will be stored.
  1731. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1732. \\[org-store-link]')
  1733. negates this setting for the duration of the command."
  1734. :group 'org-link-store
  1735. :type '(choice boolean integer))
  1736. (defcustom org-keep-stored-link-after-insertion nil
  1737. "Non-nil means keep link in list for entire session.
  1738. \\<org-mode-map>
  1739. The command `org-store-link' adds a link pointing to the current
  1740. location to an internal list. These links accumulate during a session.
  1741. The command `org-insert-link' can be used to insert links into any
  1742. Org file (offering completion for all stored links).
  1743. When this option is nil, every link which has been inserted once using
  1744. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1745. unused
  1746. links more efficient."
  1747. :group 'org-link-store
  1748. :type 'boolean)
  1749. (defgroup org-link-follow nil
  1750. "Options concerning following links in Org mode."
  1751. :tag "Org Follow Link"
  1752. :group 'org-link)
  1753. (defcustom org-link-translation-function nil
  1754. "Function to translate links with different syntax to Org syntax.
  1755. This can be used to translate links created for example by the Planner
  1756. or emacs-wiki packages to Org syntax.
  1757. The function must accept two parameters, a TYPE containing the link
  1758. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1759. which is everything after the link protocol. It should return a cons
  1760. with possibly modified values of type and path.
  1761. Org contains a function for this, so if you set this variable to
  1762. `org-translate-link-from-planner', you should be able follow many
  1763. links created by planner."
  1764. :group 'org-link-follow
  1765. :type '(choice (const nil) (function)))
  1766. (defcustom org-follow-link-hook nil
  1767. "Hook that is run after a link has been followed."
  1768. :group 'org-link-follow
  1769. :type 'hook)
  1770. (defcustom org-tab-follows-link nil
  1771. "Non-nil means on links TAB will follow the link.
  1772. Needs to be set before org.el is loaded.
  1773. This really should not be used, it does not make sense, and the
  1774. implementation is bad."
  1775. :group 'org-link-follow
  1776. :type 'boolean)
  1777. (defcustom org-return-follows-link nil
  1778. "Non-nil means on links RET will follow the link.
  1779. In tables, the special behavior of RET has precedence."
  1780. :group 'org-link-follow
  1781. :type 'boolean)
  1782. (defcustom org-mouse-1-follows-link
  1783. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1784. "Non-nil means mouse-1 on a link will follow the link.
  1785. A longer mouse click will still set point. Needs to be set
  1786. before org.el is loaded."
  1787. :group 'org-link-follow
  1788. :version "26.1"
  1789. :package-version '(Org . "8.3")
  1790. :type '(choice
  1791. (const :tag "A double click follows the link" double)
  1792. (const :tag "Unconditionally follow the link with mouse-1" t)
  1793. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1794. (defcustom org-mark-ring-length 4
  1795. "Number of different positions to be recorded in the ring.
  1796. Changing this requires a restart of Emacs to work correctly."
  1797. :group 'org-link-follow
  1798. :type 'integer)
  1799. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1800. "Non-nil means internal fuzzy links can only match headlines.
  1801. When nil, the a fuzzy link may point to a target or a named
  1802. construct in the document. When set to the special value
  1803. `query-to-create', offer to create a new headline when none
  1804. matched.
  1805. Spaces and statistics cookies are ignored during heading searches."
  1806. :group 'org-link-follow
  1807. :version "24.1"
  1808. :type '(choice
  1809. (const :tag "Use fuzzy text search" nil)
  1810. (const :tag "Match only exact headline" t)
  1811. (const :tag "Match exact headline or query to create it"
  1812. query-to-create))
  1813. :safe #'symbolp)
  1814. (defcustom org-link-frame-setup
  1815. '((vm . vm-visit-folder-other-frame)
  1816. (vm-imap . vm-visit-imap-folder-other-frame)
  1817. (gnus . org-gnus-no-new-news)
  1818. (file . find-file-other-window)
  1819. (wl . wl-other-frame))
  1820. "Setup the frame configuration for following links.
  1821. When following a link with Emacs, it may often be useful to display
  1822. this link in another window or frame. This variable can be used to
  1823. set this up for the different types of links.
  1824. For VM, use any of
  1825. `vm-visit-folder'
  1826. `vm-visit-folder-other-window'
  1827. `vm-visit-folder-other-frame'
  1828. For Gnus, use any of
  1829. `gnus'
  1830. `gnus-other-frame'
  1831. `org-gnus-no-new-news'
  1832. For FILE, use any of
  1833. `find-file'
  1834. `find-file-other-window'
  1835. `find-file-other-frame'
  1836. For Wanderlust use any of
  1837. `wl'
  1838. `wl-other-frame'
  1839. For the calendar, use the variable `calendar-setup'.
  1840. For BBDB, it is currently only possible to display the matches in
  1841. another window."
  1842. :group 'org-link-follow
  1843. :type '(list
  1844. (cons (const vm)
  1845. (choice
  1846. (const vm-visit-folder)
  1847. (const vm-visit-folder-other-window)
  1848. (const vm-visit-folder-other-frame)))
  1849. (cons (const vm-imap)
  1850. (choice
  1851. (const vm-visit-imap-folder)
  1852. (const vm-visit-imap-folder-other-window)
  1853. (const vm-visit-imap-folder-other-frame)))
  1854. (cons (const gnus)
  1855. (choice
  1856. (const gnus)
  1857. (const gnus-other-frame)
  1858. (const org-gnus-no-new-news)))
  1859. (cons (const file)
  1860. (choice
  1861. (const find-file)
  1862. (const find-file-other-window)
  1863. (const find-file-other-frame)))
  1864. (cons (const wl)
  1865. (choice
  1866. (const wl)
  1867. (const wl-other-frame)))))
  1868. (defcustom org-display-internal-link-with-indirect-buffer nil
  1869. "Non-nil means use indirect buffer to display infile links.
  1870. Activating internal links (from one location in a file to another location
  1871. in the same file) normally just jumps to the location. When the link is
  1872. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1873. is displayed in
  1874. another window. When this option is set, the other window actually displays
  1875. an indirect buffer clone of the current buffer, to avoid any visibility
  1876. changes to the current buffer."
  1877. :group 'org-link-follow
  1878. :type 'boolean)
  1879. (defcustom org-open-non-existing-files nil
  1880. "Non-nil means `org-open-file' will open non-existing files.
  1881. When nil, an error will be generated.
  1882. This variable applies only to external applications because they
  1883. might choke on non-existing files. If the link is to a file that
  1884. will be opened in Emacs, the variable is ignored."
  1885. :group 'org-link-follow
  1886. :type 'boolean)
  1887. (defcustom org-open-directory-means-index-dot-org nil
  1888. "Non-nil means a link to a directory really means to index.org.
  1889. When nil, following a directory link will run dired or open a finder/explorer
  1890. window on that directory."
  1891. :group 'org-link-follow
  1892. :type 'boolean)
  1893. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1894. "Non-nil means ask for confirmation before executing shell links.
  1895. Shell links can be dangerous: just think about a link
  1896. [[shell:rm -rf ~/*][Google Search]]
  1897. This link would show up in your Org document as \"Google Search\",
  1898. but really it would remove your entire home directory.
  1899. Therefore we advise against setting this variable to nil.
  1900. Just change it to `y-or-n-p' if you want to confirm with a
  1901. single keystroke rather than having to type \"yes\"."
  1902. :group 'org-link-follow
  1903. :type '(choice
  1904. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1905. (const :tag "with y-or-n (faster)" y-or-n-p)
  1906. (const :tag "no confirmation (dangerous)" nil)))
  1907. (put 'org-confirm-shell-link-function
  1908. 'safe-local-variable
  1909. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1910. (defcustom org-confirm-shell-link-not-regexp ""
  1911. "A regexp to skip confirmation for shell links."
  1912. :group 'org-link-follow
  1913. :version "24.1"
  1914. :type 'regexp)
  1915. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1916. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1917. Elisp links can be dangerous: just think about a link
  1918. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1919. This link would show up in your Org document as \"Google Search\",
  1920. but really it would remove your entire home directory.
  1921. Therefore we advise against setting this variable to nil.
  1922. Just change it to `y-or-n-p' if you want to confirm with a
  1923. single keystroke rather than having to type \"yes\"."
  1924. :group 'org-link-follow
  1925. :type '(choice
  1926. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1927. (const :tag "with y-or-n (faster)" y-or-n-p)
  1928. (const :tag "no confirmation (dangerous)" nil)))
  1929. (put 'org-confirm-shell-link-function
  1930. 'safe-local-variable
  1931. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1932. (defcustom org-confirm-elisp-link-not-regexp ""
  1933. "A regexp to skip confirmation for Elisp links."
  1934. :group 'org-link-follow
  1935. :version "24.1"
  1936. :type 'regexp)
  1937. (defconst org-file-apps-defaults-gnu
  1938. '((remote . emacs)
  1939. (system . mailcap)
  1940. (t . mailcap))
  1941. "Default file applications on a UNIX or GNU/Linux system.
  1942. See `org-file-apps'.")
  1943. (defconst org-file-apps-defaults-macosx
  1944. '((remote . emacs)
  1945. (system . "open %s")
  1946. ("ps.gz" . "gv %s")
  1947. ("eps.gz" . "gv %s")
  1948. ("dvi" . "xdvi %s")
  1949. ("fig" . "xfig %s")
  1950. (t . "open %s"))
  1951. "Default file applications on a macOS system.
  1952. The system \"open\" is known as a default, but we use X11 applications
  1953. for some files for which the OS does not have a good default.
  1954. See `org-file-apps'.")
  1955. (defconst org-file-apps-defaults-windowsnt
  1956. (list '(remote . emacs)
  1957. (cons 'system (lambda (file _path)
  1958. (with-no-warnings (w32-shell-execute "open" file))))
  1959. (cons t (lambda (file _path)
  1960. (with-no-warnings (w32-shell-execute "open" file)))))
  1961. "Default file applications on a Windows NT system.
  1962. The system \"open\" is used for most files.
  1963. See `org-file-apps'.")
  1964. (defcustom org-file-apps
  1965. '((auto-mode . emacs)
  1966. ("\\.mm\\'" . default)
  1967. ("\\.x?html?\\'" . default)
  1968. ("\\.pdf\\'" . default))
  1969. "External applications for opening `file:path' items in a document.
  1970. \\<org-mode-map>\
  1971. Org mode uses system defaults for different file types, but
  1972. you can use this variable to set the application for a given file
  1973. extension. The entries in this list are cons cells where the car identifies
  1974. files and the cdr the corresponding command.
  1975. Possible values for the file identifier are:
  1976. \"string\" A string as a file identifier can be interpreted in different
  1977. ways, depending on its contents:
  1978. - Alphanumeric characters only:
  1979. Match links with this file extension.
  1980. Example: (\"pdf\" . \"evince %s\")
  1981. to open PDFs with evince.
  1982. - Regular expression: Match links where the
  1983. filename matches the regexp. If you want to
  1984. use groups here, use shy groups.
  1985. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1986. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1987. to open *.html and *.xhtml with firefox.
  1988. - Regular expression which contains (non-shy) groups:
  1989. Match links where the whole link, including \"::\", and
  1990. anything after that, matches the regexp.
  1991. In a custom command string, %1, %2, etc. are replaced with
  1992. the parts of the link that were matched by the groups.
  1993. For backwards compatibility, if a command string is given
  1994. that does not use any of the group matches, this case is
  1995. handled identically to the second one (i.e. match against
  1996. file name only).
  1997. In a custom function, you can access the group matches with
  1998. (match-string n link).
  1999. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  2000. \"evince -p %1 %s\")
  2001. to open [[file:document.pdf::5]] with evince at page 5.
  2002. `directory' Matches a directory
  2003. `remote' Matches a remote file, accessible through tramp or efs.
  2004. Remote files most likely should be visited through Emacs
  2005. because external applications cannot handle such paths.
  2006. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2007. so all files Emacs knows how to handle. Using this with
  2008. command `emacs' will open most files in Emacs. Beware that this
  2009. will also open html files inside Emacs, unless you add
  2010. (\"html\" . default) to the list as well.
  2011. `system' The system command to open files, like `open' on Windows
  2012. and macOS, and mailcap under GNU/Linux. This is the command
  2013. that will be selected if you call `org-open-at-point' with a
  2014. double prefix argument (`\\[universal-argument] \
  2015. \\[universal-argument] \\[org-open-at-point]').
  2016. t Default for files not matched by any of the other options.
  2017. Possible values for the command are:
  2018. `emacs' The file will be visited by the current Emacs process.
  2019. `default' Use the default application for this file type, which is the
  2020. association for t in the list, most likely in the system-specific
  2021. part. This can be used to overrule an unwanted setting in the
  2022. system-specific variable.
  2023. `system' Use the system command for opening files, like \"open\".
  2024. This command is specified by the entry whose car is `system'.
  2025. Most likely, the system-specific version of this variable
  2026. does define this command, but you can overrule/replace it
  2027. here.
  2028. `mailcap' Use command specified in the mailcaps.
  2029. string A command to be executed by a shell; %s will be replaced
  2030. by the path to the file.
  2031. function A Lisp function, which will be called with two arguments:
  2032. the file path and the original link string, without the
  2033. \"file:\" prefix.
  2034. For more examples, see the system specific constants
  2035. `org-file-apps-defaults-macosx'
  2036. `org-file-apps-defaults-windowsnt'
  2037. `org-file-apps-defaults-gnu'."
  2038. :group 'org-link-follow
  2039. :type '(repeat
  2040. (cons (choice :value ""
  2041. (string :tag "Extension")
  2042. (const :tag "System command to open files" system)
  2043. (const :tag "Default for unrecognized files" t)
  2044. (const :tag "Remote file" remote)
  2045. (const :tag "Links to a directory" directory)
  2046. (const :tag "Any files that have Emacs modes"
  2047. auto-mode))
  2048. (choice :value ""
  2049. (const :tag "Visit with Emacs" emacs)
  2050. (const :tag "Use default" default)
  2051. (const :tag "Use the system command" system)
  2052. (string :tag "Command")
  2053. (function :tag "Function")))))
  2054. (defcustom org-doi-server-url "http://dx.doi.org/"
  2055. "The URL of the DOI server."
  2056. :type 'string
  2057. :version "24.3"
  2058. :group 'org-link-follow)
  2059. (defgroup org-refile nil
  2060. "Options concerning refiling entries in Org mode."
  2061. :tag "Org Refile"
  2062. :group 'org)
  2063. (defcustom org-directory "~/org"
  2064. "Directory with Org files.
  2065. This is just a default location to look for Org files. There is no need
  2066. at all to put your files into this directory. It is used in the
  2067. following situations:
  2068. 1. When a capture template specifies a target file that is not an
  2069. absolute path. The path will then be interpreted relative to
  2070. `org-directory'
  2071. 2. When the value of variable `org-agenda-files' is a single file, any
  2072. relative paths in this file will be taken as relative to
  2073. `org-directory'."
  2074. :group 'org-refile
  2075. :group 'org-capture
  2076. :type 'directory)
  2077. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2078. "Default target for storing notes.
  2079. Used as a fall back file for org-capture.el, for templates that
  2080. do not specify a target file."
  2081. :group 'org-refile
  2082. :group 'org-capture
  2083. :type 'file)
  2084. (defcustom org-reverse-note-order nil
  2085. "Non-nil means store new notes at the beginning of a file or entry.
  2086. When nil, new notes will be filed to the end of a file or entry.
  2087. This can also be a list with cons cells of regular expressions that
  2088. are matched against file names, and values."
  2089. :group 'org-capture
  2090. :group 'org-refile
  2091. :type '(choice
  2092. (const :tag "Reverse always" t)
  2093. (const :tag "Reverse never" nil)
  2094. (repeat :tag "By file name regexp"
  2095. (cons regexp boolean))))
  2096. (defcustom org-log-refile nil
  2097. "Information to record when a task is refiled.
  2098. Possible values are:
  2099. nil Don't add anything
  2100. time Add a time stamp to the task
  2101. note Prompt for a note and add it with template `org-log-note-headings'
  2102. This option can also be set with on a per-file-basis with
  2103. #+STARTUP: nologrefile
  2104. #+STARTUP: logrefile
  2105. #+STARTUP: lognoterefile
  2106. You can have local logging settings for a subtree by setting the LOGGING
  2107. property to one or more of these keywords.
  2108. When bulk-refiling from the agenda, the value `note' is forbidden and
  2109. will temporarily be changed to `time'."
  2110. :group 'org-refile
  2111. :group 'org-progress
  2112. :version "24.1"
  2113. :type '(choice
  2114. (const :tag "No logging" nil)
  2115. (const :tag "Record timestamp" time)
  2116. (const :tag "Record timestamp with note." note)))
  2117. (defcustom org-refile-targets nil
  2118. "Targets for refiling entries with `\\[org-refile]'.
  2119. This is a list of cons cells. Each cell contains:
  2120. - a specification of the files to be considered, either a list of files,
  2121. or a symbol whose function or variable value will be used to retrieve
  2122. a file name or a list of file names. If you use `org-agenda-files' for
  2123. that, all agenda files will be scanned for targets. Nil means consider
  2124. headings in the current buffer.
  2125. - A specification of how to find candidate refile targets. This may be
  2126. any of:
  2127. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2128. This tag has to be present in all target headlines, inheritance will
  2129. not be considered.
  2130. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2131. todo keyword.
  2132. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2133. headlines that are refiling targets.
  2134. - a cons cell (:level . N). Any headline of level N is considered a target.
  2135. Note that, when `org-odd-levels-only' is set, level corresponds to
  2136. order in hierarchy, not to the number of stars.
  2137. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2138. Note that, when `org-odd-levels-only' is set, level corresponds to
  2139. order in hierarchy, not to the number of stars.
  2140. Each element of this list generates a set of possible targets.
  2141. The union of these sets is presented (with completion) to
  2142. the user by `org-refile'.
  2143. You can set the variable `org-refile-target-verify-function' to a function
  2144. to verify each headline found by the simple criteria above.
  2145. When this variable is nil, all top-level headlines in the current buffer
  2146. are used, equivalent to the value `((nil . (:level . 1))'."
  2147. :group 'org-refile
  2148. :type '(repeat
  2149. (cons
  2150. (choice :value org-agenda-files
  2151. (const :tag "All agenda files" org-agenda-files)
  2152. (const :tag "Current buffer" nil)
  2153. (function) (variable) (file))
  2154. (choice :tag "Identify target headline by"
  2155. (cons :tag "Specific tag" (const :value :tag) (string))
  2156. (cons :tag "TODO keyword" (const :value :todo) (string))
  2157. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2158. (cons :tag "Level number" (const :value :level) (integer))
  2159. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2160. (defcustom org-refile-target-verify-function nil
  2161. "Function to verify if the headline at point should be a refile target.
  2162. The function will be called without arguments, with point at the
  2163. beginning of the headline. It should return t and leave point
  2164. where it is if the headline is a valid target for refiling.
  2165. If the target should not be selected, the function must return nil.
  2166. In addition to this, it may move point to a place from where the search
  2167. should be continued. For example, the function may decide that the entire
  2168. subtree of the current entry should be excluded and move point to the end
  2169. of the subtree."
  2170. :group 'org-refile
  2171. :type '(choice
  2172. (const nil)
  2173. (function)))
  2174. (defcustom org-refile-use-cache nil
  2175. "Non-nil means cache refile targets to speed up the process.
  2176. \\<org-mode-map>\
  2177. The cache for a particular file will be updated automatically when
  2178. the buffer has been killed, or when any of the marker used for flagging
  2179. refile targets no longer points at a live buffer.
  2180. If you have added new entries to a buffer that might themselves be targets,
  2181. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2182. if you find that easier, \
  2183. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2184. \\[org-refile]'."
  2185. :group 'org-refile
  2186. :version "24.1"
  2187. :type 'boolean)
  2188. (defcustom org-refile-use-outline-path nil
  2189. "Non-nil means provide refile targets as paths.
  2190. So a level 3 headline will be available as level1/level2/level3.
  2191. When the value is `file', also include the file name (without directory)
  2192. into the path. In this case, you can also stop the completion after
  2193. the file name, to get entries inserted as top level in the file.
  2194. When `full-file-path', include the full file path.
  2195. When `buffer-name', use the buffer name."
  2196. :group 'org-refile
  2197. :type '(choice
  2198. (const :tag "Not" nil)
  2199. (const :tag "Yes" t)
  2200. (const :tag "Start with file name" file)
  2201. (const :tag "Start with full file path" full-file-path)
  2202. (const :tag "Start with buffer name" buffer-name)))
  2203. (defcustom org-outline-path-complete-in-steps t
  2204. "Non-nil means complete the outline path in hierarchical steps.
  2205. When Org uses the refile interface to select an outline path (see
  2206. `org-refile-use-outline-path'), the completion of the path can be
  2207. done in a single go, or it can be done in steps down the headline
  2208. hierarchy. Going in steps is probably the best if you do not use
  2209. a special completion package like `ido' or `icicles'. However,
  2210. when using these packages, going in one step can be very fast,
  2211. while still showing the whole path to the entry."
  2212. :group 'org-refile
  2213. :type 'boolean)
  2214. (defcustom org-refile-allow-creating-parent-nodes nil
  2215. "Non-nil means allow the creation of new nodes as refile targets.
  2216. New nodes are then created by adding \"/new node name\" to the completion
  2217. of an existing node. When the value of this variable is `confirm',
  2218. new node creation must be confirmed by the user (recommended).
  2219. When nil, the completion must match an existing entry.
  2220. Note that, if the new heading is not seen by the criteria
  2221. listed in `org-refile-targets', multiple instances of the same
  2222. heading would be created by trying again to file under the new
  2223. heading."
  2224. :group 'org-refile
  2225. :type '(choice
  2226. (const :tag "Never" nil)
  2227. (const :tag "Always" t)
  2228. (const :tag "Prompt for confirmation" confirm)))
  2229. (defcustom org-refile-active-region-within-subtree nil
  2230. "Non-nil means also refile active region within a subtree.
  2231. By default `org-refile' doesn't allow refiling regions if they
  2232. don't contain a set of subtrees, but it might be convenient to
  2233. do so sometimes: in that case, the first line of the region is
  2234. converted to a headline before refiling."
  2235. :group 'org-refile
  2236. :version "24.1"
  2237. :type 'boolean)
  2238. (defgroup org-todo nil
  2239. "Options concerning TODO items in Org mode."
  2240. :tag "Org TODO"
  2241. :group 'org)
  2242. (defgroup org-progress nil
  2243. "Options concerning Progress logging in Org mode."
  2244. :tag "Org Progress"
  2245. :group 'org-time)
  2246. (defvar org-todo-interpretation-widgets
  2247. '((:tag "Sequence (cycling hits every state)" sequence)
  2248. (:tag "Type (cycling directly to DONE)" type))
  2249. "The available interpretation symbols for customizing `org-todo-keywords'.
  2250. Interested libraries should add to this list.")
  2251. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2252. "List of TODO entry keyword sequences and their interpretation.
  2253. \\<org-mode-map>This is a list of sequences.
  2254. Each sequence starts with a symbol, either `sequence' or `type',
  2255. indicating if the keywords should be interpreted as a sequence of
  2256. action steps, or as different types of TODO items. The first
  2257. keywords are states requiring action - these states will select a headline
  2258. for inclusion into the global TODO list Org produces. If one of the
  2259. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2260. signify that no further action is necessary. If \"|\" is not found,
  2261. the last keyword is treated as the only DONE state of the sequence.
  2262. The command `\\[org-todo]' cycles an entry through these states, and one
  2263. additional state where no keyword is present. For details about this
  2264. cycling, see the manual.
  2265. TODO keywords and interpretation can also be set on a per-file basis with
  2266. the special #+SEQ_TODO and #+TYP_TODO lines.
  2267. Each keyword can optionally specify a character for fast state selection
  2268. \(in combination with the variable `org-use-fast-todo-selection')
  2269. and specifiers for state change logging, using the same syntax that
  2270. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2271. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2272. indicates to record a time stamp each time this state is selected.
  2273. Each keyword may also specify if a timestamp or a note should be
  2274. recorded when entering or leaving the state, by adding additional
  2275. characters in the parenthesis after the keyword. This looks like this:
  2276. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2277. record only the time of the state change. With X and Y being either
  2278. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2279. Y when leaving the state if and only if the *target* state does not
  2280. define X. You may omit any of the fast-selection key or X or /Y,
  2281. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2282. For backward compatibility, this variable may also be just a list
  2283. of keywords. In this case the interpretation (sequence or type) will be
  2284. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2285. :group 'org-todo
  2286. :group 'org-keywords
  2287. :type '(choice
  2288. (repeat :tag "Old syntax, just keywords"
  2289. (string :tag "Keyword"))
  2290. (repeat :tag "New syntax"
  2291. (cons
  2292. (choice
  2293. :tag "Interpretation"
  2294. ;;Quick and dirty way to see
  2295. ;;`org-todo-interpretations'. This takes the
  2296. ;;place of item arguments
  2297. :convert-widget
  2298. (lambda (widget)
  2299. (widget-put widget
  2300. :args (mapcar
  2301. (lambda (x)
  2302. (widget-convert
  2303. (cons 'const x)))
  2304. org-todo-interpretation-widgets))
  2305. widget))
  2306. (repeat
  2307. (string :tag "Keyword"))))))
  2308. (defvar-local org-todo-keywords-1 nil
  2309. "All TODO and DONE keywords active in a buffer.")
  2310. (defvar org-todo-keywords-for-agenda nil)
  2311. (defvar org-done-keywords-for-agenda nil)
  2312. (defvar org-todo-keyword-alist-for-agenda nil)
  2313. (defvar org-tag-alist-for-agenda nil
  2314. "Alist of all tags from all agenda files.")
  2315. (defvar org-tag-groups-alist-for-agenda nil
  2316. "Alist of all groups tags from all current agenda files.")
  2317. (defvar-local org-tag-groups-alist nil)
  2318. (defvar org-agenda-contributing-files nil)
  2319. (defvar-local org-current-tag-alist nil
  2320. "Alist of all tag groups in current buffer.
  2321. This variable takes into consideration `org-tag-alist',
  2322. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2323. (defvar-local org-not-done-keywords nil)
  2324. (defvar-local org-done-keywords nil)
  2325. (defvar-local org-todo-heads nil)
  2326. (defvar-local org-todo-sets nil)
  2327. (defvar-local org-todo-log-states nil)
  2328. (defvar-local org-todo-kwd-alist nil)
  2329. (defvar-local org-todo-key-alist nil)
  2330. (defvar-local org-todo-key-trigger nil)
  2331. (defcustom org-todo-interpretation 'sequence
  2332. "Controls how TODO keywords are interpreted.
  2333. This variable is in principle obsolete and is only used for
  2334. backward compatibility, if the interpretation of todo keywords is
  2335. not given already in `org-todo-keywords'. See that variable for
  2336. more information."
  2337. :group 'org-todo
  2338. :group 'org-keywords
  2339. :type '(choice (const sequence)
  2340. (const type)))
  2341. (defcustom org-use-fast-todo-selection t
  2342. "\\<org-mode-map>\
  2343. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2344. This variable describes if and under what circumstances the cycling
  2345. mechanism for TODO keywords will be replaced by a single-key, direct
  2346. selection scheme.
  2347. When nil, fast selection is never used.
  2348. When the symbol `prefix', it will be used when `org-todo' is called
  2349. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2350. in an Org buffer, and
  2351. `\\[universal-argument] t' in an agenda buffer.
  2352. When t, fast selection is used by default. In this case, the prefix
  2353. argument forces cycling instead.
  2354. In all cases, the special interface is only used if access keys have
  2355. actually been assigned by the user, i.e. if keywords in the configuration
  2356. are followed by a letter in parenthesis, like TODO(t)."
  2357. :group 'org-todo
  2358. :type '(choice
  2359. (const :tag "Never" nil)
  2360. (const :tag "By default" t)
  2361. (const :tag "Only with C-u C-c C-t" prefix)))
  2362. (defcustom org-provide-todo-statistics t
  2363. "Non-nil means update todo statistics after insert and toggle.
  2364. ALL-HEADLINES means update todo statistics by including headlines
  2365. with no TODO keyword as well, counting them as not done.
  2366. A list of TODO keywords means the same, but skip keywords that are
  2367. not in this list.
  2368. When set to a list of two lists, the first list contains keywords
  2369. to consider as TODO keywords, the second list contains keywords
  2370. to consider as DONE keywords.
  2371. When this is set, todo statistics is updated in the parent of the
  2372. current entry each time a todo state is changed."
  2373. :group 'org-todo
  2374. :type '(choice
  2375. (const :tag "Yes, only for TODO entries" t)
  2376. (const :tag "Yes, including all entries" all-headlines)
  2377. (repeat :tag "Yes, for TODOs in this list"
  2378. (string :tag "TODO keyword"))
  2379. (list :tag "Yes, for TODOs and DONEs in these lists"
  2380. (repeat (string :tag "TODO keyword"))
  2381. (repeat (string :tag "DONE keyword")))
  2382. (other :tag "No TODO statistics" nil)))
  2383. (defcustom org-hierarchical-todo-statistics t
  2384. "Non-nil means TODO statistics covers just direct children.
  2385. When nil, all entries in the subtree are considered.
  2386. This has only an effect if `org-provide-todo-statistics' is set.
  2387. To set this to nil for only a single subtree, use a COOKIE_DATA
  2388. property and include the word \"recursive\" into the value."
  2389. :group 'org-todo
  2390. :type 'boolean)
  2391. (defcustom org-after-todo-state-change-hook nil
  2392. "Hook which is run after the state of a TODO item was changed.
  2393. The new state (a string with a TODO keyword, or nil) is available in the
  2394. Lisp variable `org-state'."
  2395. :group 'org-todo
  2396. :type 'hook)
  2397. (defvar org-blocker-hook nil
  2398. "Hook for functions that are allowed to block a state change.
  2399. Functions in this hook should not modify the buffer.
  2400. Each function gets as its single argument a property list,
  2401. see `org-trigger-hook' for more information about this list.
  2402. If any of the functions in this hook returns nil, the state change
  2403. is blocked.")
  2404. (defvar org-trigger-hook nil
  2405. "Hook for functions that are triggered by a state change.
  2406. Each function gets as its single argument a property list with at
  2407. least the following elements:
  2408. (:type type-of-change :position pos-at-entry-start
  2409. :from old-state :to new-state)
  2410. Depending on the type, more properties may be present.
  2411. This mechanism is currently implemented for:
  2412. TODO state changes
  2413. ------------------
  2414. :type todo-state-change
  2415. :from previous state (keyword as a string), or nil, or a symbol
  2416. `todo' or `done', to indicate the general type of state.
  2417. :to new state, like in :from")
  2418. (defcustom org-enforce-todo-dependencies nil
  2419. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2420. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2421. be blocked if any prior sibling is not yet done.
  2422. Finally, if the parent is blocked because of ordered siblings of its own,
  2423. the child will also be blocked."
  2424. :set (lambda (var val)
  2425. (set var val)
  2426. (if val
  2427. (add-hook 'org-blocker-hook
  2428. 'org-block-todo-from-children-or-siblings-or-parent)
  2429. (remove-hook 'org-blocker-hook
  2430. 'org-block-todo-from-children-or-siblings-or-parent)))
  2431. :group 'org-todo
  2432. :type 'boolean)
  2433. (defcustom org-enforce-todo-checkbox-dependencies nil
  2434. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2435. When this is nil, checkboxes have no influence on switching TODO states.
  2436. When non-nil, you first need to check off all check boxes before the TODO
  2437. entry can be switched to DONE.
  2438. This variable needs to be set before org.el is loaded, and you need to
  2439. restart Emacs after a change to make the change effective. The only way
  2440. to change is while Emacs is running is through the customize interface."
  2441. :set (lambda (var val)
  2442. (set var val)
  2443. (if val
  2444. (add-hook 'org-blocker-hook
  2445. 'org-block-todo-from-checkboxes)
  2446. (remove-hook 'org-blocker-hook
  2447. 'org-block-todo-from-checkboxes)))
  2448. :group 'org-todo
  2449. :type 'boolean)
  2450. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2451. "Non-nil means inserting a TODO heading is treated as state change.
  2452. So when the command `\\[org-insert-todo-heading]' is used, state change
  2453. logging will apply if appropriate. When nil, the new TODO item will
  2454. be inserted directly, and no logging will take place."
  2455. :group 'org-todo
  2456. :type 'boolean)
  2457. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2458. "Non-nil means switching TODO states with S-cursor counts as state change.
  2459. This is the default behavior. However, setting this to nil allows a
  2460. convenient way to select a TODO state and bypass any logging associated
  2461. with that."
  2462. :group 'org-todo
  2463. :type 'boolean)
  2464. (defcustom org-todo-state-tags-triggers nil
  2465. "Tag changes that should be triggered by TODO state changes.
  2466. This is a list. Each entry is
  2467. (state-change (tag . flag) .......)
  2468. State-change can be a string with a state, and empty string to indicate the
  2469. state that has no TODO keyword, or it can be one of the symbols `todo'
  2470. or `done', meaning any not-done or done state, respectively."
  2471. :group 'org-todo
  2472. :group 'org-tags
  2473. :type '(repeat
  2474. (cons (choice :tag "When changing to"
  2475. (const :tag "Not-done state" todo)
  2476. (const :tag "Done state" done)
  2477. (string :tag "State"))
  2478. (repeat
  2479. (cons :tag "Tag action"
  2480. (string :tag "Tag")
  2481. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2482. (defcustom org-log-done nil
  2483. "Information to record when a task moves to the DONE state.
  2484. Possible values are:
  2485. nil Don't add anything, just change the keyword
  2486. time Add a time stamp to the task
  2487. note Prompt for a note and add it with template `org-log-note-headings'
  2488. This option can also be set with on a per-file-basis with
  2489. #+STARTUP: nologdone
  2490. #+STARTUP: logdone
  2491. #+STARTUP: lognotedone
  2492. You can have local logging settings for a subtree by setting the LOGGING
  2493. property to one or more of these keywords."
  2494. :group 'org-todo
  2495. :group 'org-progress
  2496. :type '(choice
  2497. (const :tag "No logging" nil)
  2498. (const :tag "Record CLOSED timestamp" time)
  2499. (const :tag "Record CLOSED timestamp with note." note)))
  2500. ;; Normalize old uses of org-log-done.
  2501. (cond
  2502. ((eq org-log-done t) (setq org-log-done 'time))
  2503. ((and (listp org-log-done) (memq 'done org-log-done))
  2504. (setq org-log-done 'note)))
  2505. (defcustom org-log-reschedule nil
  2506. "Information to record when the scheduling date of a task is modified.
  2507. Possible values are:
  2508. nil Don't add anything, just change the date
  2509. time Add a time stamp to the task
  2510. note Prompt for a note and add it with template `org-log-note-headings'
  2511. This option can also be set with on a per-file-basis with
  2512. #+STARTUP: nologreschedule
  2513. #+STARTUP: logreschedule
  2514. #+STARTUP: lognotereschedule
  2515. You can have local logging settings for a subtree by setting the LOGGING
  2516. property to one or more of these keywords.
  2517. This variable has an effect when calling `org-schedule' or
  2518. `org-agenda-schedule' only."
  2519. :group 'org-todo
  2520. :group 'org-progress
  2521. :type '(choice
  2522. (const :tag "No logging" nil)
  2523. (const :tag "Record timestamp" time)
  2524. (const :tag "Record timestamp with note" note)))
  2525. (defcustom org-log-redeadline nil
  2526. "Information to record when the deadline date of a task is modified.
  2527. Possible values are:
  2528. nil Don't add anything, just change the date
  2529. time Add a time stamp to the task
  2530. note Prompt for a note and add it with template `org-log-note-headings'
  2531. This option can also be set with on a per-file-basis with
  2532. #+STARTUP: nologredeadline
  2533. #+STARTUP: logredeadline
  2534. #+STARTUP: lognoteredeadline
  2535. You can have local logging settings for a subtree by setting the LOGGING
  2536. property to one or more of these keywords.
  2537. This variable has an effect when calling `org-deadline' or
  2538. `org-agenda-deadline' only."
  2539. :group 'org-todo
  2540. :group 'org-progress
  2541. :type '(choice
  2542. (const :tag "No logging" nil)
  2543. (const :tag "Record timestamp" time)
  2544. (const :tag "Record timestamp with note." note)))
  2545. (defcustom org-log-note-clock-out nil
  2546. "Non-nil means record a note when clocking out of an item.
  2547. This can also be configured on a per-file basis by adding one of
  2548. the following lines anywhere in the buffer:
  2549. #+STARTUP: lognoteclock-out
  2550. #+STARTUP: nolognoteclock-out"
  2551. :group 'org-todo
  2552. :group 'org-progress
  2553. :type 'boolean)
  2554. (defcustom org-log-done-with-time t
  2555. "Non-nil means the CLOSED time stamp will contain date and time.
  2556. When nil, only the date will be recorded."
  2557. :group 'org-progress
  2558. :type 'boolean)
  2559. (defcustom org-log-note-headings
  2560. '((done . "CLOSING NOTE %t")
  2561. (state . "State %-12s from %-12S %t")
  2562. (note . "Note taken on %t")
  2563. (reschedule . "Rescheduled from %S on %t")
  2564. (delschedule . "Not scheduled, was %S on %t")
  2565. (redeadline . "New deadline from %S on %t")
  2566. (deldeadline . "Removed deadline, was %S on %t")
  2567. (refile . "Refiled on %t")
  2568. (clock-out . ""))
  2569. "Headings for notes added to entries.
  2570. The value is an alist, with the car being a symbol indicating the
  2571. note context, and the cdr is the heading to be used. The heading
  2572. may also be the empty string. The following placeholders can be
  2573. used:
  2574. %t a time stamp.
  2575. %T an active time stamp instead the default inactive one
  2576. %d a short-format time stamp.
  2577. %D an active short-format time stamp.
  2578. %s the new TODO state or time stamp (inactive), in double quotes.
  2579. %S the old TODO state or time stamp (inactive), in double quotes.
  2580. %u the user name.
  2581. %U full user name.
  2582. In fact, it is not a good idea to change the `state' entry,
  2583. because Agenda Log mode depends on the format of these entries."
  2584. :group 'org-todo
  2585. :group 'org-progress
  2586. :type '(list :greedy t
  2587. (cons (const :tag "Heading when closing an item" done) string)
  2588. (cons (const :tag
  2589. "Heading when changing todo state (todo sequence only)"
  2590. state) string)
  2591. (cons (const :tag "Heading when just taking a note" note) string)
  2592. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2593. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2594. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2595. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2596. (cons (const :tag "Heading when refiling" refile) string)
  2597. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2598. (unless (assq 'note org-log-note-headings)
  2599. (push '(note . "%t") org-log-note-headings))
  2600. (defcustom org-log-into-drawer nil
  2601. "Non-nil means insert state change notes and time stamps into a drawer.
  2602. When nil, state changes notes will be inserted after the headline and
  2603. any scheduling and clock lines, but not inside a drawer.
  2604. The value of this variable should be the name of the drawer to use.
  2605. LOGBOOK is proposed as the default drawer for this purpose, you can
  2606. also set this to a string to define the drawer of your choice.
  2607. A value of t is also allowed, representing \"LOGBOOK\".
  2608. A value of t or nil can also be set with on a per-file-basis with
  2609. #+STARTUP: logdrawer
  2610. #+STARTUP: nologdrawer
  2611. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2612. will be ignored.
  2613. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2614. a subtree.
  2615. Do not check directly this variable in a Lisp program. Call
  2616. function `org-log-into-drawer' instead."
  2617. :group 'org-todo
  2618. :group 'org-progress
  2619. :type '(choice
  2620. (const :tag "Not into a drawer" nil)
  2621. (const :tag "LOGBOOK" t)
  2622. (string :tag "Other")))
  2623. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2624. (defun org-log-into-drawer ()
  2625. "Name of the log drawer, as a string, or nil.
  2626. This is the value of `org-log-into-drawer'. However, if the
  2627. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2628. be used instead of the default value."
  2629. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2630. (cond ((equal p "nil") nil)
  2631. ((equal p "t") "LOGBOOK")
  2632. ((stringp p) p)
  2633. (p "LOGBOOK")
  2634. ((stringp org-log-into-drawer) org-log-into-drawer)
  2635. (org-log-into-drawer "LOGBOOK"))))
  2636. (defcustom org-log-state-notes-insert-after-drawers nil
  2637. "Non-nil means insert state change notes after any drawers in entry.
  2638. Only the drawers that *immediately* follow the headline and the
  2639. deadline/scheduled line are skipped.
  2640. When nil, insert notes right after the heading and perhaps the line
  2641. with deadline/scheduling if present.
  2642. This variable will have no effect if `org-log-into-drawer' is
  2643. set."
  2644. :group 'org-todo
  2645. :group 'org-progress
  2646. :type 'boolean)
  2647. (defcustom org-log-states-order-reversed t
  2648. "Non-nil means the latest state note will be directly after heading.
  2649. When nil, the state change notes will be ordered according to time.
  2650. This option can also be set with on a per-file-basis with
  2651. #+STARTUP: logstatesreversed
  2652. #+STARTUP: nologstatesreversed"
  2653. :group 'org-todo
  2654. :group 'org-progress
  2655. :type 'boolean)
  2656. (defcustom org-todo-repeat-to-state nil
  2657. "The TODO state to which a repeater should return the repeating task.
  2658. By default this is the first task of a TODO sequence or the
  2659. previous state of a TYPE_TODO set. But you can specify to use
  2660. the previous state in a TODO sequence or a string.
  2661. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2662. entry, which has precedence over this option."
  2663. :group 'org-todo
  2664. :version "24.1"
  2665. :type '(choice (const :tag "Use the previous TODO state" t)
  2666. (const :tag "Use the head of the TODO sequence" nil)
  2667. (string :tag "Use a specific TODO state")))
  2668. (defcustom org-log-repeat 'time
  2669. "Non-nil means record moving through the DONE state when triggering repeat.
  2670. An auto-repeating task is immediately switched back to TODO when
  2671. marked DONE. If you are not logging state changes (by adding \"@\"
  2672. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2673. record a closing note, there will be no record of the task moving
  2674. through DONE. This variable forces taking a note anyway.
  2675. nil Don't force a record
  2676. time Record a time stamp
  2677. note Prompt for a note and add it with template `org-log-note-headings'
  2678. This option can also be set with on a per-file-basis with
  2679. #+STARTUP: nologrepeat
  2680. #+STARTUP: logrepeat
  2681. #+STARTUP: lognoterepeat
  2682. You can have local logging settings for a subtree by setting the LOGGING
  2683. property to one or more of these keywords."
  2684. :group 'org-todo
  2685. :group 'org-progress
  2686. :type '(choice
  2687. (const :tag "Don't force a record" nil)
  2688. (const :tag "Force recording the DONE state" time)
  2689. (const :tag "Force recording a note with the DONE state" note)))
  2690. (defgroup org-priorities nil
  2691. "Priorities in Org mode."
  2692. :tag "Org Priorities"
  2693. :group 'org-todo)
  2694. (defcustom org-enable-priority-commands t
  2695. "Non-nil means priority commands are active.
  2696. When nil, these commands will be disabled, so that you never accidentally
  2697. set a priority."
  2698. :group 'org-priorities
  2699. :type 'boolean)
  2700. (defcustom org-highest-priority ?A
  2701. "The highest priority of TODO items. A character like ?A, ?B etc.
  2702. Must have a smaller ASCII number than `org-lowest-priority'."
  2703. :group 'org-priorities
  2704. :type 'character)
  2705. (defcustom org-lowest-priority ?C
  2706. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2707. Must have a larger ASCII number than `org-highest-priority'."
  2708. :group 'org-priorities
  2709. :type 'character)
  2710. (defcustom org-default-priority ?B
  2711. "The default priority of TODO items.
  2712. This is the priority an item gets if no explicit priority is given.
  2713. When starting to cycle on an empty priority the first step in the cycle
  2714. depends on `org-priority-start-cycle-with-default'. The resulting first
  2715. step priority must not exceed the range from `org-highest-priority' to
  2716. `org-lowest-priority' which means that `org-default-priority' has to be
  2717. in this range exclusive or inclusive the range boundaries. Else the
  2718. first step refuses to set the default and the second will fall back
  2719. to (depending on the command used) the highest or lowest priority."
  2720. :group 'org-priorities
  2721. :type 'character)
  2722. (defcustom org-priority-start-cycle-with-default t
  2723. "Non-nil means start with default priority when starting to cycle.
  2724. When this is nil, the first step in the cycle will be (depending on the
  2725. command used) one higher or lower than the default priority.
  2726. See also `org-default-priority'."
  2727. :group 'org-priorities
  2728. :type 'boolean)
  2729. (defcustom org-get-priority-function nil
  2730. "Function to extract the priority from a string.
  2731. The string is normally the headline. If this is nil Org computes the
  2732. priority from the priority cookie like [#A] in the headline. It returns
  2733. an integer, increasing by 1000 for each priority level.
  2734. The user can set a different function here, which should take a string
  2735. as an argument and return the numeric priority."
  2736. :group 'org-priorities
  2737. :version "24.1"
  2738. :type '(choice
  2739. (const nil)
  2740. (function)))
  2741. (defgroup org-time nil
  2742. "Options concerning time stamps and deadlines in Org mode."
  2743. :tag "Org Time"
  2744. :group 'org)
  2745. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2746. "Number of minutes to round time stamps to.
  2747. \\<org-mode-map>\
  2748. These are two values, the first applies when first creating a time stamp.
  2749. The second applies when changing it with the commands `S-up' and `S-down'.
  2750. When changing the time stamp, this means that it will change in steps
  2751. of N minutes, as given by the second value.
  2752. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2753. numbers should be factors of 60, so for example 5, 10, 15.
  2754. When this is larger than 1, you can still force an exact time stamp by using
  2755. a double prefix argument to a time stamp command like \
  2756. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2757. and by using a prefix arg to `S-up/down' to specify the exact number
  2758. of minutes to shift."
  2759. :group 'org-time
  2760. :get (lambda (var) ; Make sure both elements are there
  2761. (if (integerp (default-value var))
  2762. (list (default-value var) 5)
  2763. (default-value var)))
  2764. :type '(list
  2765. (integer :tag "when inserting times")
  2766. (integer :tag "when modifying times")))
  2767. ;; Normalize old customizations of this variable.
  2768. (when (integerp org-time-stamp-rounding-minutes)
  2769. (setq org-time-stamp-rounding-minutes
  2770. (list org-time-stamp-rounding-minutes
  2771. org-time-stamp-rounding-minutes)))
  2772. (defcustom org-display-custom-times nil
  2773. "Non-nil means overlay custom formats over all time stamps.
  2774. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2775. To turn this on on a per-file basis, insert anywhere in the file:
  2776. #+STARTUP: customtime"
  2777. :group 'org-time
  2778. :set 'set-default
  2779. :type 'sexp)
  2780. (make-variable-buffer-local 'org-display-custom-times)
  2781. (defcustom org-time-stamp-custom-formats
  2782. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2783. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2784. These are overlaid over the default ISO format if the variable
  2785. `org-display-custom-times' is set. Time like %H:%M should be at the
  2786. end of the second format. The custom formats are also honored by export
  2787. commands, if custom time display is turned on at the time of export."
  2788. :group 'org-time
  2789. :type 'sexp)
  2790. (defun org-time-stamp-format (&optional long inactive)
  2791. "Get the right format for a time string."
  2792. (let ((f (if long (cdr org-time-stamp-formats)
  2793. (car org-time-stamp-formats))))
  2794. (if inactive
  2795. (concat "[" (substring f 1 -1) "]")
  2796. f)))
  2797. (defcustom org-deadline-warning-days 14
  2798. "Number of days before expiration during which a deadline becomes active.
  2799. This variable governs the display in sparse trees and in the agenda.
  2800. When 0 or negative, it means use this number (the absolute value of it)
  2801. even if a deadline has a different individual lead time specified.
  2802. Custom commands can set this variable in the options section."
  2803. :group 'org-time
  2804. :group 'org-agenda-daily/weekly
  2805. :type 'integer)
  2806. (defcustom org-scheduled-delay-days 0
  2807. "Number of days before a scheduled item becomes active.
  2808. This variable governs the display in sparse trees and in the agenda.
  2809. The default value (i.e. 0) means: don't delay scheduled item.
  2810. When negative, it means use this number (the absolute value of it)
  2811. even if a scheduled item has a different individual delay time
  2812. specified.
  2813. Custom commands can set this variable in the options section."
  2814. :group 'org-time
  2815. :group 'org-agenda-daily/weekly
  2816. :version "24.4"
  2817. :package-version '(Org . "8.0")
  2818. :type 'integer)
  2819. (defcustom org-read-date-prefer-future t
  2820. "Non-nil means assume future for incomplete date input from user.
  2821. This affects the following situations:
  2822. 1. The user gives a month but not a year.
  2823. For example, if it is April and you enter \"feb 2\", this will be read
  2824. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2825. 2. The user gives a day, but no month.
  2826. For example, if today is the 15th, and you enter \"3\", Org will read
  2827. this as the third of *next* month. However, if you enter \"17\",
  2828. it will be considered as *this* month.
  2829. If you set this variable to the symbol `time', then also the following
  2830. will work:
  2831. 3. If the user gives a time.
  2832. If the time is before now, it will be interpreted as tomorrow.
  2833. Currently none of this works for ISO week specifications.
  2834. When this option is nil, the current day, month and year will always be
  2835. used as defaults.
  2836. See also `org-agenda-jump-prefer-future'."
  2837. :group 'org-time
  2838. :type '(choice
  2839. (const :tag "Never" nil)
  2840. (const :tag "Check month and day" t)
  2841. (const :tag "Check month, day, and time" time)))
  2842. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2843. "Should the agenda jump command prefer the future for incomplete dates?
  2844. The default is to do the same as configured in `org-read-date-prefer-future'.
  2845. But you can also set a deviating value here.
  2846. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2847. :group 'org-agenda
  2848. :group 'org-time
  2849. :version "24.1"
  2850. :type '(choice
  2851. (const :tag "Use org-read-date-prefer-future"
  2852. org-read-date-prefer-future)
  2853. (const :tag "Never" nil)
  2854. (const :tag "Always" t)))
  2855. (defcustom org-read-date-force-compatible-dates t
  2856. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2857. Depending on the system Emacs is running on, certain dates cannot
  2858. be represented with the type used internally to represent time.
  2859. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2860. correctly. Some systems allow for earlier dates, some for later,
  2861. some for both. One way to find out it to insert any date into an
  2862. Org buffer, putting the cursor on the year and hitting S-up and
  2863. S-down to test the range.
  2864. When this variable is set to t, the date/time prompt will not let
  2865. you specify dates outside the 1970-2037 range, so it is certain that
  2866. these dates will work in whatever version of Emacs you are
  2867. running, and also that you can move a file from one Emacs implementation
  2868. to another. WHenever Org is forcing the year for you, it will display
  2869. a message and beep.
  2870. When this variable is nil, Org will check if the date is
  2871. representable in the specific Emacs implementation you are using.
  2872. If not, it will force a year, usually the current year, and beep
  2873. to remind you. Currently this setting is not recommended because
  2874. the likelihood that you will open your Org files in an Emacs that
  2875. has limited date range is not negligible.
  2876. A workaround for this problem is to use diary sexp dates for time
  2877. stamps outside of this range."
  2878. :group 'org-time
  2879. :version "24.1"
  2880. :type 'boolean)
  2881. (defcustom org-read-date-display-live t
  2882. "Non-nil means display current interpretation of date prompt live.
  2883. This display will be in an overlay, in the minibuffer."
  2884. :group 'org-time
  2885. :type 'boolean)
  2886. (defcustom org-read-date-popup-calendar t
  2887. "Non-nil means pop up a calendar when prompting for a date.
  2888. In the calendar, the date can be selected with mouse-1. However, the
  2889. minibuffer will also be active, and you can simply enter the date as well.
  2890. When nil, only the minibuffer will be available."
  2891. :group 'org-time
  2892. :type 'boolean)
  2893. (defvaralias 'org-popup-calendar-for-date-prompt
  2894. 'org-read-date-popup-calendar)
  2895. (defcustom org-extend-today-until 0
  2896. "The hour when your day really ends. Must be an integer.
  2897. This has influence for the following applications:
  2898. - When switching the agenda to \"today\". It it is still earlier than
  2899. the time given here, the day recognized as TODAY is actually yesterday.
  2900. - When a date is read from the user and it is still before the time given
  2901. here, the current date and time will be assumed to be yesterday, 23:59.
  2902. Also, timestamps inserted in capture templates follow this rule.
  2903. IMPORTANT: This is a feature whose implementation is and likely will
  2904. remain incomplete. Really, it is only here because past midnight seems to
  2905. be the favorite working time of John Wiegley :-)"
  2906. :group 'org-time
  2907. :type 'integer)
  2908. (defcustom org-use-effective-time nil
  2909. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2910. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2911. \"effective time\" of any timestamps between midnight and 8am will be
  2912. 23:59 of the previous day."
  2913. :group 'org-time
  2914. :version "24.1"
  2915. :type 'boolean)
  2916. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2917. "When non-nil, use the last clock out time for `org-todo'.
  2918. Note that this option has precedence over the combined use of
  2919. `org-use-effective-time' and `org-extend-today-until'."
  2920. :group 'org-time
  2921. :version "24.4"
  2922. :package-version '(Org . "8.0")
  2923. :type 'boolean)
  2924. (defcustom org-edit-timestamp-down-means-later nil
  2925. "Non-nil means S-down will increase the time in a time stamp.
  2926. When nil, S-up will increase."
  2927. :group 'org-time
  2928. :type 'boolean)
  2929. (defcustom org-calendar-follow-timestamp-change t
  2930. "Non-nil means make the calendar window follow timestamp changes.
  2931. When a timestamp is modified and the calendar window is visible, it will be
  2932. moved to the new date."
  2933. :group 'org-time
  2934. :type 'boolean)
  2935. (defgroup org-tags nil
  2936. "Options concerning tags in Org mode."
  2937. :tag "Org Tags"
  2938. :group 'org)
  2939. (defcustom org-tag-alist nil
  2940. "Default tags available in Org files.
  2941. The value of this variable is an alist. Associations either:
  2942. (TAG)
  2943. (TAG . SELECT)
  2944. (SPECIAL)
  2945. where TAG is a tag as a string, SELECT is character, used to
  2946. select that tag through the fast tag selection interface, and
  2947. SPECIAL is one of the following keywords: `:startgroup',
  2948. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2949. `:newline'. These keywords are used to define a hierarchy of
  2950. tags. See manual for details.
  2951. When this variable is nil, Org mode bases tag input on what is
  2952. already in the buffer. The value can be overridden locally by
  2953. using a TAGS keyword, e.g.,
  2954. #+TAGS: tag1 tag2
  2955. See also `org-tag-persistent-alist' to sidestep this behavior."
  2956. :group 'org-tags
  2957. :type '(repeat
  2958. (choice
  2959. (cons :tag "Tag with key"
  2960. (string :tag "Tag name")
  2961. (character :tag "Access char"))
  2962. (list :tag "Tag" (string :tag "Tag name"))
  2963. (const :tag "Start radio group" (:startgroup))
  2964. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2965. (const :tag "Group tags delimiter" (:grouptags))
  2966. (const :tag "End radio group" (:endgroup))
  2967. (const :tag "End tag group, non distinct" (:endgrouptag))
  2968. (const :tag "New line" (:newline)))))
  2969. (defcustom org-tag-persistent-alist nil
  2970. "Tags always available in Org files.
  2971. The value of this variable is an alist. Associations either:
  2972. (TAG)
  2973. (TAG . SELECT)
  2974. (SPECIAL)
  2975. where TAG is a tag as a string, SELECT is a character, used to
  2976. select that tag through the fast tag selection interface, and
  2977. SPECIAL is one of the following keywords: `:startgroup',
  2978. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2979. `:newline'. These keywords are used to define a hierarchy of
  2980. tags. See manual for details.
  2981. Unlike to `org-tag-alist', tags defined in this variable do not
  2982. depend on a local TAGS keyword. Instead, to disable these tags
  2983. on a per-file basis, insert anywhere in the file:
  2984. #+STARTUP: noptag"
  2985. :group 'org-tags
  2986. :type '(repeat
  2987. (choice
  2988. (cons :tag "Tag with key"
  2989. (string :tag "Tag name")
  2990. (character :tag "Access char"))
  2991. (list :tag "Tag" (string :tag "Tag name"))
  2992. (const :tag "Start radio group" (:startgroup))
  2993. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2994. (const :tag "Group tags delimiter" (:grouptags))
  2995. (const :tag "End radio group" (:endgroup))
  2996. (const :tag "End tag group, non distinct" (:endgrouptag))
  2997. (const :tag "New line" (:newline)))))
  2998. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2999. "If non-nil, always offer completion for all tags of all agenda files.
  3000. Instead of customizing this variable directly, you might want to
  3001. set it locally for capture buffers, because there no list of
  3002. tags in that file can be created dynamically (there are none).
  3003. (add-hook \\='org-capture-mode-hook
  3004. (lambda ()
  3005. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3006. :group 'org-tags
  3007. :version "24.1"
  3008. :type 'boolean)
  3009. (defvar org-file-tags nil
  3010. "List of tags that can be inherited by all entries in the file.
  3011. The tags will be inherited if the variable `org-use-tag-inheritance'
  3012. says they should be.
  3013. This variable is populated from #+FILETAGS lines.")
  3014. (defcustom org-use-fast-tag-selection 'auto
  3015. "Non-nil means use fast tag selection scheme.
  3016. This is a special interface to select and deselect tags with single keys.
  3017. When nil, fast selection is never used.
  3018. When the symbol `auto', fast selection is used if and only if selection
  3019. characters for tags have been configured, either through the variable
  3020. `org-tag-alist' or through a #+TAGS line in the buffer.
  3021. When t, fast selection is always used and selection keys are assigned
  3022. automatically if necessary."
  3023. :group 'org-tags
  3024. :type '(choice
  3025. (const :tag "Always" t)
  3026. (const :tag "Never" nil)
  3027. (const :tag "When selection characters are configured" auto)))
  3028. (defcustom org-fast-tag-selection-single-key nil
  3029. "Non-nil means fast tag selection exits after first change.
  3030. When nil, you have to press RET to exit it.
  3031. During fast tag selection, you can toggle this flag with `C-c'.
  3032. This variable can also have the value `expert'. In this case, the window
  3033. displaying the tags menu is not even shown, until you press C-c again."
  3034. :group 'org-tags
  3035. :type '(choice
  3036. (const :tag "No" nil)
  3037. (const :tag "Yes" t)
  3038. (const :tag "Expert" expert)))
  3039. (defvar org-fast-tag-selection-include-todo nil
  3040. "Non-nil means fast tags selection interface will also offer TODO states.
  3041. This is an undocumented feature, you should not rely on it.")
  3042. (defcustom org-tags-column -77
  3043. "The column to which tags should be indented in a headline.
  3044. If this number is positive, it specifies the column. If it is negative,
  3045. it means that the tags should be flushright to that column. For example,
  3046. -80 works well for a normal 80 character screen.
  3047. When 0, place tags directly after headline text, with only one space in
  3048. between."
  3049. :group 'org-tags
  3050. :type 'integer)
  3051. (defcustom org-auto-align-tags t
  3052. "Non-nil keeps tags aligned when modifying headlines.
  3053. Some operations (i.e. demoting) change the length of a headline and
  3054. therefore shift the tags around. With this option turned on, after
  3055. each such operation the tags are again aligned to `org-tags-column'."
  3056. :group 'org-tags
  3057. :type 'boolean)
  3058. (defcustom org-use-tag-inheritance t
  3059. "Non-nil means tags in levels apply also for sublevels.
  3060. When nil, only the tags directly given in a specific line apply there.
  3061. This may also be a list of tags that should be inherited, or a regexp that
  3062. matches tags that should be inherited. Additional control is possible
  3063. with the variable `org-tags-exclude-from-inheritance' which gives an
  3064. explicit list of tags to be excluded from inheritance, even if the value of
  3065. `org-use-tag-inheritance' would select it for inheritance.
  3066. If this option is t, a match early-on in a tree can lead to a large
  3067. number of matches in the subtree when constructing the agenda or creating
  3068. a sparse tree. If you only want to see the first match in a tree during
  3069. a search, check out the variable `org-tags-match-list-sublevels'."
  3070. :group 'org-tags
  3071. :type '(choice
  3072. (const :tag "Not" nil)
  3073. (const :tag "Always" t)
  3074. (repeat :tag "Specific tags" (string :tag "Tag"))
  3075. (regexp :tag "Tags matched by regexp")))
  3076. (defcustom org-tags-exclude-from-inheritance nil
  3077. "List of tags that should never be inherited.
  3078. This is a way to exclude a few tags from inheritance. For way to do
  3079. the opposite, to actively allow inheritance for selected tags,
  3080. see the variable `org-use-tag-inheritance'."
  3081. :group 'org-tags
  3082. :type '(repeat (string :tag "Tag")))
  3083. (defun org-tag-inherit-p (tag)
  3084. "Check if TAG is one that should be inherited."
  3085. (cond
  3086. ((member tag org-tags-exclude-from-inheritance) nil)
  3087. ((eq org-use-tag-inheritance t) t)
  3088. ((not org-use-tag-inheritance) nil)
  3089. ((stringp org-use-tag-inheritance)
  3090. (string-match org-use-tag-inheritance tag))
  3091. ((listp org-use-tag-inheritance)
  3092. (member tag org-use-tag-inheritance))
  3093. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3094. (defcustom org-tags-match-list-sublevels t
  3095. "Non-nil means list also sublevels of headlines matching a search.
  3096. This variable applies to tags/property searches, and also to stuck
  3097. projects because this search is based on a tags match as well.
  3098. When set to the symbol `indented', sublevels are indented with
  3099. leading dots.
  3100. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3101. the sublevels of a headline matching a tag search often also match
  3102. the same search. Listing all of them can create very long lists.
  3103. Setting this variable to nil causes subtrees of a match to be skipped.
  3104. This variable is semi-obsolete and probably should always be true. It
  3105. is better to limit inheritance to certain tags using the variables
  3106. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3107. :group 'org-tags
  3108. :type '(choice
  3109. (const :tag "No, don't list them" nil)
  3110. (const :tag "Yes, do list them" t)
  3111. (const :tag "List them, indented with leading dots" indented)))
  3112. (defcustom org-tags-sort-function nil
  3113. "When set, tags are sorted using this function as a comparator."
  3114. :group 'org-tags
  3115. :type '(choice
  3116. (const :tag "No sorting" nil)
  3117. (const :tag "Alphabetical" org-string-collate-lessp)
  3118. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3119. (function :tag "Custom function" nil)))
  3120. (defvar org-tags-history nil
  3121. "History of minibuffer reads for tags.")
  3122. (defvar org-last-tags-completion-table nil
  3123. "The last used completion table for tags.")
  3124. (defvar org-after-tags-change-hook nil
  3125. "Hook that is run after the tags in a line have changed.")
  3126. (defgroup org-properties nil
  3127. "Options concerning properties in Org mode."
  3128. :tag "Org Properties"
  3129. :group 'org)
  3130. (defcustom org-property-format "%-10s %s"
  3131. "How property key/value pairs should be formatted by `indent-line'.
  3132. When `indent-line' hits a property definition, it will format the line
  3133. according to this format, mainly to make sure that the values are
  3134. lined-up with respect to each other."
  3135. :group 'org-properties
  3136. :type 'string)
  3137. (defcustom org-properties-postprocess-alist nil
  3138. "Alist of properties and functions to adjust inserted values.
  3139. Elements of this alist must be of the form
  3140. ([string] [function])
  3141. where [string] must be a property name and [function] must be a
  3142. lambda expression: this lambda expression must take one argument,
  3143. the value to adjust, and return the new value as a string.
  3144. For example, this element will allow the property \"Remaining\"
  3145. to be updated wrt the relation between the \"Effort\" property
  3146. and the clock summary:
  3147. ((\"Remaining\" (lambda(value)
  3148. (let ((clocksum (org-clock-sum-current-item))
  3149. (effort (org-duration-to-minutes
  3150. (org-entry-get (point) \"Effort\"))))
  3151. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3152. :group 'org-properties
  3153. :version "24.1"
  3154. :type '(alist :key-type (string :tag "Property")
  3155. :value-type (function :tag "Function")))
  3156. (defcustom org-use-property-inheritance nil
  3157. "Non-nil means properties apply also for sublevels.
  3158. This setting is chiefly used during property searches. Turning it on can
  3159. cause significant overhead when doing a search, which is why it is not
  3160. on by default.
  3161. When nil, only the properties directly given in the current entry count.
  3162. When t, every property is inherited. The value may also be a list of
  3163. properties that should have inheritance, or a regular expression matching
  3164. properties that should be inherited.
  3165. However, note that some special properties use inheritance under special
  3166. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3167. and the properties ending in \"_ALL\" when they are used as descriptor
  3168. for valid values of a property.
  3169. Note for programmers:
  3170. When querying an entry with `org-entry-get', you can control if inheritance
  3171. should be used. By default, `org-entry-get' looks only at the local
  3172. properties. You can request inheritance by setting the inherit argument
  3173. to t (to force inheritance) or to `selective' (to respect the setting
  3174. in this variable)."
  3175. :group 'org-properties
  3176. :type '(choice
  3177. (const :tag "Not" nil)
  3178. (const :tag "Always" t)
  3179. (repeat :tag "Specific properties" (string :tag "Property"))
  3180. (regexp :tag "Properties matched by regexp")))
  3181. (defun org-property-inherit-p (property)
  3182. "Return a non-nil value if PROPERTY should be inherited."
  3183. (cond
  3184. ((eq org-use-property-inheritance t) t)
  3185. ((not org-use-property-inheritance) nil)
  3186. ((stringp org-use-property-inheritance)
  3187. (string-match org-use-property-inheritance property))
  3188. ((listp org-use-property-inheritance)
  3189. (member-ignore-case property org-use-property-inheritance))
  3190. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3191. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3192. "The default column format, if no other format has been defined.
  3193. This variable can be set on the per-file basis by inserting a line
  3194. #+COLUMNS: %25ITEM ....."
  3195. :group 'org-properties
  3196. :type 'string)
  3197. (defcustom org-columns-ellipses ".."
  3198. "The ellipses to be used when a field in column view is truncated.
  3199. When this is the empty string, as many characters as possible are shown,
  3200. but then there will be no visual indication that the field has been truncated.
  3201. When this is a string of length N, the last N characters of a truncated
  3202. field are replaced by this string. If the column is narrower than the
  3203. ellipses string, only part of the ellipses string will be shown."
  3204. :group 'org-properties
  3205. :type 'string)
  3206. (defconst org-global-properties-fixed
  3207. '(("VISIBILITY_ALL" . "folded children content all")
  3208. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3209. "List of property/value pairs that can be inherited by any entry.
  3210. These are fixed values, for the preset properties. The user variable
  3211. that can be used to add to this list is `org-global-properties'.
  3212. The entries in this list are cons cells where the car is a property
  3213. name and cdr is a string with the value. If the value represents
  3214. multiple items like an \"_ALL\" property, separate the items by
  3215. spaces.")
  3216. (defcustom org-global-properties nil
  3217. "List of property/value pairs that can be inherited by any entry.
  3218. This list will be combined with the constant `org-global-properties-fixed'.
  3219. The entries in this list are cons cells where the car is a property
  3220. name and cdr is a string with the value.
  3221. You can set buffer-local values for the same purpose in the variable
  3222. `org-file-properties' this by adding lines like
  3223. #+PROPERTY: NAME VALUE"
  3224. :group 'org-properties
  3225. :type '(repeat
  3226. (cons (string :tag "Property")
  3227. (string :tag "Value"))))
  3228. (defvar-local org-file-properties nil
  3229. "List of property/value pairs that can be inherited by any entry.
  3230. Valid for the current buffer.
  3231. This variable is populated from #+PROPERTY lines.")
  3232. (defgroup org-agenda nil
  3233. "Options concerning agenda views in Org mode."
  3234. :tag "Org Agenda"
  3235. :group 'org)
  3236. (defvar-local org-category nil
  3237. "Variable used by Org files to set a category for agenda display.
  3238. Such files should use a file variable to set it, for example
  3239. # -*- mode: org; org-category: \"ELisp\"
  3240. or contain a special line
  3241. #+CATEGORY: ELisp
  3242. If the file does not specify a category, then file's base name
  3243. is used instead.")
  3244. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3245. (defcustom org-agenda-files nil
  3246. "The files to be used for agenda display.
  3247. If an entry is a directory, all files in that directory that are matched
  3248. by `org-agenda-file-regexp' will be part of the file list.
  3249. If the value of the variable is not a list but a single file name, then
  3250. the list of agenda files is actually stored and maintained in that file,
  3251. one agenda file per line. In this file paths can be given relative to
  3252. `org-directory'. Tilde expansion and environment variable substitution
  3253. are also made.
  3254. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3255. and removed with `\\[org-remove-file]'."
  3256. :group 'org-agenda
  3257. :type '(choice
  3258. (repeat :tag "List of files and directories" file)
  3259. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3260. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3261. "Regular expression to match files for `org-agenda-files'.
  3262. If any element in the list in that variable contains a directory instead
  3263. of a normal file, all files in that directory that are matched by this
  3264. regular expression will be included."
  3265. :group 'org-agenda
  3266. :type 'regexp)
  3267. (defcustom org-agenda-text-search-extra-files nil
  3268. "List of extra files to be searched by text search commands.
  3269. These files will be searched in addition to the agenda files by the
  3270. commands `org-search-view' (`\\[org-agenda] s') \
  3271. and `org-occur-in-agenda-files'.
  3272. Note that these files will only be searched for text search commands,
  3273. not for the other agenda views like todo lists, tag searches or the weekly
  3274. agenda. This variable is intended to list notes and possibly archive files
  3275. that should also be searched by these two commands.
  3276. In fact, if the first element in the list is the symbol `agenda-archives',
  3277. then all archive files of all agenda files will be added to the search
  3278. scope."
  3279. :group 'org-agenda
  3280. :type '(set :greedy t
  3281. (const :tag "Agenda Archives" agenda-archives)
  3282. (repeat :inline t (file))))
  3283. (defvaralias 'org-agenda-multi-occur-extra-files
  3284. 'org-agenda-text-search-extra-files)
  3285. (defcustom org-agenda-skip-unavailable-files nil
  3286. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3287. A nil value means to remove them, after a query, from the list."
  3288. :group 'org-agenda
  3289. :type 'boolean)
  3290. (defcustom org-agenda-diary-file 'diary-file
  3291. "File to which to add new entries with the `i' key in agenda and calendar.
  3292. When this is the symbol `diary-file', the functionality in the Emacs
  3293. calendar will be used to add entries to the `diary-file'. But when this
  3294. points to a file, `org-agenda-diary-entry' will be used instead."
  3295. :group 'org-agenda
  3296. :type '(choice
  3297. (const :tag "The standard Emacs diary file" diary-file)
  3298. (file :tag "Special Org file diary entries")))
  3299. (defgroup org-latex nil
  3300. "Options for embedding LaTeX code into Org mode."
  3301. :tag "Org LaTeX"
  3302. :group 'org)
  3303. (defcustom org-format-latex-options
  3304. '(:foreground default :background default :scale 1.0
  3305. :html-foreground "Black" :html-background "Transparent"
  3306. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3307. "Options for creating images from LaTeX fragments.
  3308. This is a property list with the following properties:
  3309. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3310. `default' means use the foreground of the default face.
  3311. `auto' means use the foreground from the text face.
  3312. :background the background color, or \"Transparent\".
  3313. `default' means use the background of the default face.
  3314. `auto' means use the background from the text face.
  3315. :scale a scaling factor for the size of the images, to get more pixels
  3316. :html-foreground, :html-background, :html-scale
  3317. the same numbers for HTML export.
  3318. :matchers a list indicating which matchers should be used to
  3319. find LaTeX fragments. Valid members of this list are:
  3320. \"begin\" find environments
  3321. \"$1\" find single characters surrounded by $.$
  3322. \"$\" find math expressions surrounded by $...$
  3323. \"$$\" find math expressions surrounded by $$....$$
  3324. \"\\(\" find math expressions surrounded by \\(...\\)
  3325. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3326. :group 'org-latex
  3327. :type 'plist)
  3328. (defcustom org-format-latex-signal-error t
  3329. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3330. When nil, just push out a message."
  3331. :group 'org-latex
  3332. :version "24.1"
  3333. :type 'boolean)
  3334. (defcustom org-latex-to-mathml-jar-file nil
  3335. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3336. Use this to specify additional executable file say a jar file.
  3337. When using MathToWeb as the converter, specify the full-path to
  3338. your mathtoweb.jar file."
  3339. :group 'org-latex
  3340. :version "24.1"
  3341. :type '(choice
  3342. (const :tag "None" nil)
  3343. (file :tag "JAR file" :must-match t)))
  3344. (defcustom org-latex-to-mathml-convert-command nil
  3345. "Command to convert LaTeX fragments to MathML.
  3346. Replace format-specifiers in the command as noted below and use
  3347. `shell-command' to convert LaTeX to MathML.
  3348. %j: Executable file in fully expanded form as specified by
  3349. `org-latex-to-mathml-jar-file'.
  3350. %I: Input LaTeX file in fully expanded form.
  3351. %i: The latex fragment to be converted.
  3352. %o: Output MathML file.
  3353. This command is used by `org-create-math-formula'.
  3354. When using MathToWeb as the converter, set this option to
  3355. \"java -jar %j -unicode -force -df %o %I\".
  3356. When using LaTeXML set this option to
  3357. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3358. :group 'org-latex
  3359. :version "24.1"
  3360. :type '(choice
  3361. (const :tag "None" nil)
  3362. (string :tag "\nShell command")))
  3363. (defcustom org-preview-latex-default-process 'dvipng
  3364. "The default process to convert LaTeX fragments to image files.
  3365. All available processes and theirs documents can be found in
  3366. `org-preview-latex-process-alist', which see."
  3367. :group 'org-latex
  3368. :version "26.1"
  3369. :package-version '(Org . "9.0")
  3370. :type 'symbol)
  3371. (defcustom org-preview-latex-process-alist
  3372. '((dvipng
  3373. :programs ("latex" "dvipng")
  3374. :description "dvi > png"
  3375. :message "you need to install the programs: latex and dvipng."
  3376. :image-input-type "dvi"
  3377. :image-output-type "png"
  3378. :image-size-adjust (1.0 . 1.0)
  3379. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3380. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3381. (dvisvgm
  3382. :programs ("latex" "dvisvgm")
  3383. :description "dvi > svg"
  3384. :message "you need to install the programs: latex and dvisvgm."
  3385. :use-xcolor t
  3386. :image-input-type "dvi"
  3387. :image-output-type "svg"
  3388. :image-size-adjust (1.7 . 1.5)
  3389. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3390. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3391. (imagemagick
  3392. :programs ("latex" "convert")
  3393. :description "pdf > png"
  3394. :message "you need to install the programs: latex and imagemagick."
  3395. :use-xcolor t
  3396. :image-input-type "pdf"
  3397. :image-output-type "png"
  3398. :image-size-adjust (1.0 . 1.0)
  3399. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3400. :image-converter
  3401. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3402. "Definitions of external processes for LaTeX previewing.
  3403. Org mode can use some external commands to generate TeX snippet's images for
  3404. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3405. `org-create-formula-image' how to call them.
  3406. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3407. PROPERTIES accepts the following attributes:
  3408. :programs list of strings, required programs.
  3409. :description string, describe the process.
  3410. :message string, message it when required programs cannot be found.
  3411. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3412. :image-output-type string, output file type of image converter (e.g., \"png\").
  3413. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3414. deal with background and foreground color of image.
  3415. Otherwise, dvipng style background and foreground color
  3416. format are generated. You may then refer to them in
  3417. command options with \"%F\" and \"%B\".
  3418. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3419. image size showed in buffer and the cdr element is for
  3420. HTML file. This option is only useful for process
  3421. developers, users should use variable
  3422. `org-format-latex-options' instead.
  3423. :post-clean list of strings, files matched are to be cleaned up once
  3424. the image is generated. When nil, the files with \".dvi\",
  3425. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3426. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3427. be cleaned up.
  3428. :latex-header list of strings, the LaTeX header of the snippet file.
  3429. When nil, the fallback value is used instead, which is
  3430. controlled by `org-format-latex-header',
  3431. `org-latex-default-packages-alist' and
  3432. `org-latex-packages-alist', which see.
  3433. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3434. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3435. replaced with values defined below.
  3436. :image-converter list of image converter commands strings. Each of them is
  3437. given to the shell and supports any of the following
  3438. place-holders defined below.
  3439. Place-holders used by `:image-converter' and `:latex-compiler':
  3440. %f input file name
  3441. %b base name of input file
  3442. %o base directory of input file
  3443. %O absolute output file name
  3444. Place-holders only used by `:image-converter':
  3445. %F foreground of image
  3446. %B background of image
  3447. %D dpi, which is used to adjust image size by some processing commands.
  3448. %S the image size scale ratio, which is used to adjust image size by some
  3449. processing commands."
  3450. :group 'org-latex
  3451. :version "26.1"
  3452. :package-version '(Org . "9.0")
  3453. :type '(alist :tag "LaTeX to image backends"
  3454. :value-type (plist)))
  3455. (defcustom org-preview-latex-image-directory "ltximg/"
  3456. "Path to store latex preview images.
  3457. A relative path here creates many directories relative to the
  3458. processed Org files paths. An absolute path puts all preview
  3459. images at the same place."
  3460. :group 'org-latex
  3461. :version "26.1"
  3462. :package-version '(Org . "9.0")
  3463. :type 'string)
  3464. (defun org-format-latex-mathml-available-p ()
  3465. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3466. (save-match-data
  3467. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3468. org-latex-to-mathml-convert-command)
  3469. (let ((executable (car (split-string
  3470. org-latex-to-mathml-convert-command))))
  3471. (when (executable-find executable)
  3472. (if (string-match
  3473. "%j" org-latex-to-mathml-convert-command)
  3474. (file-readable-p org-latex-to-mathml-jar-file)
  3475. t))))))
  3476. (defcustom org-format-latex-header "\\documentclass{article}
  3477. \\usepackage[usenames]{color}
  3478. \[PACKAGES]
  3479. \[DEFAULT-PACKAGES]
  3480. \\pagestyle{empty} % do not remove
  3481. % The settings below are copied from fullpage.sty
  3482. \\setlength{\\textwidth}{\\paperwidth}
  3483. \\addtolength{\\textwidth}{-3cm}
  3484. \\setlength{\\oddsidemargin}{1.5cm}
  3485. \\addtolength{\\oddsidemargin}{-2.54cm}
  3486. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3487. \\setlength{\\textheight}{\\paperheight}
  3488. \\addtolength{\\textheight}{-\\headheight}
  3489. \\addtolength{\\textheight}{-\\headsep}
  3490. \\addtolength{\\textheight}{-\\footskip}
  3491. \\addtolength{\\textheight}{-3cm}
  3492. \\setlength{\\topmargin}{1.5cm}
  3493. \\addtolength{\\topmargin}{-2.54cm}"
  3494. "The document header used for processing LaTeX fragments.
  3495. It is imperative that this header make sure that no page number
  3496. appears on the page. The package defined in the variables
  3497. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3498. will either replace the placeholder \"[PACKAGES]\" in this
  3499. header, or they will be appended."
  3500. :group 'org-latex
  3501. :type 'string)
  3502. (defun org-set-packages-alist (var val)
  3503. "Set the packages alist and make sure it has 3 elements per entry."
  3504. (set var (mapcar (lambda (x)
  3505. (if (and (consp x) (= (length x) 2))
  3506. (list (car x) (nth 1 x) t)
  3507. x))
  3508. val)))
  3509. (defun org-get-packages-alist (var)
  3510. "Get the packages alist and make sure it has 3 elements per entry."
  3511. (mapcar (lambda (x)
  3512. (if (and (consp x) (= (length x) 2))
  3513. (list (car x) (nth 1 x) t)
  3514. x))
  3515. (default-value var)))
  3516. (defcustom org-latex-default-packages-alist
  3517. '(("AUTO" "inputenc" t ("pdflatex"))
  3518. ("T1" "fontenc" t ("pdflatex"))
  3519. ("" "graphicx" t)
  3520. ("" "grffile" t)
  3521. ("" "longtable" nil)
  3522. ("" "wrapfig" nil)
  3523. ("" "rotating" nil)
  3524. ("normalem" "ulem" t)
  3525. ("" "amsmath" t)
  3526. ("" "textcomp" t)
  3527. ("" "amssymb" t)
  3528. ("" "capt-of" nil)
  3529. ("" "hyperref" nil))
  3530. "Alist of default packages to be inserted in the header.
  3531. Change this only if one of the packages here causes an
  3532. incompatibility with another package you are using.
  3533. The packages in this list are needed by one part or another of
  3534. Org mode to function properly:
  3535. - inputenc, fontenc: for basic font and character selection
  3536. - graphicx: for including images
  3537. - grffile: allow periods and spaces in graphics file names
  3538. - longtable: For multipage tables
  3539. - wrapfig: for figure placement
  3540. - rotating: for sideways figures and tables
  3541. - ulem: for underline and strike-through
  3542. - amsmath: for subscript and superscript and math environments
  3543. - textcomp, amssymb: for various symbols used
  3544. for interpreting the entities in `org-entities'. You can skip
  3545. some of these packages if you don't use any of their symbols.
  3546. - capt-of: for captions outside of floats
  3547. - hyperref: for cross references
  3548. Therefore you should not modify this variable unless you know
  3549. what you are doing. The one reason to change it anyway is that
  3550. you might be loading some other package that conflicts with one
  3551. of the default packages. Each element is either a cell or
  3552. a string.
  3553. A cell is of the format
  3554. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3555. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3556. when compiling LaTeX snippets into images for inclusion into
  3557. non-LaTeX output. COMPILERS is a list of compilers that should
  3558. include the package, see `org-latex-compiler'. If the document
  3559. compiler is not in the list, and the list is non-nil, the package
  3560. will not be inserted in the final document.
  3561. A string will be inserted as-is in the header of the document."
  3562. :group 'org-latex
  3563. :group 'org-export-latex
  3564. :set 'org-set-packages-alist
  3565. :get 'org-get-packages-alist
  3566. :version "26.1"
  3567. :package-version '(Org . "8.3")
  3568. :type '(repeat
  3569. (choice
  3570. (list :tag "options/package pair"
  3571. (string :tag "options")
  3572. (string :tag "package")
  3573. (boolean :tag "Snippet")
  3574. (choice
  3575. (const :tag "For all compilers" nil)
  3576. (repeat :tag "Allowed compiler" string)))
  3577. (string :tag "A line of LaTeX"))))
  3578. (defcustom org-latex-packages-alist nil
  3579. "Alist of packages to be inserted in every LaTeX header.
  3580. These will be inserted after `org-latex-default-packages-alist'.
  3581. Each element is either a cell or a string.
  3582. A cell is of the format:
  3583. (\"options\" \"package\" SNIPPET-FLAG)
  3584. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3585. needed when turning LaTeX snippets into images for inclusion into
  3586. non-LaTeX output.
  3587. A string will be inserted as-is in the header of the document.
  3588. Make sure that you only list packages here which:
  3589. - you want in every file;
  3590. - do not conflict with the setup in `org-format-latex-header';
  3591. - do not conflict with the default packages in
  3592. `org-latex-default-packages-alist'."
  3593. :group 'org-latex
  3594. :group 'org-export-latex
  3595. :set 'org-set-packages-alist
  3596. :get 'org-get-packages-alist
  3597. :type '(repeat
  3598. (choice
  3599. (list :tag "options/package pair"
  3600. (string :tag "options")
  3601. (string :tag "package")
  3602. (boolean :tag "Snippet"))
  3603. (string :tag "A line of LaTeX"))))
  3604. (defgroup org-appearance nil
  3605. "Settings for Org mode appearance."
  3606. :tag "Org Appearance"
  3607. :group 'org)
  3608. (defcustom org-level-color-stars-only nil
  3609. "Non-nil means fontify only the stars in each headline.
  3610. When nil, the entire headline is fontified.
  3611. Changing it requires restart of `font-lock-mode' to become effective
  3612. also in regions already fontified."
  3613. :group 'org-appearance
  3614. :type 'boolean)
  3615. (defcustom org-hide-leading-stars nil
  3616. "Non-nil means hide the first N-1 stars in a headline.
  3617. This works by using the face `org-hide' for these stars. This
  3618. face is white for a light background, and black for a dark
  3619. background. You may have to customize the face `org-hide' to
  3620. make this work.
  3621. Changing it requires restart of `font-lock-mode' to become effective
  3622. also in regions already fontified.
  3623. You may also set this on a per-file basis by adding one of the following
  3624. lines to the buffer:
  3625. #+STARTUP: hidestars
  3626. #+STARTUP: showstars"
  3627. :group 'org-appearance
  3628. :type 'boolean)
  3629. (defcustom org-hidden-keywords nil
  3630. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3631. For example, a value \\='(title) for this list makes the document's title
  3632. appear in the buffer without the initial \"#+TITLE:\" part."
  3633. :group 'org-appearance
  3634. :version "24.1"
  3635. :type '(set (const :tag "#+AUTHOR" author)
  3636. (const :tag "#+DATE" date)
  3637. (const :tag "#+EMAIL" email)
  3638. (const :tag "#+TITLE" title)))
  3639. (defcustom org-custom-properties nil
  3640. "List of properties (as strings) with a special meaning.
  3641. The default use of these custom properties is to let the user
  3642. hide them with `org-toggle-custom-properties-visibility'."
  3643. :group 'org-properties
  3644. :group 'org-appearance
  3645. :version "24.3"
  3646. :type '(repeat (string :tag "Property Name")))
  3647. (defcustom org-fontify-done-headline nil
  3648. "Non-nil means change the face of a headline if it is marked DONE.
  3649. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3650. When this is non-nil, the headline after the keyword is set to the
  3651. `org-headline-done' as an additional indication."
  3652. :group 'org-appearance
  3653. :type 'boolean)
  3654. (defcustom org-fontify-emphasized-text t
  3655. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3656. Changing this variable requires a restart of Emacs to take effect."
  3657. :group 'org-appearance
  3658. :type 'boolean)
  3659. (defcustom org-fontify-whole-heading-line nil
  3660. "Non-nil means fontify the whole line for headings.
  3661. This is useful when setting a background color for the
  3662. org-level-* faces."
  3663. :group 'org-appearance
  3664. :type 'boolean)
  3665. (defcustom org-highlight-latex-and-related nil
  3666. "Non-nil means highlight LaTeX related syntax in the buffer.
  3667. When non nil, the value should be a list containing any of the
  3668. following symbols:
  3669. `latex' Highlight LaTeX snippets and environments.
  3670. `script' Highlight subscript and superscript.
  3671. `entities' Highlight entities."
  3672. :group 'org-appearance
  3673. :version "24.4"
  3674. :package-version '(Org . "8.0")
  3675. :type '(choice
  3676. (const :tag "No highlighting" nil)
  3677. (set :greedy t :tag "Highlight"
  3678. (const :tag "LaTeX snippets and environments" latex)
  3679. (const :tag "Subscript and superscript" script)
  3680. (const :tag "Entities" entities))))
  3681. (defcustom org-hide-emphasis-markers nil
  3682. "Non-nil mean font-lock should hide the emphasis marker characters."
  3683. :group 'org-appearance
  3684. :type 'boolean
  3685. :safe #'booleanp)
  3686. (defcustom org-hide-macro-markers nil
  3687. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3688. :group 'org-appearance
  3689. :type 'boolean)
  3690. (defcustom org-pretty-entities nil
  3691. "Non-nil means show entities as UTF8 characters.
  3692. When nil, the \\name form remains in the buffer."
  3693. :group 'org-appearance
  3694. :version "24.1"
  3695. :type 'boolean)
  3696. (defcustom org-pretty-entities-include-sub-superscripts t
  3697. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3698. :group 'org-appearance
  3699. :version "24.1"
  3700. :type 'boolean)
  3701. (defvar org-emph-re nil
  3702. "Regular expression for matching emphasis.
  3703. After a match, the match groups contain these elements:
  3704. 0 The match of the full regular expression, including the characters
  3705. before and after the proper match
  3706. 1 The character before the proper match, or empty at beginning of line
  3707. 2 The proper match, including the leading and trailing markers
  3708. 3 The leading marker like * or /, indicating the type of highlighting
  3709. 4 The text between the emphasis markers, not including the markers
  3710. 5 The character after the match, empty at the end of a line")
  3711. (defvar org-verbatim-re nil
  3712. "Regular expression for matching verbatim text.")
  3713. (defvar org-emphasis-regexp-components) ; defined just below
  3714. (defvar org-emphasis-alist) ; defined just below
  3715. (defun org-set-emph-re (var val)
  3716. "Set variable and compute the emphasis regular expression."
  3717. (set var val)
  3718. (when (and (boundp 'org-emphasis-alist)
  3719. (boundp 'org-emphasis-regexp-components)
  3720. org-emphasis-alist org-emphasis-regexp-components)
  3721. (pcase-let*
  3722. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3723. (body (if (<= nl 0) body
  3724. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3725. (template
  3726. (format (concat "\\([%s]\\|^\\)" ;before markers
  3727. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3728. "\\([%s]\\|$\\)") ;after markers
  3729. pre border border body border post)))
  3730. (setq org-emph-re (format template "*/_+"))
  3731. (setq org-verbatim-re (format template "=~")))))
  3732. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3733. ;; set this option proved cumbersome. See this message/thread:
  3734. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3735. (defvar org-emphasis-regexp-components
  3736. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3737. "Components used to build the regular expression for emphasis.
  3738. This is a list with five entries. Terminology: In an emphasis string
  3739. like \" *strong word* \", we call the initial space PREMATCH, the final
  3740. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3741. and \"trong wor\" is the body. The different components in this variable
  3742. specify what is allowed/forbidden in each part:
  3743. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3744. post Chars allowed as postmatch. End of line will be allowed too.
  3745. border The chars *forbidden* as border characters.
  3746. body-regexp A regexp like \".\" to match a body character. Don't use
  3747. non-shy groups here, and don't allow newline here.
  3748. newline The maximum number of newlines allowed in an emphasis exp.
  3749. You need to reload Org or to restart Emacs after setting this.")
  3750. (defcustom org-emphasis-alist
  3751. '(("*" bold)
  3752. ("/" italic)
  3753. ("_" underline)
  3754. ("=" org-verbatim verbatim)
  3755. ("~" org-code verbatim)
  3756. ("+" (:strike-through t)))
  3757. "Alist of characters and faces to emphasize text.
  3758. Text starting and ending with a special character will be emphasized,
  3759. for example *bold*, _underlined_ and /italic/. This variable sets the
  3760. marker characters and the face to be used by font-lock for highlighting
  3761. in Org buffers.
  3762. You need to reload Org or to restart Emacs after customizing this."
  3763. :group 'org-appearance
  3764. :set 'org-set-emph-re
  3765. :version "24.4"
  3766. :package-version '(Org . "8.0")
  3767. :type '(repeat
  3768. (list
  3769. (string :tag "Marker character")
  3770. (choice
  3771. (face :tag "Font-lock-face")
  3772. (plist :tag "Face property list"))
  3773. (option (const verbatim)))))
  3774. (defvar org-protecting-blocks '("src" "example" "export")
  3775. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3776. This is needed for font-lock setup.")
  3777. ;;; Functions and variables from their packages
  3778. ;; Declared here to avoid compiler warnings
  3779. (defvar mark-active)
  3780. ;; Various packages
  3781. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3782. (declare-function calendar-forward-day "cal-move" (arg))
  3783. (declare-function calendar-goto-date "cal-move" (date))
  3784. (declare-function calendar-goto-today "cal-move" ())
  3785. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3786. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3787. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3788. (declare-function cdlatex-tab "ext:cdlatex" ())
  3789. (declare-function dired-get-filename
  3790. "dired"
  3791. (&optional localp no-error-if-not-filep))
  3792. (declare-function iswitchb-read-buffer
  3793. "iswitchb"
  3794. (prompt &optional
  3795. default require-match _predicate start matches-set))
  3796. (declare-function org-agenda-change-all-lines
  3797. "org-agenda"
  3798. (newhead hdmarker &optional fixface just-this))
  3799. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3800. "org-agenda"
  3801. (&optional end))
  3802. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3803. (declare-function org-agenda-format-item
  3804. "org-agenda"
  3805. (extra txt &optional level category tags dotime
  3806. remove-re habitp))
  3807. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3808. (declare-function org-agenda-save-markers-for-cut-and-paste
  3809. "org-agenda"
  3810. (beg end))
  3811. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3812. (declare-function org-agenda-skip "org-agenda" ())
  3813. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3814. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3815. (declare-function org-indent-mode "org-indent" (&optional arg))
  3816. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3817. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3818. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3819. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3820. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3821. (declare-function parse-time-string "parse-time" (string))
  3822. (defvar align-mode-rules-list)
  3823. (defvar calc-embedded-close-formula)
  3824. (defvar calc-embedded-open-formula)
  3825. (defvar calc-embedded-open-mode)
  3826. (defvar font-lock-unfontify-region-function)
  3827. (defvar iswitchb-temp-buflist)
  3828. (defvar org-agenda-tags-todo-honor-ignore-options)
  3829. (defvar remember-data-file)
  3830. (defvar texmathp-why)
  3831. ;;;###autoload
  3832. (defun turn-on-orgtbl ()
  3833. "Unconditionally turn on `orgtbl-mode'."
  3834. (require 'org-table)
  3835. (orgtbl-mode 1))
  3836. (defun org-at-table-p (&optional table-type)
  3837. "Non-nil if the cursor is inside an Org table.
  3838. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3839. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3840. (or (not (derived-mode-p 'org-mode))
  3841. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3842. (and e (or table-type
  3843. (eq 'org (org-element-property :type e))))))))
  3844. (defun org-at-table.el-p ()
  3845. "Non-nil when point is at a table.el table."
  3846. (and (org-match-line "[ \t]*[|+]")
  3847. (let ((element (org-element-at-point)))
  3848. (and (eq (org-element-type element) 'table)
  3849. (eq (org-element-property :type element) 'table.el)))))
  3850. (defun org-at-table-hline-p ()
  3851. "Non-nil when point is inside a hline in a table.
  3852. Assume point is already in a table."
  3853. (org-match-line org-table-hline-regexp))
  3854. (defun org-table-map-tables (function &optional quietly)
  3855. "Apply FUNCTION to the start of all tables in the buffer."
  3856. (org-with-wide-buffer
  3857. (goto-char (point-min))
  3858. (while (re-search-forward org-table-any-line-regexp nil t)
  3859. (unless quietly
  3860. (message "Mapping tables: %d%%"
  3861. (floor (* 100.0 (point)) (buffer-size))))
  3862. (beginning-of-line 1)
  3863. (when (and (looking-at org-table-line-regexp)
  3864. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3865. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3866. (save-excursion (funcall function))
  3867. (or (looking-at org-table-line-regexp)
  3868. (forward-char 1)))
  3869. (re-search-forward org-table-any-border-regexp nil 1)))
  3870. (unless quietly (message "Mapping tables: done")))
  3871. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3872. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3873. (declare-function org-resolve-clocks "org-clock"
  3874. (&optional also-non-dangling-p prompt last-valid))
  3875. (defun org-at-TBLFM-p (&optional pos)
  3876. "Non-nil when point (or POS) is in #+TBLFM line."
  3877. (save-excursion
  3878. (goto-char (or pos (point)))
  3879. (beginning-of-line)
  3880. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3881. (eq (org-element-type (org-element-at-point)) 'table))))
  3882. (defvar org-clock-start-time)
  3883. (defvar org-clock-marker (make-marker)
  3884. "Marker recording the last clock-in.")
  3885. (defvar org-clock-hd-marker (make-marker)
  3886. "Marker recording the last clock-in, but the headline position.")
  3887. (defvar org-clock-heading ""
  3888. "The heading of the current clock entry.")
  3889. (defun org-clock-is-active ()
  3890. "Return the buffer where the clock is currently running.
  3891. Return nil if no clock is running."
  3892. (marker-buffer org-clock-marker))
  3893. (defun org-check-running-clock ()
  3894. "Check if the current buffer contains the running clock.
  3895. If yes, offer to stop it and to save the buffer with the changes."
  3896. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3897. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3898. (buffer-name))))
  3899. (org-clock-out)
  3900. (when (y-or-n-p "Save changed buffer?")
  3901. (save-buffer))))
  3902. (defun org-clocktable-try-shift (dir n)
  3903. "Check if this line starts a clock table, if yes, shift the time block."
  3904. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3905. (org-clocktable-shift dir n)))
  3906. ;;;###autoload
  3907. (defun org-clock-persistence-insinuate ()
  3908. "Set up hooks for clock persistence."
  3909. (require 'org-clock)
  3910. (add-hook 'org-mode-hook 'org-clock-load)
  3911. (add-hook 'kill-emacs-hook 'org-clock-save))
  3912. (defgroup org-archive nil
  3913. "Options concerning archiving in Org mode."
  3914. :tag "Org Archive"
  3915. :group 'org-structure)
  3916. (defcustom org-archive-location "%s_archive::"
  3917. "The location where subtrees should be archived.
  3918. The value of this variable is a string, consisting of two parts,
  3919. separated by a double-colon. The first part is a filename and
  3920. the second part is a headline.
  3921. When the filename is omitted, archiving happens in the same file.
  3922. %s in the filename will be replaced by the current file
  3923. name (without the directory part). Archiving to a different file
  3924. is useful to keep archived entries from contributing to the
  3925. Org Agenda.
  3926. The archived entries will be filed as subtrees of the specified
  3927. headline. When the headline is omitted, the subtrees are simply
  3928. filed away at the end of the file, as top-level entries. Also in
  3929. the heading you can use %s to represent the file name, this can be
  3930. useful when using the same archive for a number of different files.
  3931. Here are a few examples:
  3932. \"%s_archive::\"
  3933. If the current file is Projects.org, archive in file
  3934. Projects.org_archive, as top-level trees. This is the default.
  3935. \"::* Archived Tasks\"
  3936. Archive in the current file, under the top-level headline
  3937. \"* Archived Tasks\".
  3938. \"~/org/archive.org::\"
  3939. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3940. \"~/org/archive.org::* From %s\"
  3941. Archive in file ~/org/archive.org (absolute path), under headlines
  3942. \"From FILENAME\" where file name is the current file name.
  3943. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3944. The \"datetree/\" string is special, signifying to archive
  3945. items to the datetree. Items are placed in either the CLOSED
  3946. date of the item, or the current date if there is no CLOSED date.
  3947. The heading will be a subentry to the current date. There doesn't
  3948. need to be a heading, but there always needs to be a slash after
  3949. datetree. For example, to store archived items directly in the
  3950. datetree, use \"~/org/datetree.org::datetree/\".
  3951. \"basement::** Finished Tasks\"
  3952. Archive in file ./basement (relative path), as level 3 trees
  3953. below the level 2 heading \"** Finished Tasks\".
  3954. You may set this option on a per-file basis by adding to the buffer a
  3955. line like
  3956. #+ARCHIVE: basement::** Finished Tasks
  3957. You may also define it locally for a subtree by setting an ARCHIVE property
  3958. in the entry. If such a property is found in an entry, or anywhere up
  3959. the hierarchy, it will be used."
  3960. :group 'org-archive
  3961. :type 'string)
  3962. (defcustom org-agenda-skip-archived-trees t
  3963. "Non-nil means the agenda will skip any items located in archived trees.
  3964. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3965. variable is no longer recommended, you should leave it at the value t.
  3966. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3967. :group 'org-archive
  3968. :group 'org-agenda-skip
  3969. :type 'boolean)
  3970. (defcustom org-columns-skip-archived-trees t
  3971. "Non-nil means ignore archived trees when creating column view."
  3972. :group 'org-archive
  3973. :group 'org-properties
  3974. :type 'boolean)
  3975. (defcustom org-cycle-open-archived-trees nil
  3976. "Non-nil means `org-cycle' will open archived trees.
  3977. An archived tree is a tree marked with the tag ARCHIVE.
  3978. When nil, archived trees will stay folded. You can still open them with
  3979. normal outline commands like `show-all', but not with the cycling commands."
  3980. :group 'org-archive
  3981. :group 'org-cycle
  3982. :type 'boolean)
  3983. (defcustom org-sparse-tree-open-archived-trees nil
  3984. "Non-nil means sparse tree construction shows matches in archived trees.
  3985. When nil, matches in these trees are highlighted, but the trees are kept in
  3986. collapsed state."
  3987. :group 'org-archive
  3988. :group 'org-sparse-trees
  3989. :type 'boolean)
  3990. (defcustom org-sparse-tree-default-date-type nil
  3991. "The default date type when building a sparse tree.
  3992. When this is nil, a date is a scheduled or a deadline timestamp.
  3993. Otherwise, these types are allowed:
  3994. all: all timestamps
  3995. active: only active timestamps (<...>)
  3996. inactive: only inactive timestamps ([...])
  3997. scheduled: only scheduled timestamps
  3998. deadline: only deadline timestamps"
  3999. :type '(choice (const :tag "Scheduled or deadline" nil)
  4000. (const :tag "All timestamps" all)
  4001. (const :tag "Only active timestamps" active)
  4002. (const :tag "Only inactive timestamps" inactive)
  4003. (const :tag "Only scheduled timestamps" scheduled)
  4004. (const :tag "Only deadline timestamps" deadline)
  4005. (const :tag "Only closed timestamps" closed))
  4006. :version "26.1"
  4007. :package-version '(Org . "8.3")
  4008. :group 'org-sparse-trees)
  4009. (defun org-cycle-hide-archived-subtrees (state)
  4010. "Re-hide all archived subtrees after a visibility state change.
  4011. STATE should be one of the symbols listed in the docstring of
  4012. `org-cycle-hook'."
  4013. (when (and (not org-cycle-open-archived-trees)
  4014. (not (memq state '(overview folded))))
  4015. (save-excursion
  4016. (let* ((globalp (memq state '(contents all)))
  4017. (beg (if globalp (point-min) (point)))
  4018. (end (if globalp (point-max) (org-end-of-subtree t))))
  4019. (org-hide-archived-subtrees beg end)
  4020. (goto-char beg)
  4021. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4022. (message "%s" (substitute-command-keys
  4023. "Subtree is archived and stays closed. Use \
  4024. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4025. (defun org-force-cycle-archived ()
  4026. "Cycle subtree even if it is archived."
  4027. (interactive)
  4028. (setq this-command 'org-cycle)
  4029. (let ((org-cycle-open-archived-trees t))
  4030. (call-interactively 'org-cycle)))
  4031. (defun org-hide-archived-subtrees (beg end)
  4032. "Re-hide all archived subtrees after a visibility state change."
  4033. (org-with-wide-buffer
  4034. (let ((case-fold-search nil)
  4035. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4036. (goto-char beg)
  4037. ;; Include headline point is currently on.
  4038. (beginning-of-line)
  4039. (while (and (< (point) end) (re-search-forward re end t))
  4040. (when (member org-archive-tag (org-get-tags nil t))
  4041. (org-flag-subtree t)
  4042. (org-end-of-subtree t))))))
  4043. (defun org-flag-subtree (flag)
  4044. (save-excursion
  4045. (org-back-to-heading t)
  4046. (org-flag-region (line-end-position)
  4047. (progn (org-end-of-subtree t) (point))
  4048. flag
  4049. 'outline)))
  4050. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4051. ;; Declare Column View Code
  4052. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4053. (declare-function org-columns-compute "org-colview" (property))
  4054. ;; Declare ID code
  4055. (declare-function org-id-store-link "org-id")
  4056. (declare-function org-id-locations-load "org-id")
  4057. (declare-function org-id-locations-save "org-id")
  4058. (defvar org-id-track-globally)
  4059. ;;; Variables for pre-computed regular expressions, all buffer local
  4060. (defvar-local org-todo-regexp nil
  4061. "Matches any of the TODO state keywords.
  4062. Since TODO keywords are case-sensitive, `case-fold-search' is
  4063. expected to be bound to nil when matching against this regexp.")
  4064. (defvar-local org-not-done-regexp nil
  4065. "Matches any of the TODO state keywords except the last one.
  4066. Since TODO keywords are case-sensitive, `case-fold-search' is
  4067. expected to be bound to nil when matching against this regexp.")
  4068. (defvar-local org-not-done-heading-regexp nil
  4069. "Matches a TODO headline that is not done.
  4070. Since TODO keywords are case-sensitive, `case-fold-search' is
  4071. expected to be bound to nil when matching against this regexp.")
  4072. (defvar-local org-todo-line-regexp nil
  4073. "Matches a headline and puts TODO state into group 2 if present.
  4074. Since TODO keywords are case-sensitive, `case-fold-search' is
  4075. expected to be bound to nil when matching against this regexp.")
  4076. (defvar-local org-complex-heading-regexp nil
  4077. "Matches a headline and puts everything into groups:
  4078. group 1: Stars
  4079. group 2: The TODO keyword, maybe
  4080. group 3: Priority cookie
  4081. group 4: True headline
  4082. group 5: Tags
  4083. Since TODO keywords are case-sensitive, `case-fold-search' is
  4084. expected to be bound to nil when matching against this regexp.")
  4085. (defvar-local org-complex-heading-regexp-format nil
  4086. "Printf format to make regexp to match an exact headline.
  4087. This regexp will match the headline of any node which has the
  4088. exact headline text that is put into the format, but may have any
  4089. TODO state, priority and tags.")
  4090. (defvar-local org-todo-line-tags-regexp nil
  4091. "Matches a headline and puts TODO state into group 2 if present.
  4092. Also put tags into group 4 if tags are present.")
  4093. (defconst org-plain-time-of-day-regexp
  4094. (concat
  4095. "\\(\\<[012]?[0-9]"
  4096. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4097. "\\(--?"
  4098. "\\(\\<[012]?[0-9]"
  4099. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4100. "\\)?")
  4101. "Regular expression to match a plain time or time range.
  4102. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4103. groups carry important information:
  4104. 0 the full match
  4105. 1 the first time, range or not
  4106. 8 the second time, if it is a range.")
  4107. (defconst org-plain-time-extension-regexp
  4108. (concat
  4109. "\\(\\<[012]?[0-9]"
  4110. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4111. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4112. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4113. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4114. groups carry important information:
  4115. 0 the full match
  4116. 7 hours of duration
  4117. 9 minutes of duration")
  4118. (defconst org-stamp-time-of-day-regexp
  4119. (concat
  4120. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4121. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4122. "\\(--?"
  4123. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4124. "Regular expression to match a timestamp time or time range.
  4125. After a match, the following groups carry important information:
  4126. 0 the full match
  4127. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4128. 2 the first time, range or not
  4129. 4 the second time, if it is a range.")
  4130. (defconst org-startup-options
  4131. '(("fold" org-startup-folded t)
  4132. ("overview" org-startup-folded t)
  4133. ("nofold" org-startup-folded nil)
  4134. ("showall" org-startup-folded nil)
  4135. ("showeverything" org-startup-folded showeverything)
  4136. ("content" org-startup-folded content)
  4137. ("indent" org-startup-indented t)
  4138. ("noindent" org-startup-indented nil)
  4139. ("hidestars" org-hide-leading-stars t)
  4140. ("showstars" org-hide-leading-stars nil)
  4141. ("odd" org-odd-levels-only t)
  4142. ("oddeven" org-odd-levels-only nil)
  4143. ("align" org-startup-align-all-tables t)
  4144. ("noalign" org-startup-align-all-tables nil)
  4145. ("shrink" org-startup-shrink-all-tables t)
  4146. ("inlineimages" org-startup-with-inline-images t)
  4147. ("noinlineimages" org-startup-with-inline-images nil)
  4148. ("latexpreview" org-startup-with-latex-preview t)
  4149. ("nolatexpreview" org-startup-with-latex-preview nil)
  4150. ("customtime" org-display-custom-times t)
  4151. ("logdone" org-log-done time)
  4152. ("lognotedone" org-log-done note)
  4153. ("nologdone" org-log-done nil)
  4154. ("lognoteclock-out" org-log-note-clock-out t)
  4155. ("nolognoteclock-out" org-log-note-clock-out nil)
  4156. ("logrepeat" org-log-repeat state)
  4157. ("lognoterepeat" org-log-repeat note)
  4158. ("logdrawer" org-log-into-drawer t)
  4159. ("nologdrawer" org-log-into-drawer nil)
  4160. ("logstatesreversed" org-log-states-order-reversed t)
  4161. ("nologstatesreversed" org-log-states-order-reversed nil)
  4162. ("nologrepeat" org-log-repeat nil)
  4163. ("logreschedule" org-log-reschedule time)
  4164. ("lognotereschedule" org-log-reschedule note)
  4165. ("nologreschedule" org-log-reschedule nil)
  4166. ("logredeadline" org-log-redeadline time)
  4167. ("lognoteredeadline" org-log-redeadline note)
  4168. ("nologredeadline" org-log-redeadline nil)
  4169. ("logrefile" org-log-refile time)
  4170. ("lognoterefile" org-log-refile note)
  4171. ("nologrefile" org-log-refile nil)
  4172. ("fninline" org-footnote-define-inline t)
  4173. ("nofninline" org-footnote-define-inline nil)
  4174. ("fnlocal" org-footnote-section nil)
  4175. ("fnauto" org-footnote-auto-label t)
  4176. ("fnprompt" org-footnote-auto-label nil)
  4177. ("fnconfirm" org-footnote-auto-label confirm)
  4178. ("fnplain" org-footnote-auto-label plain)
  4179. ("fnadjust" org-footnote-auto-adjust t)
  4180. ("nofnadjust" org-footnote-auto-adjust nil)
  4181. ("constcgs" constants-unit-system cgs)
  4182. ("constSI" constants-unit-system SI)
  4183. ("noptag" org-tag-persistent-alist nil)
  4184. ("hideblocks" org-hide-block-startup t)
  4185. ("nohideblocks" org-hide-block-startup nil)
  4186. ("beamer" org-startup-with-beamer-mode t)
  4187. ("entitiespretty" org-pretty-entities t)
  4188. ("entitiesplain" org-pretty-entities nil))
  4189. "Variable associated with STARTUP options for Org.
  4190. Each element is a list of three items: the startup options (as written
  4191. in the #+STARTUP line), the corresponding variable, and the value to set
  4192. this variable to if the option is found. An optional forth element PUSH
  4193. means to push this value onto the list in the variable.")
  4194. (defcustom org-group-tags t
  4195. "When non-nil (the default), use group tags.
  4196. This can be turned on/off through `org-toggle-tags-groups'."
  4197. :group 'org-tags
  4198. :group 'org-startup
  4199. :type 'boolean)
  4200. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4201. (defun org-toggle-tags-groups ()
  4202. "Toggle support for group tags.
  4203. Support for group tags is controlled by the option
  4204. `org-group-tags', which is non-nil by default."
  4205. (interactive)
  4206. (setq org-group-tags (not org-group-tags))
  4207. (cond ((and (derived-mode-p 'org-agenda-mode)
  4208. org-group-tags)
  4209. (org-agenda-redo))
  4210. ((derived-mode-p 'org-mode)
  4211. (let ((org-inhibit-startup t)) (org-mode))))
  4212. (message "Groups tags support has been turned %s"
  4213. (if org-group-tags "on" "off")))
  4214. (defun org--tag-add-to-alist (alist1 alist2)
  4215. "Merge tags from ALIST1 into ALIST2.
  4216. Duplicates tags outside a group are removed. Keywords and order
  4217. are preserved.
  4218. The function assumes ALIST1 and ALIST2 are proper tag alists.
  4219. See `org-tag-alist' for their structure."
  4220. (cond
  4221. ((null alist2) alist1)
  4222. ((null alist1) alist2)
  4223. (t
  4224. (let ((to-add nil)
  4225. (group-flag nil))
  4226. (dolist (tag-pair alist1)
  4227. (pcase tag-pair
  4228. (`(,(or :startgrouptag :startgroup))
  4229. (setq group-flag t)
  4230. (push tag-pair to-add))
  4231. (`(,(or :endgrouptag :endgroup))
  4232. (setq group-flag nil)
  4233. (push tag-pair to-add))
  4234. (`(,(or :grouptags :newline))
  4235. (push tag-pair to-add))
  4236. (`(,tag . ,_)
  4237. ;; Remove duplicates from ALIST1, unless they are in
  4238. ;; a group. Indeed, it makes sense to have a tag appear in
  4239. ;; multiple groups.
  4240. (when (or group-flag (not (assoc tag alist2)))
  4241. (push tag-pair to-add)))
  4242. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  4243. ;; Preserve order of ALIST1.
  4244. (append (nreverse to-add) alist2)))))
  4245. (defun org-set-regexps-and-options (&optional tags-only)
  4246. "Precompute regular expressions used in the current buffer.
  4247. When optional argument TAGS-ONLY is non-nil, only compute tags
  4248. related expressions."
  4249. (when (derived-mode-p 'org-mode)
  4250. (let ((alist (org--setup-collect-keywords
  4251. (org-make-options-regexp
  4252. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4253. (and (not tags-only)
  4254. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4255. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4256. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4257. ;; Startup options. Get this early since it does change
  4258. ;; behavior for other options (e.g., tags).
  4259. (let ((startup (cdr (assq 'startup alist))))
  4260. (dolist (option startup)
  4261. (let ((entry (assoc-string option org-startup-options t)))
  4262. (when entry
  4263. (let ((var (nth 1 entry))
  4264. (val (nth 2 entry)))
  4265. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4266. (unless (listp (symbol-value var))
  4267. (set (make-local-variable var) nil))
  4268. (add-to-list var val)))))))
  4269. (setq-local org-file-tags
  4270. (mapcar #'org-add-prop-inherited
  4271. (cdr (assq 'filetags alist))))
  4272. (setq org-current-tag-alist
  4273. (org--tag-add-to-alist
  4274. org-tag-persistent-alist
  4275. (let ((tags (cdr (assq 'tags alist))))
  4276. (if tags (org-tag-string-to-alist tags)
  4277. org-tag-alist))))
  4278. (setq org-tag-groups-alist
  4279. (org-tag-alist-to-groups org-current-tag-alist))
  4280. (unless tags-only
  4281. ;; File properties.
  4282. (setq-local org-file-properties (cdr (assq 'property alist)))
  4283. ;; Archive location.
  4284. (let ((archive (cdr (assq 'archive alist))))
  4285. (when archive (setq-local org-archive-location archive)))
  4286. ;; Category.
  4287. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4288. (when cat
  4289. (setq-local org-category (intern cat))
  4290. (setq-local org-file-properties
  4291. (org--update-property-plist
  4292. "CATEGORY" cat org-file-properties))))
  4293. ;; Columns.
  4294. (let ((column (cdr (assq 'columns alist))))
  4295. (when column (setq-local org-columns-default-format column)))
  4296. ;; Constants.
  4297. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4298. ;; Link abbreviations.
  4299. (let ((links (cdr (assq 'link alist))))
  4300. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4301. ;; Priorities.
  4302. (let ((priorities (cdr (assq 'priorities alist))))
  4303. (when priorities
  4304. (setq-local org-highest-priority (nth 0 priorities))
  4305. (setq-local org-lowest-priority (nth 1 priorities))
  4306. (setq-local org-default-priority (nth 2 priorities))))
  4307. ;; Scripts.
  4308. (let ((scripts (assq 'scripts alist)))
  4309. (when scripts
  4310. (setq-local org-use-sub-superscripts (cdr scripts))))
  4311. ;; TODO keywords.
  4312. (setq-local org-todo-kwd-alist nil)
  4313. (setq-local org-todo-key-alist nil)
  4314. (setq-local org-todo-key-trigger nil)
  4315. (setq-local org-todo-keywords-1 nil)
  4316. (setq-local org-done-keywords nil)
  4317. (setq-local org-todo-heads nil)
  4318. (setq-local org-todo-sets nil)
  4319. (setq-local org-todo-log-states nil)
  4320. (let ((todo-sequences
  4321. (or (nreverse (cdr (assq 'todo alist)))
  4322. (let ((d (default-value 'org-todo-keywords)))
  4323. (if (not (stringp (car d))) d
  4324. ;; XXX: Backward compatibility code.
  4325. (list (cons org-todo-interpretation d)))))))
  4326. (dolist (sequence todo-sequences)
  4327. (let* ((sequence (or (run-hook-with-args-until-success
  4328. 'org-todo-setup-filter-hook sequence)
  4329. sequence))
  4330. (sequence-type (car sequence))
  4331. (keywords (cdr sequence))
  4332. (sep (member "|" keywords))
  4333. names alist)
  4334. (dolist (k (remove "|" keywords))
  4335. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4336. k)
  4337. (error "Invalid TODO keyword %s" k))
  4338. (let ((name (match-string 1 k))
  4339. (key (match-string 2 k))
  4340. (log (org-extract-log-state-settings k)))
  4341. (push name names)
  4342. (push (cons name (and key (string-to-char key))) alist)
  4343. (when log (push log org-todo-log-states))))
  4344. (let* ((names (nreverse names))
  4345. (done (if sep (org-remove-keyword-keys (cdr sep))
  4346. (last names)))
  4347. (head (car names))
  4348. (tail (list sequence-type head (car done) (org-last done))))
  4349. (add-to-list 'org-todo-heads head 'append)
  4350. (push names org-todo-sets)
  4351. (setq org-done-keywords (append org-done-keywords done nil))
  4352. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4353. (setq org-todo-key-alist
  4354. (append org-todo-key-alist
  4355. (and alist
  4356. (append '((:startgroup))
  4357. (nreverse alist)
  4358. '((:endgroup))))))
  4359. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4360. (setq org-todo-sets (nreverse org-todo-sets)
  4361. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4362. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4363. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4364. ;; Compute the regular expressions and other local variables.
  4365. ;; Using `org-outline-regexp-bol' would complicate them much,
  4366. ;; because of the fixed white space at the end of that string.
  4367. (unless org-done-keywords
  4368. (setq org-done-keywords
  4369. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4370. (setq org-not-done-keywords
  4371. (org-delete-all org-done-keywords
  4372. (copy-sequence org-todo-keywords-1))
  4373. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4374. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4375. org-not-done-heading-regexp
  4376. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4377. org-todo-line-regexp
  4378. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4379. org-complex-heading-regexp
  4380. (concat "^\\(\\*+\\)"
  4381. "\\(?: +" org-todo-regexp "\\)?"
  4382. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4383. "\\(?: +\\(.*?\\)\\)??"
  4384. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4385. "[ \t]*$")
  4386. org-complex-heading-regexp-format
  4387. (concat "^\\(\\*+\\)"
  4388. "\\(?: +" org-todo-regexp "\\)?"
  4389. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4390. "\\(?: +"
  4391. ;; Stats cookies can be stuck to body.
  4392. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4393. "\\(%s\\)"
  4394. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4395. "\\)"
  4396. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4397. "[ \t]*$")
  4398. org-todo-line-tags-regexp
  4399. (concat "^\\(\\*+\\)"
  4400. "\\(?: +" org-todo-regexp "\\)?"
  4401. "\\(?: +\\(.*?\\)\\)??"
  4402. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4403. "[ \t]*$"))
  4404. (org-compute-latex-and-related-regexp)))))
  4405. (defun org--setup-collect-keywords (regexp &optional files alist)
  4406. "Return setup keywords values as an alist.
  4407. REGEXP matches a subset of setup keywords. FILES is a list of
  4408. file names already visited. It is used to avoid circular setup
  4409. files. ALIST, when non-nil, is the alist computed so far.
  4410. Return value contains the following keys: `archive', `category',
  4411. `columns', `constants', `filetags', `link', `priorities',
  4412. `property', `scripts', `startup', `tags' and `todo'."
  4413. (org-with-wide-buffer
  4414. (goto-char (point-min))
  4415. (let ((case-fold-search t))
  4416. (while (re-search-forward regexp nil t)
  4417. (let ((element (org-element-at-point)))
  4418. (when (eq (org-element-type element) 'keyword)
  4419. (let ((key (org-element-property :key element))
  4420. (value (org-element-property :value element)))
  4421. (cond
  4422. ((equal key "ARCHIVE")
  4423. (when (org-string-nw-p value)
  4424. (push (cons 'archive value) alist)))
  4425. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4426. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4427. ((equal key "CONSTANTS")
  4428. (let* ((constants (assq 'constants alist))
  4429. (store (cdr constants)))
  4430. (dolist (pair (split-string value))
  4431. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4432. pair)
  4433. (let* ((name (match-string 1 pair))
  4434. (value (match-string 2 pair))
  4435. (old (assoc name store)))
  4436. (if old (setcdr old value)
  4437. (push (cons name value) store)))))
  4438. (if constants (setcdr constants store)
  4439. (push (cons 'constants store) alist))))
  4440. ((equal key "FILETAGS")
  4441. (when (org-string-nw-p value)
  4442. (let ((old (assq 'filetags alist))
  4443. (new (apply #'nconc
  4444. (mapcar (lambda (x) (org-split-string x ":"))
  4445. (split-string value)))))
  4446. (if old (setcdr old (append new (cdr old)))
  4447. (push (cons 'filetags new) alist)))))
  4448. ((equal key "LINK")
  4449. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4450. (let ((links (assq 'link alist))
  4451. (pair (cons (match-string-no-properties 1 value)
  4452. (match-string-no-properties 2 value))))
  4453. (if links (push pair (cdr links))
  4454. (push (list 'link pair) alist)))))
  4455. ((equal key "OPTIONS")
  4456. (when (and (org-string-nw-p value)
  4457. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4458. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4459. ((equal key "PRIORITIES")
  4460. (push (cons 'priorities
  4461. (let ((prio (split-string value)))
  4462. (if (< (length prio) 3) '(?A ?C ?B)
  4463. (mapcar #'string-to-char prio))))
  4464. alist))
  4465. ((equal key "PROPERTY")
  4466. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4467. (let* ((property (assq 'property alist))
  4468. (value (org--update-property-plist
  4469. (match-string-no-properties 1 value)
  4470. (match-string-no-properties 2 value)
  4471. (cdr property))))
  4472. (if property (setcdr property value)
  4473. (push (cons 'property value) alist)))))
  4474. ((equal key "STARTUP")
  4475. (let ((startup (assq 'startup alist)))
  4476. (if startup
  4477. (setcdr startup
  4478. (append (cdr startup) (split-string value)))
  4479. (push (cons 'startup (split-string value)) alist))))
  4480. ((equal key "TAGS")
  4481. (let ((tag-cell (assq 'tags alist)))
  4482. (if tag-cell
  4483. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4484. (push (cons 'tags value) alist))))
  4485. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4486. (let ((todo (assq 'todo alist))
  4487. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4488. (split-string value))))
  4489. (if todo (push value (cdr todo))
  4490. (push (list 'todo value) alist))))
  4491. ((equal key "SETUPFILE")
  4492. (unless buffer-read-only ; Do not check in Gnus messages.
  4493. (let ((f (and (org-string-nw-p value)
  4494. (expand-file-name
  4495. (org-unbracket-string "\"" "\"" value)))))
  4496. (when (and f (file-readable-p f) (not (member f files)))
  4497. (with-temp-buffer
  4498. (setq default-directory (file-name-directory f))
  4499. (insert-file-contents f)
  4500. (setq alist
  4501. ;; Fake Org mode to benefit from cache
  4502. ;; without recurring needlessly.
  4503. (let ((major-mode 'org-mode))
  4504. (org--setup-collect-keywords
  4505. regexp (cons f files) alist)))))))))))))))
  4506. alist)
  4507. (defun org-tag-string-to-alist (s)
  4508. "Return tag alist associated to string S.
  4509. S is a value for TAGS keyword or produced with
  4510. `org-tag-alist-to-string'. Return value is an alist suitable for
  4511. `org-tag-alist' or `org-tag-persistent-alist'."
  4512. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4513. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4514. "\\(?:(\\(.\\))\\)?\\'"))
  4515. alist group-flag)
  4516. (dolist (tokens lines (cdr (nreverse alist)))
  4517. (push '(:newline) alist)
  4518. (while tokens
  4519. (let ((token (pop tokens)))
  4520. (pcase token
  4521. ("{"
  4522. (push '(:startgroup) alist)
  4523. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4524. ("}"
  4525. (push '(:endgroup) alist)
  4526. (setq group-flag nil))
  4527. ("["
  4528. (push '(:startgrouptag) alist)
  4529. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4530. ("]"
  4531. (push '(:endgrouptag) alist)
  4532. (setq group-flag nil))
  4533. (":"
  4534. (push '(:grouptags) alist))
  4535. ((guard (string-match tag-re token))
  4536. (let ((tag (match-string 1 token))
  4537. (key (and (match-beginning 2)
  4538. (string-to-char (match-string 2 token)))))
  4539. ;; Push all tags in groups, no matter if they already
  4540. ;; appear somewhere else in the list.
  4541. (when (or group-flag (not (assoc tag alist)))
  4542. (push (cons tag key) alist))))))))))
  4543. (defun org-tag-alist-to-string (alist &optional skip-key)
  4544. "Return tag string associated to ALIST.
  4545. ALIST is an alist, as defined in `org-tag-alist' or
  4546. `org-tag-persistent-alist', or produced with
  4547. `org-tag-string-to-alist'.
  4548. Return value is a string suitable as a value for \"TAGS\"
  4549. keyword.
  4550. When optional argument SKIP-KEY is non-nil, skip selection keys
  4551. next to tags."
  4552. (mapconcat (lambda (token)
  4553. (pcase token
  4554. (`(:startgroup) "{")
  4555. (`(:endgroup) "}")
  4556. (`(:startgrouptag) "[")
  4557. (`(:endgrouptag) "]")
  4558. (`(:grouptags) ":")
  4559. (`(:newline) "\\n")
  4560. ((and
  4561. (guard (not skip-key))
  4562. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4563. (format "%s(%c)" tag key))
  4564. (`(,(and tag (pred stringp)) . ,_) tag)
  4565. (_ (user-error "Invalid tag token: %S" token))))
  4566. alist
  4567. " "))
  4568. (defun org-tag-alist-to-groups (alist)
  4569. "Return group alist from tag ALIST.
  4570. ALIST is an alist, as defined in `org-tag-alist' or
  4571. `org-tag-persistent-alist', or produced with
  4572. `org-tag-string-to-alist'. Return value is an alist following
  4573. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4574. a string, summarizing TAGS, as a list of strings."
  4575. (let (groups group-status current-group)
  4576. (dolist (token alist (nreverse groups))
  4577. (pcase token
  4578. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4579. (`(,(or :endgroup :endgrouptag))
  4580. (when (eq group-status 'append)
  4581. (push (nreverse current-group) groups))
  4582. (setq group-status nil current-group nil))
  4583. (`(:grouptags) (setq group-status 'append))
  4584. ((and `(,tag . ,_) (guard group-status))
  4585. (if (eq group-status 'append) (push tag current-group)
  4586. (setq current-group (list tag))))
  4587. (_ nil)))))
  4588. (defvar org--file-cache (make-hash-table :test #'equal)
  4589. "Hash table to store contents of files referenced via a URL.
  4590. This is the cache of file URLs read using `org-file-contents'.")
  4591. (defun org-reset-file-cache ()
  4592. "Reset the cache of files downloaded by `org-file-contents'."
  4593. (clrhash org--file-cache))
  4594. (defun org-file-url-p (file)
  4595. "Non-nil if FILE is a URL."
  4596. (require 'ffap)
  4597. (string-match-p ffap-url-regexp file))
  4598. (defun org-file-contents (file &optional noerror nocache)
  4599. "Return the contents of FILE, as a string.
  4600. FILE can be a file name or URL.
  4601. If FILE is a URL, download the contents. If the URL contents are
  4602. already cached in the `org--file-cache' hash table, the download step
  4603. is skipped.
  4604. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4605. from file or URL.
  4606. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4607. is available. This option applies only if FILE is a URL."
  4608. (let* ((is-url (org-file-url-p file))
  4609. (cache (and is-url
  4610. (not nocache)
  4611. (gethash file org--file-cache))))
  4612. (cond
  4613. (cache)
  4614. (is-url
  4615. (with-current-buffer (url-retrieve-synchronously file)
  4616. (goto-char (point-min))
  4617. ;; Move point to after the url-retrieve header.
  4618. (search-forward "\n\n" nil :move)
  4619. ;; Search for the success code only in the url-retrieve header.
  4620. (if (save-excursion
  4621. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4622. ;; Update the cache `org--file-cache' and return contents.
  4623. (puthash file
  4624. (buffer-substring-no-properties (point) (point-max))
  4625. org--file-cache)
  4626. (funcall (if noerror #'message #'user-error)
  4627. "Unable to fetch file from %S"
  4628. file))))
  4629. (t
  4630. (with-temp-buffer
  4631. (condition-case nil
  4632. (progn
  4633. (insert-file-contents file)
  4634. (buffer-string))
  4635. (file-error
  4636. (funcall (if noerror #'message #'user-error)
  4637. "Unable to read file %S"
  4638. file))))))))
  4639. (defun org-extract-log-state-settings (x)
  4640. "Extract the log state setting from a TODO keyword string.
  4641. This will extract info from a string like \"WAIT(w@/!)\"."
  4642. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4643. (let ((kw (match-string 1 x))
  4644. (log1 (and (match-end 3) (match-string 3 x)))
  4645. (log2 (and (match-end 4) (match-string 4 x))))
  4646. (and (or log1 log2)
  4647. (list kw
  4648. (and log1 (if (equal log1 "!") 'time 'note))
  4649. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4650. (defun org-remove-keyword-keys (list)
  4651. "Remove a pair of parenthesis at the end of each string in LIST."
  4652. (mapcar (lambda (x)
  4653. (if (string-match "(.*)$" x)
  4654. (substring x 0 (match-beginning 0))
  4655. x))
  4656. list))
  4657. (defun org-assign-fast-keys (alist)
  4658. "Assign fast keys to a keyword-key alist.
  4659. Respect keys that are already there."
  4660. (let (new e (alt ?0))
  4661. (while (setq e (pop alist))
  4662. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4663. (cdr e)) ;; Key already assigned.
  4664. (push e new)
  4665. (let ((clist (string-to-list (downcase (car e))))
  4666. (used (append new alist)))
  4667. (when (= (car clist) ?@)
  4668. (pop clist))
  4669. (while (and clist (rassoc (car clist) used))
  4670. (pop clist))
  4671. (unless clist
  4672. (while (rassoc alt used)
  4673. (cl-incf alt)))
  4674. (push (cons (car e) (or (car clist) alt)) new))))
  4675. (nreverse new)))
  4676. ;;; Some variables used in various places
  4677. (defvar org-window-configuration nil
  4678. "Used in various places to store a window configuration.")
  4679. (defvar org-selected-window nil
  4680. "Used in various places to store a window configuration.")
  4681. (defvar org-finish-function nil
  4682. "Function to be called when `C-c C-c' is used.
  4683. This is for getting out of special buffers like capture.")
  4684. (defvar org-last-state)
  4685. ;; Defined somewhere in this file, but used before definition.
  4686. (defvar org-entities) ;; defined in org-entities.el
  4687. (defvar org-struct-menu)
  4688. (defvar org-org-menu)
  4689. (defvar org-tbl-menu)
  4690. ;;;; Define the Org mode
  4691. ;; We use a before-change function to check if a table might need
  4692. ;; an update.
  4693. (defvar org-table-may-need-update t
  4694. "Indicates that a table might need an update.
  4695. This variable is set by `org-before-change-function'.
  4696. `org-table-align' sets it back to nil.")
  4697. (defun org-before-change-function (_beg _end)
  4698. "Every change indicates that a table might need an update."
  4699. (setq org-table-may-need-update t))
  4700. (defvar org-mode-map)
  4701. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4702. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4703. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4704. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4705. (defvar org-table-buffer-is-an nil)
  4706. (defvar bidi-paragraph-direction)
  4707. (defvar buffer-face-mode-face)
  4708. (require 'outline)
  4709. ;; Other stuff we need.
  4710. (require 'time-date)
  4711. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4712. (require 'easymenu)
  4713. (autoload 'easy-menu-add "easymenu")
  4714. (require 'overlay)
  4715. ;; (require 'org-macs) moved higher up in the file before it is first used
  4716. (require 'org-entities)
  4717. ;; (require 'org-compat) moved higher up in the file before it is first used
  4718. (require 'org-faces)
  4719. (require 'org-list)
  4720. (require 'org-pcomplete)
  4721. (require 'org-src)
  4722. (require 'org-footnote)
  4723. (require 'org-macro)
  4724. ;; babel
  4725. (require 'ob)
  4726. ;;;###autoload
  4727. (define-derived-mode org-mode outline-mode "Org"
  4728. "Outline-based notes management and organizer, alias
  4729. \"Carsten's outline-mode for keeping track of everything.\"
  4730. Org mode develops organizational tasks around a NOTES file which
  4731. contains information about projects as plain text. Org mode is
  4732. implemented on top of Outline mode, which is ideal to keep the content
  4733. of large files well structured. It supports ToDo items, deadlines and
  4734. time stamps, which magically appear in the diary listing of the Emacs
  4735. calendar. Tables are easily created with a built-in table editor.
  4736. Plain text URL-like links connect to websites, emails (VM), Usenet
  4737. messages (Gnus), BBDB entries, and any files related to the project.
  4738. For printing and sharing of notes, an Org file (or a part of it)
  4739. can be exported as a structured ASCII or HTML file.
  4740. The following commands are available:
  4741. \\{org-mode-map}"
  4742. ;; Get rid of Outline menus, they are not needed
  4743. ;; Need to do this here because define-derived-mode sets up
  4744. ;; the keymap so late. Still, it is a waste to call this each time
  4745. ;; we switch another buffer into Org mode.
  4746. (define-key org-mode-map [menu-bar headings] 'undefined)
  4747. (define-key org-mode-map [menu-bar hide] 'undefined)
  4748. (define-key org-mode-map [menu-bar show] 'undefined)
  4749. (org-load-modules-maybe)
  4750. (org-install-agenda-files-menu)
  4751. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4752. (add-to-invisibility-spec '(org-hide-block . t))
  4753. (add-to-invisibility-spec '(org-hide-drawer . t))
  4754. (setq-local outline-regexp org-outline-regexp)
  4755. (setq-local outline-level 'org-outline-level)
  4756. (setq bidi-paragraph-direction 'left-to-right)
  4757. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4758. (unless org-display-table
  4759. (setq org-display-table (make-display-table)))
  4760. (set-display-table-slot
  4761. org-display-table 4
  4762. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4763. org-ellipsis)))
  4764. (setq buffer-display-table org-display-table))
  4765. (org-set-regexps-and-options)
  4766. (org-set-font-lock-defaults)
  4767. (when (and org-tag-faces (not org-tags-special-faces-re))
  4768. ;; tag faces set outside customize.... force initialization.
  4769. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4770. ;; Calc embedded
  4771. (setq-local calc-embedded-open-mode "# ")
  4772. ;; Modify a few syntax entries
  4773. (modify-syntax-entry ?\" "\"")
  4774. (modify-syntax-entry ?\\ "_")
  4775. (modify-syntax-entry ?~ "_")
  4776. (modify-syntax-entry ?< "(>")
  4777. (modify-syntax-entry ?> ")<")
  4778. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4779. ;; Activate before-change-function
  4780. (setq-local org-table-may-need-update t)
  4781. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4782. ;; Check for running clock before killing a buffer
  4783. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4784. ;; Initialize macros templates.
  4785. (org-macro-initialize-templates)
  4786. ;; Initialize radio targets.
  4787. (org-update-radio-target-regexp)
  4788. ;; Indentation.
  4789. (setq-local indent-line-function 'org-indent-line)
  4790. (setq-local indent-region-function 'org-indent-region)
  4791. ;; Filling and auto-filling.
  4792. (org-setup-filling)
  4793. ;; Comments.
  4794. (org-setup-comments-handling)
  4795. ;; Initialize cache.
  4796. (org-element-cache-reset)
  4797. ;; Beginning/end of defun
  4798. (setq-local beginning-of-defun-function 'org-backward-element)
  4799. (setq-local end-of-defun-function
  4800. (lambda ()
  4801. (if (not (org-at-heading-p))
  4802. (org-forward-element)
  4803. (org-forward-element)
  4804. (forward-char -1))))
  4805. ;; Next error for sparse trees
  4806. (setq-local next-error-function 'org-occur-next-match)
  4807. ;; Make commit log messages from Org documents easier.
  4808. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4809. ;; Make sure dependence stuff works reliably, even for users who set it
  4810. ;; too late :-(
  4811. (if org-enforce-todo-dependencies
  4812. (add-hook 'org-blocker-hook
  4813. 'org-block-todo-from-children-or-siblings-or-parent)
  4814. (remove-hook 'org-blocker-hook
  4815. 'org-block-todo-from-children-or-siblings-or-parent))
  4816. (if org-enforce-todo-checkbox-dependencies
  4817. (add-hook 'org-blocker-hook
  4818. 'org-block-todo-from-checkboxes)
  4819. (remove-hook 'org-blocker-hook
  4820. 'org-block-todo-from-checkboxes))
  4821. ;; Align options lines
  4822. (setq-local
  4823. align-mode-rules-list
  4824. '((org-in-buffer-settings
  4825. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4826. (modes . '(org-mode)))))
  4827. ;; Make isearch reveal context
  4828. (setq-local outline-isearch-open-invisible-function
  4829. (lambda (&rest _) (org-show-context 'isearch)))
  4830. ;; Setup the pcomplete hooks
  4831. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4832. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4833. (setq-local pcomplete-default-completion-function 'ignore)
  4834. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4835. (setq-local pcomplete-termination-string "")
  4836. (setq-local buffer-face-mode-face 'org-default)
  4837. ;; If empty file that did not turn on Org mode automatically, make
  4838. ;; it to.
  4839. (when (and org-insert-mode-line-in-empty-file
  4840. (called-interactively-p 'any)
  4841. (= (point-min) (point-max)))
  4842. (insert "# -*- mode: org -*-\n\n"))
  4843. (unless org-inhibit-startup
  4844. (org-unmodified
  4845. (when org-startup-with-beamer-mode (org-beamer-mode))
  4846. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4847. (org-table-map-tables
  4848. (cond ((and org-startup-align-all-tables
  4849. org-startup-shrink-all-tables)
  4850. (lambda () (org-table-align) (org-table-shrink)))
  4851. (org-startup-align-all-tables #'org-table-align)
  4852. (t #'org-table-shrink))
  4853. t))
  4854. (when org-startup-with-inline-images (org-display-inline-images))
  4855. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4856. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4857. (when org-startup-truncated (setq truncate-lines t))
  4858. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4859. (org-refresh-effort-properties)))
  4860. ;; Try to set `org-hide' face correctly.
  4861. (let ((foreground (org-find-invisible-foreground)))
  4862. (when foreground
  4863. (set-face-foreground 'org-hide foreground))))
  4864. ;; Update `customize-package-emacs-version-alist'
  4865. (add-to-list 'customize-package-emacs-version-alist
  4866. '(Org ("8.0" . "24.4")
  4867. ("8.1" . "24.4")
  4868. ("8.2" . "24.4")
  4869. ("8.2.7" . "24.4")
  4870. ("8.3" . "26.1")
  4871. ("9.0" . "26.1")
  4872. ("9.1" . "26.1")
  4873. ("9.2" . "27.1")))
  4874. (defvar org-mode-transpose-word-syntax-table
  4875. (let ((st (make-syntax-table text-mode-syntax-table)))
  4876. (dolist (c org-emphasis-alist st)
  4877. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4878. (when (fboundp 'abbrev-table-put)
  4879. (abbrev-table-put org-mode-abbrev-table
  4880. :parents (list text-mode-abbrev-table)))
  4881. (defun org-find-invisible-foreground ()
  4882. (let ((candidates (remove
  4883. "unspecified-bg"
  4884. (nconc
  4885. (list (face-background 'default)
  4886. (face-background 'org-default))
  4887. (mapcar
  4888. (lambda (alist)
  4889. (when (boundp alist)
  4890. (cdr (assq 'background-color (symbol-value alist)))))
  4891. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4892. (list (face-foreground 'org-hide))))))
  4893. (car (remove nil candidates))))
  4894. (defun org-current-time (&optional rounding-minutes past)
  4895. "Current time, possibly rounded to ROUNDING-MINUTES.
  4896. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4897. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4898. the rounding returns a past time."
  4899. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4900. (car org-time-stamp-rounding-minutes)))
  4901. (time (decode-time)) res)
  4902. (if (< r 1)
  4903. (current-time)
  4904. (setq res
  4905. (apply 'encode-time
  4906. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4907. (nthcdr 2 time))))
  4908. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4909. (seconds-to-time (- (float-time res) (* r 60)))
  4910. res))))
  4911. (defun org-today ()
  4912. "Return today date, considering `org-extend-today-until'."
  4913. (time-to-days
  4914. (time-subtract (current-time)
  4915. (list 0 (* 3600 org-extend-today-until) 0))))
  4916. ;;;; Font-Lock stuff, including the activators
  4917. (defvar org-mouse-map (make-sparse-keymap))
  4918. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4919. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4920. (when org-mouse-1-follows-link
  4921. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4922. (when org-tab-follows-link
  4923. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4924. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4925. (require 'font-lock)
  4926. (defconst org-non-link-chars "]\t\n\r<>")
  4927. (defvar org-link-types-re nil
  4928. "Matches a link that has a url-like prefix like \"http:\"")
  4929. (defvar org-link-re-with-space nil
  4930. "Matches a link with spaces, optional angular brackets around it.")
  4931. (defvar org-link-re-with-space2 nil
  4932. "Matches a link with spaces, optional angular brackets around it.")
  4933. (defvar org-link-re-with-space3 nil
  4934. "Matches a link with spaces, only for internal part in bracket links.")
  4935. (defvar org-angle-link-re nil
  4936. "Matches link with angular brackets, spaces are allowed.")
  4937. (defvar org-plain-link-re nil
  4938. "Matches plain link, without spaces.")
  4939. (defvar org-bracket-link-regexp nil
  4940. "Matches a link in double brackets.")
  4941. (defvar org-bracket-link-analytic-regexp nil
  4942. "Regular expression used to analyze links.
  4943. Here is what the match groups contain after a match:
  4944. 1: http:
  4945. 2: http
  4946. 3: path
  4947. 4: [desc]
  4948. 5: desc")
  4949. (defvar org-bracket-link-analytic-regexp++ nil
  4950. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4951. (defvar org-any-link-re nil
  4952. "Regular expression matching any link.")
  4953. (defconst org-match-sexp-depth 3
  4954. "Number of stacked braces for sub/superscript matching.")
  4955. (defun org-create-multibrace-regexp (left right n)
  4956. "Create a regular expression which will match a balanced sexp.
  4957. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4958. as single character strings.
  4959. The regexp returned will match the entire expression including the
  4960. delimiters. It will also define a single group which contains the
  4961. match except for the outermost delimiters. The maximum depth of
  4962. stacked delimiters is N. Escaping delimiters is not possible."
  4963. (let* ((nothing (concat "[^" left right "]*?"))
  4964. (or "\\|")
  4965. (re nothing)
  4966. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4967. (while (> n 1)
  4968. (setq n (1- n)
  4969. re (concat re or next)
  4970. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4971. (concat left "\\(" re "\\)" right)))
  4972. (defconst org-match-substring-regexp
  4973. (concat
  4974. "\\(\\S-\\)\\([_^]\\)\\("
  4975. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4976. "\\|"
  4977. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4978. "\\|"
  4979. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4980. "The regular expression matching a sub- or superscript.")
  4981. (defconst org-match-substring-with-braces-regexp
  4982. (concat
  4983. "\\(\\S-\\)\\([_^]\\)"
  4984. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4985. "The regular expression matching a sub- or superscript, forcing braces.")
  4986. (defun org-make-link-regexps ()
  4987. "Update the link regular expressions.
  4988. This should be called after the variable `org-link-parameters' has changed."
  4989. (let ((types-re (regexp-opt (org-link-types) t)))
  4990. (setq org-link-types-re
  4991. (concat "\\`" types-re ":")
  4992. org-link-re-with-space
  4993. (concat "<?" types-re ":"
  4994. "\\([^" org-non-link-chars " ]"
  4995. "[^" org-non-link-chars "]*"
  4996. "[^" org-non-link-chars " ]\\)>?")
  4997. org-link-re-with-space2
  4998. (concat "<?" types-re ":"
  4999. "\\([^" org-non-link-chars " ]"
  5000. "[^\t\n\r]*"
  5001. "[^" org-non-link-chars " ]\\)>?")
  5002. org-link-re-with-space3
  5003. (concat "<?" types-re ":"
  5004. "\\([^" org-non-link-chars " ]"
  5005. "[^\t\n\r]*\\)")
  5006. org-angle-link-re
  5007. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5008. types-re)
  5009. org-plain-link-re
  5010. (concat
  5011. "\\<" types-re ":"
  5012. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5013. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5014. org-bracket-link-regexp
  5015. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5016. org-bracket-link-analytic-regexp
  5017. (concat
  5018. "\\[\\["
  5019. "\\(" types-re ":\\)?"
  5020. "\\([^]]+\\)"
  5021. "\\]"
  5022. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5023. "\\]")
  5024. org-bracket-link-analytic-regexp++
  5025. (concat
  5026. "\\[\\["
  5027. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5028. "\\([^]]+\\)"
  5029. "\\]"
  5030. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5031. "\\]")
  5032. org-any-link-re
  5033. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5034. org-angle-link-re "\\)\\|\\("
  5035. org-plain-link-re "\\)"))))
  5036. (org-make-link-regexps)
  5037. (defvar org-emph-face nil)
  5038. (defun org-do-emphasis-faces (limit)
  5039. "Run through the buffer and emphasize strings."
  5040. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5041. (car org-emphasis-regexp-components))))
  5042. (catch :exit
  5043. (while (re-search-forward quick-re limit t)
  5044. (let* ((marker (match-string 2))
  5045. (verbatim? (member marker '("~" "="))))
  5046. (when (save-excursion
  5047. (goto-char (match-beginning 0))
  5048. (and
  5049. ;; Do not match table hlines.
  5050. (not (and (equal marker "+")
  5051. (org-match-line
  5052. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5053. ;; Do not match headline stars. Do not consider
  5054. ;; stars of a headline as closing marker for bold
  5055. ;; markup either.
  5056. (not (and (equal marker "*")
  5057. (save-excursion
  5058. (forward-char)
  5059. (skip-chars-backward "*")
  5060. (looking-at-p org-outline-regexp-bol))))
  5061. ;; Match full emphasis markup regexp.
  5062. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5063. ;; Do not span over paragraph boundaries.
  5064. (not (string-match-p org-element-paragraph-separate
  5065. (match-string 2)))
  5066. ;; Do not span over cells in table rows.
  5067. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5068. (string-match-p "|" (match-string 4))))))
  5069. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5070. (font-lock-prepend-text-property
  5071. (match-beginning 2) (match-end 2) 'face face)
  5072. (when verbatim?
  5073. (org-remove-flyspell-overlays-in
  5074. (match-beginning 0) (match-end 0)))
  5075. (add-text-properties (match-beginning 2) (match-end 2)
  5076. '(font-lock-multiline t org-emphasis t))
  5077. (when org-hide-emphasis-markers
  5078. (add-text-properties (match-end 4) (match-beginning 5)
  5079. '(invisible org-link))
  5080. (add-text-properties (match-beginning 3) (match-end 3)
  5081. '(invisible org-link)))
  5082. (throw :exit t))))))))
  5083. (defun org-emphasize (&optional char)
  5084. "Insert or change an emphasis, i.e. a font like bold or italic.
  5085. If there is an active region, change that region to a new emphasis.
  5086. If there is no region, just insert the marker characters and position
  5087. the cursor between them.
  5088. CHAR should be the marker character. If it is a space, it means to
  5089. remove the emphasis of the selected region.
  5090. If CHAR is not given (for example in an interactive call) it will be
  5091. prompted for."
  5092. (interactive)
  5093. (let ((erc org-emphasis-regexp-components)
  5094. (string "") beg end move s)
  5095. (if (org-region-active-p)
  5096. (setq beg (region-beginning)
  5097. end (region-end)
  5098. string (buffer-substring beg end))
  5099. (setq move t))
  5100. (unless char
  5101. (message "Emphasis marker or tag: [%s]"
  5102. (mapconcat #'car org-emphasis-alist ""))
  5103. (setq char (read-char-exclusive)))
  5104. (if (equal char ?\s)
  5105. (setq s ""
  5106. move nil)
  5107. (unless (assoc (char-to-string char) org-emphasis-alist)
  5108. (user-error "No such emphasis marker: \"%c\"" char))
  5109. (setq s (char-to-string char)))
  5110. (while (and (> (length string) 1)
  5111. (equal (substring string 0 1) (substring string -1))
  5112. (assoc (substring string 0 1) org-emphasis-alist))
  5113. (setq string (substring string 1 -1)))
  5114. (setq string (concat s string s))
  5115. (when beg (delete-region beg end))
  5116. (unless (or (bolp)
  5117. (string-match (concat "[" (nth 0 erc) "\n]")
  5118. (char-to-string (char-before (point)))))
  5119. (insert " "))
  5120. (unless (or (eobp)
  5121. (string-match (concat "[" (nth 1 erc) "\n]")
  5122. (char-to-string (char-after (point)))))
  5123. (insert " ") (backward-char 1))
  5124. (insert string)
  5125. (and move (backward-char 1))))
  5126. (defconst org-nonsticky-props
  5127. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5128. (defsubst org-rear-nonsticky-at (pos)
  5129. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5130. (defun org-activate-links (limit)
  5131. "Add link properties to links.
  5132. This includes angle, plain, and bracket links."
  5133. (catch :exit
  5134. (while (re-search-forward org-any-link-re limit t)
  5135. (let* ((start (match-beginning 0))
  5136. (end (match-end 0))
  5137. (style (cond ((eq ?< (char-after start)) 'angle)
  5138. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5139. (t 'plain))))
  5140. (when (and (memq style org-highlight-links)
  5141. ;; Do not confuse plain links with tags.
  5142. (not (and (eq style 'plain)
  5143. (let ((face (get-text-property
  5144. (max (1- start) (point-min)) 'face)))
  5145. (if (consp face) (memq 'org-tag face)
  5146. (eq 'org-tag face))))))
  5147. (let* ((link-object (save-excursion
  5148. (goto-char start)
  5149. (save-match-data (org-element-link-parser))))
  5150. (link (org-element-property :raw-link link-object))
  5151. (type (org-element-property :type link-object))
  5152. (path (org-element-property :path link-object))
  5153. (properties ;for link's visible part
  5154. (list
  5155. 'face (pcase (org-link-get-parameter type :face)
  5156. ((and (pred functionp) face) (funcall face path))
  5157. ((and (pred facep) face) face)
  5158. ((and (pred consp) face) face) ;anonymous
  5159. (_ 'org-link))
  5160. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5161. 'highlight)
  5162. 'keymap (or (org-link-get-parameter type :keymap)
  5163. org-mouse-map)
  5164. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5165. ((and (pred stringp) echo) echo)
  5166. ((and (pred functionp) echo) echo)
  5167. (_ (concat "LINK: " link)))
  5168. 'htmlize-link (pcase (org-link-get-parameter type
  5169. :htmlize-link)
  5170. ((and (pred functionp) f) (funcall f))
  5171. (_ `(:uri ,link)))
  5172. 'font-lock-multiline t)))
  5173. (org-remove-flyspell-overlays-in start end)
  5174. (org-rear-nonsticky-at end)
  5175. (if (not (eq 'bracket style))
  5176. (add-text-properties start end properties)
  5177. ;; Handle invisible parts in bracket links.
  5178. (remove-text-properties start end '(invisible nil))
  5179. (let ((hidden
  5180. (append `(invisible
  5181. ,(or (org-link-get-parameter type :display)
  5182. 'org-link))
  5183. properties))
  5184. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5185. (visible-end (or (match-end 4) (match-end 2))))
  5186. (add-text-properties start visible-start hidden)
  5187. (add-text-properties visible-start visible-end properties)
  5188. (add-text-properties visible-end end hidden)
  5189. (org-rear-nonsticky-at visible-start)
  5190. (org-rear-nonsticky-at visible-end)))
  5191. (let ((f (org-link-get-parameter type :activate-func)))
  5192. (when (functionp f)
  5193. (funcall f start end path (eq style 'bracket))))
  5194. (throw :exit t))))) ;signal success
  5195. nil))
  5196. (defun org-activate-code (limit)
  5197. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5198. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5199. (remove-text-properties (match-beginning 0) (match-end 0)
  5200. '(display t invisible t intangible t))
  5201. t))
  5202. (defcustom org-src-fontify-natively t
  5203. "When non-nil, fontify code in code blocks.
  5204. See also the `org-block' face."
  5205. :type 'boolean
  5206. :version "26.1"
  5207. :package-version '(Org . "8.3")
  5208. :group 'org-appearance
  5209. :group 'org-babel)
  5210. (defcustom org-allow-promoting-top-level-subtree nil
  5211. "When non-nil, allow promoting a top level subtree.
  5212. The leading star of the top level headline will be replaced
  5213. by a #."
  5214. :type 'boolean
  5215. :version "24.1"
  5216. :group 'org-appearance)
  5217. (defun org-fontify-meta-lines-and-blocks (limit)
  5218. (condition-case nil
  5219. (org-fontify-meta-lines-and-blocks-1 limit)
  5220. (error (message "Org mode fontification error in %S at %d"
  5221. (current-buffer)
  5222. (line-number-at-pos)))))
  5223. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5224. "Fontify #+ lines and blocks."
  5225. (let ((case-fold-search t))
  5226. (when (re-search-forward
  5227. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5228. limit t)
  5229. (let ((beg (match-beginning 0))
  5230. (block-start (match-end 0))
  5231. (block-end nil)
  5232. (lang (match-string 7))
  5233. (beg1 (line-beginning-position 2))
  5234. (dc1 (downcase (match-string 2)))
  5235. (dc3 (downcase (match-string 3)))
  5236. end end1 quoting block-type)
  5237. (cond
  5238. ((and (match-end 4) (equal dc3 "+begin"))
  5239. ;; Truly a block
  5240. (setq block-type (downcase (match-string 5))
  5241. quoting (member block-type org-protecting-blocks))
  5242. (when (re-search-forward
  5243. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5244. nil t) ;; on purpose, we look further than LIMIT
  5245. (setq end (min (point-max) (match-end 0))
  5246. end1 (min (point-max) (1- (match-beginning 0))))
  5247. (setq block-end (match-beginning 0))
  5248. (when quoting
  5249. (org-remove-flyspell-overlays-in beg1 end1)
  5250. (remove-text-properties beg end
  5251. '(display t invisible t intangible t)))
  5252. (add-text-properties
  5253. beg end '(font-lock-fontified t font-lock-multiline t))
  5254. (add-text-properties beg beg1 '(face org-meta-line))
  5255. (org-remove-flyspell-overlays-in beg beg1)
  5256. (add-text-properties ; For end_src
  5257. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5258. (org-remove-flyspell-overlays-in end1 end)
  5259. (cond
  5260. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5261. (org-src-font-lock-fontify-block lang block-start block-end)
  5262. (add-text-properties beg1 block-end '(src-block t)))
  5263. (quoting
  5264. (add-text-properties beg1 (min (point-max) (1+ end1))
  5265. (list 'face
  5266. (list :inherit
  5267. (let ((face-name
  5268. (intern (format "org-block-%s" lang))))
  5269. (append (and (facep face-name) (list face-name))
  5270. '(org-block))))))) ; end of source block
  5271. ((not org-fontify-quote-and-verse-blocks))
  5272. ((string= block-type "quote")
  5273. (add-face-text-property
  5274. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5275. ((string= block-type "verse")
  5276. (add-face-text-property
  5277. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5278. (add-text-properties beg beg1 '(face org-block-begin-line))
  5279. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5280. '(face org-block-end-line))
  5281. t))
  5282. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5283. (org-remove-flyspell-overlays-in
  5284. (match-beginning 0)
  5285. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5286. (add-text-properties
  5287. beg (match-end 3)
  5288. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5289. '(font-lock-fontified t invisible t)
  5290. '(font-lock-fontified t face org-document-info-keyword)))
  5291. (add-text-properties
  5292. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5293. (if (string-equal dc1 "+title:")
  5294. '(font-lock-fontified t face org-document-title)
  5295. '(font-lock-fontified t face org-document-info))))
  5296. ((string-prefix-p "+caption" dc1)
  5297. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5298. (remove-text-properties (match-beginning 0) (match-end 0)
  5299. '(display t invisible t intangible t))
  5300. ;; Handle short captions.
  5301. (save-excursion
  5302. (beginning-of-line)
  5303. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5304. (add-text-properties (line-beginning-position) (match-end 1)
  5305. '(font-lock-fontified t face org-meta-line))
  5306. (add-text-properties (match-end 0) (line-end-position)
  5307. '(font-lock-fontified t face org-block))
  5308. t)
  5309. ((member dc3 '(" " ""))
  5310. (org-remove-flyspell-overlays-in beg (match-end 0))
  5311. (add-text-properties
  5312. beg (match-end 0)
  5313. '(font-lock-fontified t face font-lock-comment-face)))
  5314. (t ;; just any other in-buffer setting, but not indented
  5315. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5316. (remove-text-properties (match-beginning 0) (match-end 0)
  5317. '(display t invisible t intangible t))
  5318. (add-text-properties beg (match-end 0)
  5319. '(font-lock-fontified t face org-meta-line))
  5320. t))))))
  5321. (defun org-fontify-drawers (limit)
  5322. "Fontify drawers."
  5323. (when (re-search-forward org-drawer-regexp limit t)
  5324. (add-text-properties
  5325. (match-beginning 0) (match-end 0)
  5326. '(font-lock-fontified t face org-special-keyword))
  5327. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5328. t))
  5329. (defun org-fontify-macros (limit)
  5330. "Fontify macros."
  5331. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5332. (let ((begin (match-beginning 0))
  5333. (opening-end (match-beginning 1)))
  5334. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5335. (match-string 1))
  5336. (let ((end (match-end 1))
  5337. (closing-start (match-beginning 1)))
  5338. (add-text-properties
  5339. begin end
  5340. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5341. (org-remove-flyspell-overlays-in begin end)
  5342. (when org-hide-macro-markers
  5343. (add-text-properties begin opening-end '(invisible t))
  5344. (add-text-properties closing-start end '(invisible t)))
  5345. t)))))
  5346. (defun org-activate-footnote-links (limit)
  5347. "Add text properties for footnotes."
  5348. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5349. (when fn
  5350. (let* ((beg (nth 1 fn))
  5351. (end (nth 2 fn))
  5352. (label (car fn))
  5353. (referencep (/= (line-beginning-position) beg)))
  5354. (when (and referencep (nth 3 fn))
  5355. (save-excursion
  5356. (goto-char beg)
  5357. (search-forward (or label "fn:"))
  5358. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5359. (add-text-properties beg end
  5360. (list 'mouse-face 'highlight
  5361. 'keymap org-mouse-map
  5362. 'help-echo
  5363. (if referencep "Footnote reference"
  5364. "Footnote definition")
  5365. 'font-lock-fontified t
  5366. 'font-lock-multiline t
  5367. 'face 'org-footnote))))))
  5368. (defun org-activate-dates (limit)
  5369. "Add text properties for dates."
  5370. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5371. (not (equal (char-before (match-beginning 0)) 91)))
  5372. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5373. (add-text-properties (match-beginning 0) (match-end 0)
  5374. (list 'mouse-face 'highlight
  5375. 'keymap org-mouse-map))
  5376. (org-rear-nonsticky-at (match-end 0))
  5377. (when org-display-custom-times
  5378. ;; If it's a date range, activate custom time for second date.
  5379. (when (match-end 3)
  5380. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5381. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5382. t))
  5383. (defvar-local org-target-link-regexp nil
  5384. "Regular expression matching radio targets in plain text.")
  5385. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5386. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5387. border border border))
  5388. "Regular expression matching a link target.")
  5389. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5390. "Regular expression matching a radio target.")
  5391. (defconst org-any-target-regexp
  5392. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5393. "Regular expression matching any target.")
  5394. (defun org-activate-target-links (limit)
  5395. "Add text properties for target matches."
  5396. (when org-target-link-regexp
  5397. (let ((case-fold-search t))
  5398. (when (re-search-forward org-target-link-regexp limit t)
  5399. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5400. (add-text-properties (match-beginning 1) (match-end 1)
  5401. (list 'mouse-face 'highlight
  5402. 'keymap org-mouse-map
  5403. 'help-echo "Radio target link"
  5404. 'org-linked-text t))
  5405. (org-rear-nonsticky-at (match-end 1))
  5406. t))))
  5407. (defun org-update-radio-target-regexp ()
  5408. "Find all radio targets in this file and update the regular expression.
  5409. Also refresh fontification if needed."
  5410. (interactive)
  5411. (let ((old-regexp org-target-link-regexp)
  5412. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5413. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5414. (targets
  5415. (org-with-wide-buffer
  5416. (goto-char (point-min))
  5417. (let (rtn)
  5418. (while (re-search-forward org-radio-target-regexp nil t)
  5419. ;; Make sure point is really within the object.
  5420. (backward-char)
  5421. (let ((obj (org-element-context)))
  5422. (when (eq (org-element-type obj) 'radio-target)
  5423. (cl-pushnew (org-element-property :value obj) rtn
  5424. :test #'equal))))
  5425. rtn))))
  5426. (setq org-target-link-regexp
  5427. (and targets
  5428. (concat before-re
  5429. (mapconcat
  5430. (lambda (x)
  5431. (replace-regexp-in-string
  5432. " +" "\\s-+" (regexp-quote x) t t))
  5433. targets
  5434. "\\|")
  5435. after-re)))
  5436. (unless (equal old-regexp org-target-link-regexp)
  5437. ;; Clean-up cache.
  5438. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5439. ((not org-target-link-regexp) old-regexp)
  5440. (t
  5441. (concat before-re
  5442. (mapconcat
  5443. (lambda (re)
  5444. (substring re (length before-re)
  5445. (- (length after-re))))
  5446. (list old-regexp org-target-link-regexp)
  5447. "\\|")
  5448. after-re)))))
  5449. (org-with-wide-buffer
  5450. (goto-char (point-min))
  5451. (while (re-search-forward regexp nil t)
  5452. (org-element-cache-refresh (match-beginning 1)))))
  5453. ;; Re fontify buffer.
  5454. (when (memq 'radio org-highlight-links)
  5455. (org-restart-font-lock)))))
  5456. (defvar org-latex-and-related-regexp nil
  5457. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5458. (defun org-compute-latex-and-related-regexp ()
  5459. "Compute regular expression for LaTeX, entities and sub/superscript.
  5460. Result depends on variable `org-highlight-latex-and-related'."
  5461. (setq-local
  5462. org-latex-and-related-regexp
  5463. (let* ((re-sub
  5464. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5465. ((eq org-use-sub-superscripts '{})
  5466. (list org-match-substring-with-braces-regexp))
  5467. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5468. (re-latex
  5469. (when (memq 'latex org-highlight-latex-and-related)
  5470. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5471. (delq nil
  5472. (mapcar (lambda (x)
  5473. (and (member (car x) matchers) (nth 1 x)))
  5474. org-latex-regexps)))))
  5475. (re-entities
  5476. (when (memq 'entities org-highlight-latex-and-related)
  5477. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5478. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5479. (defun org-do-latex-and-related (limit)
  5480. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5481. LIMIT bounds the search for syntax to highlight. Stop at first
  5482. highlighted object, if any. Return t if some highlighting was
  5483. done, nil otherwise."
  5484. (when (org-string-nw-p org-latex-and-related-regexp)
  5485. (catch 'found
  5486. (while (re-search-forward org-latex-and-related-regexp limit t)
  5487. (unless
  5488. (cl-some
  5489. (lambda (f)
  5490. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5491. (save-excursion
  5492. (goto-char (1+ (match-beginning 0)))
  5493. (face-at-point nil t)))
  5494. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5495. '(?_ ?^))
  5496. 1
  5497. 0)))
  5498. (font-lock-prepend-text-property
  5499. (+ offset (match-beginning 0)) (match-end 0)
  5500. 'face 'org-latex-and-related)
  5501. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5502. '(font-lock-multiline t)))
  5503. (throw 'found t)))
  5504. nil)))
  5505. (defun org-restart-font-lock ()
  5506. "Restart `font-lock-mode', to force refontification."
  5507. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5508. (font-lock-mode -1)
  5509. (font-lock-mode 1)))
  5510. (defun org-activate-tags (limit)
  5511. (when (re-search-forward org-tag-line-re limit t)
  5512. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5513. (add-text-properties (match-beginning 1) (match-end 1)
  5514. (list 'mouse-face 'highlight
  5515. 'keymap org-mouse-map))
  5516. (org-rear-nonsticky-at (match-end 1))
  5517. t))
  5518. (defun org-outline-level ()
  5519. "Compute the outline level of the heading at point.
  5520. If this is called at a normal headline, the level is the number
  5521. of stars. Use `org-reduced-level' to remove the effect of
  5522. `org-odd-levels'. Unlike to `org-current-level', this function
  5523. takes into consideration inlinetasks."
  5524. (org-with-wide-buffer
  5525. (end-of-line)
  5526. (if (re-search-backward org-outline-regexp-bol nil t)
  5527. (1- (- (match-end 0) (match-beginning 0)))
  5528. 0)))
  5529. (defvar org-font-lock-keywords nil)
  5530. (defsubst org-re-property (property &optional literal allow-null value)
  5531. "Return a regexp matching a PROPERTY line.
  5532. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5533. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5534. non-nil, match properties even without a value.
  5535. Match group 3 is set to the value when it exists. If there is no
  5536. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5537. With optional argument VALUE, match only property lines with
  5538. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5539. unless LITERAL is non-nil."
  5540. (concat
  5541. "^\\(?4:[ \t]*\\)"
  5542. (format "\\(?1::\\(?2:%s\\):\\)"
  5543. (if literal property (regexp-quote property)))
  5544. (cond (value
  5545. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5546. (if literal value (regexp-quote value))))
  5547. (allow-null
  5548. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5549. (t
  5550. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5551. (defconst org-property-re
  5552. (org-re-property "\\S-+" 'literal t)
  5553. "Regular expression matching a property line.
  5554. There are four matching groups:
  5555. 1: :PROPKEY: including the leading and trailing colon,
  5556. 2: PROPKEY without the leading and trailing colon,
  5557. 3: PROPVAL without leading or trailing spaces,
  5558. 4: the indentation of the current line,
  5559. 5: trailing whitespace.")
  5560. (defvar org-font-lock-hook nil
  5561. "Functions to be called for special font lock stuff.")
  5562. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5563. (defvar org-font-lock-set-keywords-hook nil
  5564. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5565. This is called after `org-font-lock-extra-keywords' is defined, but before
  5566. it is installed to be used by font lock. This can be useful if something
  5567. needs to be inserted at a specific position in the font-lock sequence.")
  5568. (defun org-font-lock-hook (limit)
  5569. "Run `org-font-lock-hook' within LIMIT."
  5570. (run-hook-with-args 'org-font-lock-hook limit))
  5571. (defun org-set-font-lock-defaults ()
  5572. "Set font lock defaults for the current buffer."
  5573. (let* ((em org-fontify-emphasized-text)
  5574. (lk org-highlight-links)
  5575. (org-font-lock-extra-keywords
  5576. (list
  5577. ;; Call the hook
  5578. '(org-font-lock-hook)
  5579. ;; Headlines
  5580. `(,(if org-fontify-whole-heading-line
  5581. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5582. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5583. (1 (org-get-level-face 1))
  5584. (2 (org-get-level-face 2))
  5585. (3 (org-get-level-face 3)))
  5586. ;; Table lines
  5587. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5588. (1 'org-table t))
  5589. ;; Table internals
  5590. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5591. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5592. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5593. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5594. ;; Drawers
  5595. '(org-fontify-drawers)
  5596. ;; Properties
  5597. (list org-property-re
  5598. '(1 'org-special-keyword t)
  5599. '(3 'org-property-value t))
  5600. ;; Link related fontification.
  5601. '(org-activate-links)
  5602. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5603. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5604. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5605. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5606. ;; Targets.
  5607. (list org-any-target-regexp '(0 'org-target t))
  5608. ;; Diary sexps.
  5609. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5610. ;; Macro
  5611. '(org-fontify-macros)
  5612. ;; TODO keyword
  5613. (list (format org-heading-keyword-regexp-format
  5614. org-todo-regexp)
  5615. '(2 (org-get-todo-face 2) t))
  5616. ;; DONE
  5617. (if org-fontify-done-headline
  5618. (list (format org-heading-keyword-regexp-format
  5619. (concat
  5620. "\\(?:"
  5621. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5622. "\\)"))
  5623. '(2 'org-headline-done t))
  5624. nil)
  5625. ;; Priorities
  5626. '(org-font-lock-add-priority-faces)
  5627. ;; Tags
  5628. '(org-font-lock-add-tag-faces)
  5629. ;; Tags groups
  5630. (when (and org-group-tags org-tag-groups-alist)
  5631. (list (concat org-outline-regexp-bol ".+\\(:"
  5632. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5633. ":\\).*$")
  5634. '(1 'org-tag-group prepend)))
  5635. ;; Special keywords
  5636. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5637. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5638. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5639. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5640. ;; Emphasis
  5641. (when em '(org-do-emphasis-faces))
  5642. ;; Checkboxes
  5643. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5644. 1 'org-checkbox prepend)
  5645. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5646. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5647. (0 (org-get-checkbox-statistics-face) t)))
  5648. ;; Description list items
  5649. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5650. 1 'org-list-dt prepend)
  5651. ;; ARCHIVEd headings
  5652. (list (concat
  5653. org-outline-regexp-bol
  5654. "\\(.*:" org-archive-tag ":.*\\)")
  5655. '(1 'org-archived prepend))
  5656. ;; Specials
  5657. '(org-do-latex-and-related)
  5658. '(org-fontify-entities)
  5659. '(org-raise-scripts)
  5660. ;; Code
  5661. '(org-activate-code (1 'org-code t))
  5662. ;; COMMENT
  5663. (list (format
  5664. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5665. org-todo-regexp
  5666. org-comment-string)
  5667. '(9 'org-special-keyword t))
  5668. ;; Blocks and meta lines
  5669. '(org-fontify-meta-lines-and-blocks))))
  5670. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5671. (run-hooks 'org-font-lock-set-keywords-hook)
  5672. ;; Now set the full font-lock-keywords
  5673. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5674. (setq-local font-lock-defaults
  5675. '(org-font-lock-keywords t nil nil backward-paragraph))
  5676. (kill-local-variable 'font-lock-keywords)
  5677. nil))
  5678. (defun org-toggle-pretty-entities ()
  5679. "Toggle the composition display of entities as UTF8 characters."
  5680. (interactive)
  5681. (setq-local org-pretty-entities (not org-pretty-entities))
  5682. (org-restart-font-lock)
  5683. (if org-pretty-entities
  5684. (message "Entities are now displayed as UTF8 characters")
  5685. (save-restriction
  5686. (widen)
  5687. (decompose-region (point-min) (point-max))
  5688. (message "Entities are now displayed as plain text"))))
  5689. (defvar-local org-custom-properties-overlays nil
  5690. "List of overlays used for custom properties.")
  5691. (defun org-toggle-custom-properties-visibility ()
  5692. "Display or hide properties in `org-custom-properties'."
  5693. (interactive)
  5694. (if org-custom-properties-overlays
  5695. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5696. (setq org-custom-properties-overlays nil))
  5697. (when org-custom-properties
  5698. (org-with-wide-buffer
  5699. (goto-char (point-min))
  5700. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5701. (while (re-search-forward regexp nil t)
  5702. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5703. (when (and end (< (point) end))
  5704. ;; Hide first custom property in current drawer.
  5705. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5706. (overlay-put o 'invisible t)
  5707. (overlay-put o 'org-custom-property t)
  5708. (push o org-custom-properties-overlays))
  5709. ;; Hide additional custom properties in the same drawer.
  5710. (while (re-search-forward regexp end t)
  5711. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5712. (overlay-put o 'invisible t)
  5713. (overlay-put o 'org-custom-property t)
  5714. (push o org-custom-properties-overlays)))))
  5715. ;; Each entry is limited to a single property drawer.
  5716. (outline-next-heading)))))))
  5717. (defun org-fontify-entities (limit)
  5718. "Find an entity to fontify."
  5719. (let (ee)
  5720. (when org-pretty-entities
  5721. (catch 'match
  5722. ;; "\_ "-family is left out on purpose. Only the first one,
  5723. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5724. ;; confusing when adding a second white space character.
  5725. (while (re-search-forward
  5726. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5727. limit t)
  5728. (when (and (not (org-at-comment-p))
  5729. (setq ee (org-entity-get (match-string 1)))
  5730. (= (length (nth 6 ee)) 1))
  5731. (let* ((end (if (equal (match-string 2) "{}")
  5732. (match-end 2)
  5733. (match-end 1))))
  5734. (add-text-properties
  5735. (match-beginning 0) end
  5736. (list 'font-lock-fontified t))
  5737. (compose-region (match-beginning 0) end
  5738. (nth 6 ee) nil)
  5739. (backward-char 1)
  5740. (throw 'match t))))
  5741. nil))))
  5742. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5743. "Fontify string S like in Org mode."
  5744. (with-temp-buffer
  5745. (insert s)
  5746. (let ((org-odd-levels-only odd-levels))
  5747. (org-mode)
  5748. (org-font-lock-ensure)
  5749. (buffer-string))))
  5750. (defvar org-m nil)
  5751. (defvar org-l nil)
  5752. (defvar org-f nil)
  5753. (defun org-get-level-face (n)
  5754. "Get the right face for match N in font-lock matching of headlines."
  5755. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5756. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5757. (if org-cycle-level-faces
  5758. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5759. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5760. (cond
  5761. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5762. ((eq n 2) org-f)
  5763. (t (unless org-level-color-stars-only org-f))))
  5764. (defun org-face-from-face-or-color (context inherit face-or-color)
  5765. "Create a face list that inherits INHERIT, but sets the foreground color.
  5766. When FACE-OR-COLOR is not a string, just return it."
  5767. (if (stringp face-or-color)
  5768. (list :inherit inherit
  5769. (cdr (assoc context org-faces-easy-properties))
  5770. face-or-color)
  5771. face-or-color))
  5772. (defun org-get-todo-face (kwd)
  5773. "Get the right face for a TODO keyword KWD.
  5774. If KWD is a number, get the corresponding match group."
  5775. (when (numberp kwd) (setq kwd (match-string kwd)))
  5776. (or (org-face-from-face-or-color
  5777. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5778. (and (member kwd org-done-keywords) 'org-done)
  5779. 'org-todo))
  5780. (defun org-get-priority-face (priority)
  5781. "Get the right face for PRIORITY.
  5782. PRIORITY is a character."
  5783. (or (org-face-from-face-or-color
  5784. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5785. 'org-priority))
  5786. (defun org-get-tag-face (tag)
  5787. "Get the right face for TAG.
  5788. If TAG is a number, get the corresponding match group."
  5789. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5790. (or (org-face-from-face-or-color
  5791. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5792. 'org-tag)))
  5793. (defun org-font-lock-add-priority-faces (limit)
  5794. "Add the special priority faces."
  5795. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5796. (add-text-properties
  5797. (match-beginning 1) (match-end 1)
  5798. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5799. 'font-lock-fontified t))))
  5800. (defun org-font-lock-add-tag-faces (limit)
  5801. "Add the special tag faces."
  5802. (when (and org-tag-faces org-tags-special-faces-re)
  5803. (while (re-search-forward org-tags-special-faces-re limit t)
  5804. (add-text-properties (match-beginning 1) (match-end 1)
  5805. (list 'face (org-get-tag-face 1)
  5806. 'font-lock-fontified t))
  5807. (backward-char 1))))
  5808. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5809. "Remove fontification and activation overlays from links."
  5810. (font-lock-default-unfontify-region beg end)
  5811. (let* ((buffer-undo-list t)
  5812. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5813. (inhibit-modification-hooks t)
  5814. deactivate-mark buffer-file-name buffer-file-truename)
  5815. (decompose-region beg end)
  5816. (remove-text-properties beg end
  5817. '(mouse-face t keymap t org-linked-text t
  5818. invisible t intangible t
  5819. org-emphasis t))
  5820. (org-remove-font-lock-display-properties beg end)))
  5821. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5822. ((raise 0.3) (height 0.7))
  5823. ((raise -0.5))
  5824. ((raise 0.5)))
  5825. "Display properties for showing superscripts and subscripts.")
  5826. (defun org-remove-font-lock-display-properties (beg end)
  5827. "Remove specific display properties that have been added by font lock.
  5828. The will remove the raise properties that are used to show superscripts
  5829. and subscripts."
  5830. (let (next prop)
  5831. (while (< beg end)
  5832. (setq next (next-single-property-change beg 'display nil end)
  5833. prop (get-text-property beg 'display))
  5834. (when (member prop org-script-display)
  5835. (put-text-property beg next 'display nil))
  5836. (setq beg next))))
  5837. (defun org-raise-scripts (limit)
  5838. "Add raise properties to sub/superscripts."
  5839. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5840. (re-search-forward
  5841. (if (eq org-use-sub-superscripts t)
  5842. org-match-substring-regexp
  5843. org-match-substring-with-braces-regexp)
  5844. limit t))
  5845. (let* ((pos (point)) table-p comment-p
  5846. (mpos (match-beginning 3))
  5847. (emph-p (get-text-property mpos 'org-emphasis))
  5848. (link-p (get-text-property mpos 'mouse-face))
  5849. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5850. (goto-char (point-at-bol))
  5851. (setq table-p (looking-at-p org-table-dataline-regexp)
  5852. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5853. (goto-char pos)
  5854. ;; Handle a_b^c
  5855. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5856. (unless (or comment-p emph-p link-p keyw-p)
  5857. (put-text-property (match-beginning 3) (match-end 0)
  5858. 'display
  5859. (if (equal (char-after (match-beginning 2)) ?^)
  5860. (nth (if table-p 3 1) org-script-display)
  5861. (nth (if table-p 2 0) org-script-display)))
  5862. (add-text-properties (match-beginning 2) (match-end 2)
  5863. (list 'invisible t))
  5864. (when (and (eq (char-after (match-beginning 3)) ?{)
  5865. (eq (char-before (match-end 3)) ?}))
  5866. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5867. (list 'invisible t))
  5868. (add-text-properties (1- (match-end 3)) (match-end 3)
  5869. (list 'invisible t))))
  5870. t)))
  5871. (defun org-remove-empty-overlays-at (pos)
  5872. "Remove outline overlays that do not contain non-white stuff."
  5873. (dolist (o (overlays-at pos))
  5874. (and (eq 'outline (overlay-get o 'invisible))
  5875. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5876. (overlay-end o))))
  5877. (delete-overlay o))))
  5878. (defun org-show-empty-lines-in-parent ()
  5879. "Move to the parent and re-show empty lines before visible headlines."
  5880. (save-excursion
  5881. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5882. (org-cycle-show-empty-lines context))))
  5883. (defun org-files-list ()
  5884. "Return `org-agenda-files' list, plus all open Org files.
  5885. This is useful for operations that need to scan all of a user's
  5886. open and agenda-wise Org files."
  5887. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5888. (dolist (buf (buffer-list))
  5889. (with-current-buffer buf
  5890. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5891. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5892. :test #'equal))))
  5893. files))
  5894. (defsubst org-entry-beginning-position ()
  5895. "Return the beginning position of the current entry."
  5896. (save-excursion (org-back-to-heading t) (point)))
  5897. (defsubst org-entry-end-position ()
  5898. "Return the end position of the current entry."
  5899. (save-excursion (outline-next-heading) (point)))
  5900. (defun org-subtree-end-visible-p ()
  5901. "Is the end of the current subtree visible?"
  5902. (pos-visible-in-window-p
  5903. (save-excursion (org-end-of-subtree t) (point))))
  5904. (defun org-first-headline-recenter ()
  5905. "Move cursor to the first headline and recenter the headline."
  5906. (let ((window (get-buffer-window)))
  5907. (when window
  5908. (goto-char (point-min))
  5909. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5910. (set-window-start window (line-beginning-position))))))
  5911. ;;; Visibility (headlines, blocks, drawers)
  5912. ;;;; Headlines visibility
  5913. (defun org-show-entry ()
  5914. "Show the body directly following this heading.
  5915. Show the heading too, if it is currently invisible."
  5916. (interactive)
  5917. (save-excursion
  5918. (ignore-errors
  5919. (org-back-to-heading t)
  5920. (org-flag-region
  5921. (line-end-position 0)
  5922. (save-excursion
  5923. (if (re-search-forward
  5924. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5925. (match-beginning 1)
  5926. (point-max)))
  5927. nil
  5928. 'outline))))
  5929. (defun org-show-children (&optional level)
  5930. "Show all direct subheadings of this heading.
  5931. Prefix arg LEVEL is how many levels below the current level
  5932. should be shown. Default is enough to cause the following
  5933. heading to appear."
  5934. (interactive "p")
  5935. (save-excursion
  5936. (org-back-to-heading t)
  5937. (let* ((current-level (funcall outline-level))
  5938. (max-level (org-get-valid-level
  5939. current-level
  5940. (if level (prefix-numeric-value level) 1)))
  5941. (end (save-excursion (org-end-of-subtree t t)))
  5942. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5943. (past-first-child nil)
  5944. ;; Make sure to skip inlinetasks.
  5945. (re (format regexp-fmt
  5946. current-level
  5947. (cond
  5948. ((not (featurep 'org-inlinetask)) "")
  5949. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5950. 3))
  5951. (t (1- org-inlinetask-min-level))))))
  5952. ;; Display parent heading.
  5953. (org-flag-heading nil)
  5954. (forward-line)
  5955. ;; Display children. First child may be deeper than expected
  5956. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5957. ;; MAX-LEVEL accordingly.
  5958. (while (re-search-forward re end t)
  5959. (unless past-first-child
  5960. (setq re (format regexp-fmt
  5961. current-level
  5962. (max (funcall outline-level) max-level)))
  5963. (setq past-first-child t))
  5964. (org-flag-heading nil)))))
  5965. (defun org-show-subtree ()
  5966. "Show everything after this heading at deeper levels."
  5967. (interactive)
  5968. (org-flag-region
  5969. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5970. ;;;; Blocks visibility
  5971. (defun org-hide-block-toggle-maybe ()
  5972. "Toggle visibility of block at point.
  5973. Unlike to `org-hide-block-toggle', this function does not throw
  5974. an error. Return a non-nil value when toggling is successful."
  5975. (interactive)
  5976. (ignore-errors (org-hide-block-toggle)))
  5977. (defun org-hide-block-toggle (&optional force)
  5978. "Toggle the visibility of the current block.
  5979. When optional argument FORCE is `off', make block visible. If it
  5980. is non-nil, hide it unconditionally. Throw an error when not at
  5981. a block. Return a non-nil value when toggling is successful."
  5982. (interactive)
  5983. (let ((element (org-element-at-point)))
  5984. (unless (memq (org-element-type element)
  5985. '(center-block comment-block dynamic-block example-block
  5986. export-block quote-block special-block
  5987. src-block verse-block))
  5988. (user-error "Not at a block"))
  5989. (let* ((post (org-element-property :post-affiliated element))
  5990. (start (save-excursion
  5991. (goto-char post)
  5992. (line-end-position)))
  5993. (end (save-excursion
  5994. (goto-char (org-element-property :end element))
  5995. (skip-chars-backward " \t\n")
  5996. (line-end-position))))
  5997. ;; Do nothing when not before or at the block opening line or at
  5998. ;; the block closing line.
  5999. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  6000. (cond ((eq force 'off)
  6001. (org-flag-region start end nil 'org-hide-block))
  6002. (force
  6003. (org-flag-region start end t 'org-hide-block))
  6004. ((eq (get-char-property start 'invisible) 'org-hide-block)
  6005. (org-flag-region start end nil 'org-hide-block))
  6006. (t
  6007. (org-flag-region start end t 'org-hide-block)))
  6008. ;; When the block is hidden away, make sure point is left in
  6009. ;; a visible part of the buffer.
  6010. (when (invisible-p (max (1- (point)) (point-min)))
  6011. (goto-char post))
  6012. ;; Signal success.
  6013. t))))
  6014. (defun org-hide-block-toggle-all ()
  6015. "Toggle the visibility of all blocks in the current buffer."
  6016. (org-block-map 'org-hide-block-toggle))
  6017. (defun org-hide-block-all ()
  6018. "Fold all blocks in the current buffer."
  6019. (interactive)
  6020. (org-show-all '(blocks))
  6021. (org-block-map 'org-hide-block-toggle-maybe))
  6022. ;;;; Drawers visibility
  6023. (defun org-cycle-hide-drawers (state &optional exceptions)
  6024. "Re-hide all drawers after a visibility state change.
  6025. STATE should be one of the symbols listed in the docstring of
  6026. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6027. a list of strings specifying which drawers should not be hidden."
  6028. (when (and (derived-mode-p 'org-mode)
  6029. (not (memq state '(overview folded contents))))
  6030. (save-excursion
  6031. (let* ((globalp (eq state 'all))
  6032. (beg (if globalp (point-min) (point)))
  6033. (end (if globalp (point-max)
  6034. (if (eq state 'children)
  6035. (save-excursion (outline-next-heading) (point))
  6036. (org-end-of-subtree t)))))
  6037. (goto-char beg)
  6038. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6039. (unless (member-ignore-case (match-string 1) exceptions)
  6040. (let ((drawer (org-element-at-point)))
  6041. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6042. (org-flag-drawer t drawer)
  6043. ;; Make sure to skip drawer entirely or we might flag
  6044. ;; it another time when matching its ending line with
  6045. ;; `org-drawer-regexp'.
  6046. (goto-char (org-element-property :end drawer))))))))))
  6047. (defun org-flag-drawer (flag &optional element)
  6048. "When FLAG is non-nil, hide the drawer we are at.
  6049. Otherwise make it visible. When optional argument ELEMENT is
  6050. a parsed drawer, as returned by `org-element-at-point', hide or
  6051. show that drawer instead."
  6052. (let ((drawer (or element
  6053. (and (save-excursion
  6054. (beginning-of-line)
  6055. (looking-at-p org-drawer-regexp))
  6056. (org-element-at-point)))))
  6057. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6058. (let ((post (org-element-property :post-affiliated drawer)))
  6059. (org-flag-region
  6060. (save-excursion (goto-char post) (line-end-position))
  6061. (save-excursion (goto-char (org-element-property :end drawer))
  6062. (skip-chars-backward " \t\n")
  6063. (line-end-position))
  6064. flag 'org-hide-drawer)
  6065. ;; When the drawer is hidden away, make sure point lies in
  6066. ;; a visible part of the buffer.
  6067. (when (invisible-p (max (1- (point)) (point-min)))
  6068. (goto-char post))))))
  6069. ;;;; Visibility cycling
  6070. (defvar-local org-cycle-global-status nil)
  6071. (put 'org-cycle-global-status 'org-state t)
  6072. (defvar-local org-cycle-subtree-status nil)
  6073. (put 'org-cycle-subtree-status 'org-state t)
  6074. (defun org-show-all (&optional types)
  6075. "Show all contents in the visible part of the buffer.
  6076. By default, the function expands headings, blocks and drawers.
  6077. When optional argument TYPE is a list of symbols among `blocks',
  6078. `drawers' and `headings', to only expand one specific type."
  6079. (dolist (type (or types '(blocks drawers headings)))
  6080. (org-flag-region (point-min) (point-max) nil
  6081. (pcase type
  6082. (`blocks 'org-hide-block)
  6083. (`drawers 'org-hide-drawer)
  6084. (`headings 'outline)
  6085. (_ (error "Invalid type: %S" type))))))
  6086. ;;;###autoload
  6087. (defun org-cycle (&optional arg)
  6088. "TAB-action and visibility cycling for Org mode.
  6089. This is the command invoked in Org mode by the `TAB' key. Its main
  6090. purpose is outline visibility cycling, but it also invokes other actions
  6091. in special contexts.
  6092. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6093. the entire
  6094. buffer through 3 states (global cycling)
  6095. 1. OVERVIEW: Show only top-level headlines.
  6096. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6097. 3. SHOW ALL: Show everything.
  6098. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6099. switch to the startup visibility,
  6100. determined by the variable `org-startup-folded', and by any VISIBILITY
  6101. properties in the buffer.
  6102. With a `\\[universal-argument] \\[universal-argument] \
  6103. \\[universal-argument]' prefix argument, show the entire buffer, including
  6104. any drawers.
  6105. When inside a table, re-align the table and move to the next field.
  6106. When point is at the beginning of a headline, rotate the subtree started
  6107. by this line through 3 different states (local cycling)
  6108. 1. FOLDED: Only the main headline is shown.
  6109. 2. CHILDREN: The main headline and the direct children are shown.
  6110. From this state, you can move to one of the children
  6111. and zoom in further.
  6112. 3. SUBTREE: Show the entire subtree, including body text.
  6113. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6114. When point is at the beginning of an empty headline and the variable
  6115. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6116. of the headline by demoting and promoting it to likely levels. This
  6117. speeds up creation document structure by pressing `TAB' once or several
  6118. times right after creating a new headline.
  6119. When there is a numeric prefix, go up to a heading with level ARG, do
  6120. a `show-subtree' and return to the previous cursor position. If ARG
  6121. is negative, go up that many levels.
  6122. When point is not at the beginning of a headline, execute the global
  6123. binding for `TAB', which is re-indenting the line. See the option
  6124. `org-cycle-emulate-tab' for details.
  6125. As a special case, if point is at the beginning of the buffer and there is
  6126. no headline in line 1, this function will act as if called with prefix arg
  6127. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6128. prefix arg, but only
  6129. if the variable `org-cycle-global-at-bob' is t."
  6130. (interactive "P")
  6131. (org-load-modules-maybe)
  6132. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6133. (and org-cycle-level-after-item/entry-creation
  6134. (or (org-cycle-level)
  6135. (org-cycle-item-indentation))))
  6136. (let* ((limit-level
  6137. (or org-cycle-max-level
  6138. (and (boundp 'org-inlinetask-min-level)
  6139. org-inlinetask-min-level
  6140. (1- org-inlinetask-min-level))))
  6141. (nstars (and limit-level
  6142. (if org-odd-levels-only
  6143. (and limit-level (1- (* limit-level 2)))
  6144. limit-level)))
  6145. (org-outline-regexp
  6146. (if (not (derived-mode-p 'org-mode))
  6147. outline-regexp
  6148. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6149. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6150. (not (looking-at org-outline-regexp))))
  6151. (org-cycle-hook
  6152. (if bob-special
  6153. (delq 'org-optimize-window-after-visibility-change
  6154. (copy-sequence org-cycle-hook))
  6155. org-cycle-hook))
  6156. (pos (point)))
  6157. (cond
  6158. ((equal arg '(16))
  6159. (setq last-command 'dummy)
  6160. (org-set-startup-visibility)
  6161. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6162. ((equal arg '(64))
  6163. (org-show-all)
  6164. (org-unlogged-message "Entire buffer visible, including drawers"))
  6165. ((equal arg '(4)) (org-cycle-internal-global))
  6166. ;; Try hiding block at point.
  6167. ((org-hide-block-toggle-maybe))
  6168. ;; Try cdlatex TAB completion
  6169. ((org-try-cdlatex-tab))
  6170. ;; Table: enter it or move to the next field.
  6171. ((org-at-table-p 'any)
  6172. (if (org-at-table.el-p)
  6173. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6174. Use `\\[org-edit-special]' to edit table.el tables"))
  6175. (if arg (org-table-edit-field t)
  6176. (org-table-justify-field-maybe)
  6177. (call-interactively 'org-table-next-field))))
  6178. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6179. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6180. (bob-special (org-cycle-internal-global))
  6181. ;; Drawers: delegate to `org-flag-drawer'.
  6182. ((save-excursion
  6183. (beginning-of-line 1)
  6184. (looking-at org-drawer-regexp))
  6185. (org-flag-drawer ; toggle block visibility
  6186. (not (get-char-property (match-end 0) 'invisible))))
  6187. ;; Show-subtree, ARG levels up from here.
  6188. ((integerp arg)
  6189. (save-excursion
  6190. (org-back-to-heading)
  6191. (outline-up-heading (if (< arg 0) (- arg)
  6192. (- (funcall outline-level) arg)))
  6193. (org-show-subtree)))
  6194. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6195. ((and (featurep 'org-inlinetask)
  6196. (org-inlinetask-at-task-p)
  6197. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6198. (org-inlinetask-toggle-visibility))
  6199. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6200. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6201. (save-excursion (move-beginning-of-line 1)
  6202. (looking-at org-outline-regexp)))
  6203. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6204. (org-cycle-internal-local))
  6205. ;; From there: TAB emulation and template completion.
  6206. (buffer-read-only (org-back-to-heading))
  6207. ((run-hook-with-args-until-success
  6208. 'org-tab-after-check-for-cycling-hook))
  6209. ((run-hook-with-args-until-success
  6210. 'org-tab-before-tab-emulation-hook))
  6211. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6212. (or (not (bolp))
  6213. (not (looking-at org-outline-regexp))))
  6214. (call-interactively (global-key-binding "\t")))
  6215. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6216. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6217. (or (and (eq org-cycle-emulate-tab 'white)
  6218. (= (match-end 0) (point-at-eol)))
  6219. (and (eq org-cycle-emulate-tab 'whitestart)
  6220. (>= (match-end 0) pos))))
  6221. t
  6222. (eq org-cycle-emulate-tab t))
  6223. (call-interactively (global-key-binding "\t")))
  6224. (t (save-excursion
  6225. (org-back-to-heading)
  6226. (org-cycle)))))))
  6227. (defun org-cycle-internal-global ()
  6228. "Do the global cycling action."
  6229. ;; Hack to avoid display of messages for .org attachments in Gnus
  6230. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6231. (cond
  6232. ((and (eq last-command this-command)
  6233. (eq org-cycle-global-status 'overview))
  6234. ;; We just created the overview - now do table of contents
  6235. ;; This can be slow in very large buffers, so indicate action
  6236. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6237. (unless ga (org-unlogged-message "CONTENTS..."))
  6238. (org-content)
  6239. (unless ga (org-unlogged-message "CONTENTS...done"))
  6240. (setq org-cycle-global-status 'contents)
  6241. (run-hook-with-args 'org-cycle-hook 'contents))
  6242. ((and (eq last-command this-command)
  6243. (eq org-cycle-global-status 'contents))
  6244. ;; We just showed the table of contents - now show everything
  6245. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6246. (org-show-all '(headings blocks))
  6247. (unless ga (org-unlogged-message "SHOW ALL"))
  6248. (setq org-cycle-global-status 'all)
  6249. (run-hook-with-args 'org-cycle-hook 'all))
  6250. (t
  6251. ;; Default action: go to overview
  6252. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6253. (org-overview)
  6254. (unless ga (org-unlogged-message "OVERVIEW"))
  6255. (setq org-cycle-global-status 'overview)
  6256. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6257. (defvar org-called-with-limited-levels nil
  6258. "Non-nil when `org-with-limited-levels' is currently active.")
  6259. (defun org-cycle-internal-local ()
  6260. "Do the local cycling action."
  6261. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6262. ;; First, determine end of headline (EOH), end of subtree or item
  6263. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6264. (save-excursion
  6265. (if (org-at-item-p)
  6266. (progn
  6267. (beginning-of-line)
  6268. (setq struct (org-list-struct))
  6269. (setq eoh (point-at-eol))
  6270. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6271. (setq has-children (org-list-has-child-p (point) struct)))
  6272. (org-back-to-heading)
  6273. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6274. (setq eos (save-excursion (org-end-of-subtree t t)
  6275. (when (bolp) (backward-char)) (point)))
  6276. (setq has-children
  6277. (or (save-excursion
  6278. (let ((level (funcall outline-level)))
  6279. (outline-next-heading)
  6280. (and (org-at-heading-p t)
  6281. (> (funcall outline-level) level))))
  6282. (save-excursion
  6283. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6284. ;; Determine end invisible part of buffer (EOL)
  6285. (beginning-of-line 2)
  6286. (while (and (not (eobp)) ;This is like `next-line'.
  6287. (get-char-property (1- (point)) 'invisible))
  6288. (goto-char (next-single-char-property-change (point) 'invisible))
  6289. (and (eolp) (beginning-of-line 2)))
  6290. (setq eol (point)))
  6291. ;; Find out what to do next and set `this-command'
  6292. (cond
  6293. ((= eos eoh)
  6294. ;; Nothing is hidden behind this heading
  6295. (unless (org-before-first-heading-p)
  6296. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6297. (org-unlogged-message "EMPTY ENTRY")
  6298. (setq org-cycle-subtree-status nil)
  6299. (save-excursion
  6300. (goto-char eos)
  6301. (outline-next-heading)
  6302. (when (org-invisible-p) (org-flag-heading nil))))
  6303. ((and (or (>= eol eos)
  6304. (not (string-match "\\S-" (buffer-substring eol eos))))
  6305. (or has-children
  6306. (not (setq children-skipped
  6307. org-cycle-skip-children-state-if-no-children))))
  6308. ;; Entire subtree is hidden in one line: children view
  6309. (unless (org-before-first-heading-p)
  6310. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6311. (if (org-at-item-p)
  6312. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6313. (org-show-entry)
  6314. (org-with-limited-levels (org-show-children))
  6315. (org-show-set-visibility 'canonical)
  6316. ;; Fold every list in subtree to top-level items.
  6317. (when (eq org-cycle-include-plain-lists 'integrate)
  6318. (save-excursion
  6319. (org-back-to-heading)
  6320. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6321. (beginning-of-line 1)
  6322. (let* ((struct (org-list-struct))
  6323. (prevs (org-list-prevs-alist struct))
  6324. (end (org-list-get-bottom-point struct)))
  6325. (dolist (e (org-list-get-all-items (point) struct prevs))
  6326. (org-list-set-item-visibility e struct 'folded))
  6327. (goto-char (if (< end eos) end eos)))))))
  6328. (org-unlogged-message "CHILDREN")
  6329. (save-excursion
  6330. (goto-char eos)
  6331. (outline-next-heading)
  6332. (when (org-invisible-p) (org-flag-heading nil)))
  6333. (setq org-cycle-subtree-status 'children)
  6334. (unless (org-before-first-heading-p)
  6335. (run-hook-with-args 'org-cycle-hook 'children)))
  6336. ((or children-skipped
  6337. (and (eq last-command this-command)
  6338. (eq org-cycle-subtree-status 'children)))
  6339. ;; We just showed the children, or no children are there,
  6340. ;; now show everything.
  6341. (unless (org-before-first-heading-p)
  6342. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6343. (org-flag-region eoh eos nil 'outline)
  6344. (org-unlogged-message
  6345. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6346. (setq org-cycle-subtree-status 'subtree)
  6347. (unless (org-before-first-heading-p)
  6348. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6349. (t
  6350. ;; Default action: hide the subtree.
  6351. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6352. (org-flag-region eoh eos t 'outline)
  6353. (org-unlogged-message "FOLDED")
  6354. (setq org-cycle-subtree-status 'folded)
  6355. (unless (org-before-first-heading-p)
  6356. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6357. ;;;###autoload
  6358. (defun org-global-cycle (&optional arg)
  6359. "Cycle the global visibility. For details see `org-cycle'.
  6360. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6361. With a numeric prefix, show all headlines up to that level."
  6362. (interactive "P")
  6363. (let ((org-cycle-include-plain-lists
  6364. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6365. (cond
  6366. ((integerp arg)
  6367. (org-show-all '(headings blocks))
  6368. (outline-hide-sublevels arg)
  6369. (setq org-cycle-global-status 'contents))
  6370. ((equal arg '(4))
  6371. (org-set-startup-visibility)
  6372. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6373. (t
  6374. (org-cycle '(4))))))
  6375. (defun org-set-startup-visibility ()
  6376. "Set the visibility required by startup options and properties."
  6377. (cond
  6378. ((eq org-startup-folded t)
  6379. (org-overview))
  6380. ((eq org-startup-folded 'content)
  6381. (org-content))
  6382. ((or (eq org-startup-folded 'showeverything)
  6383. (eq org-startup-folded nil))
  6384. (org-show-all)))
  6385. (unless (eq org-startup-folded 'showeverything)
  6386. (when org-hide-block-startup (org-hide-block-all))
  6387. (org-set-visibility-according-to-property)
  6388. (org-cycle-hide-archived-subtrees 'all)
  6389. (org-cycle-hide-drawers 'all)
  6390. (org-cycle-show-empty-lines t)))
  6391. (defun org-set-visibility-according-to-property ()
  6392. "Switch subtree visibilities according to :VISIBILITY: property."
  6393. (interactive)
  6394. (org-with-wide-buffer
  6395. (goto-char (point-min))
  6396. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6397. (if (not (org-at-property-p)) (outline-next-heading)
  6398. (let ((state (match-string 3)))
  6399. (save-excursion
  6400. (org-back-to-heading t)
  6401. (outline-hide-subtree)
  6402. (org-reveal)
  6403. (cond
  6404. ((equal state "folded")
  6405. (outline-hide-subtree))
  6406. ((equal state "children")
  6407. (org-show-hidden-entry)
  6408. (org-show-children))
  6409. ((equal state "content")
  6410. (save-excursion
  6411. (save-restriction
  6412. (org-narrow-to-subtree)
  6413. (org-content))))
  6414. ((member state '("all" "showall"))
  6415. (outline-show-subtree)))))))))
  6416. (defun org-overview ()
  6417. "Switch to overview mode, showing only top-level headlines.
  6418. This shows all headlines with a level equal or greater than the level
  6419. of the first headline in the buffer. This is important, because if the
  6420. first headline is not level one, then (hide-sublevels 1) gives confusing
  6421. results."
  6422. (interactive)
  6423. (save-excursion
  6424. (let ((level
  6425. (save-excursion
  6426. (goto-char (point-min))
  6427. (when (re-search-forward org-outline-regexp-bol nil t)
  6428. (goto-char (match-beginning 0))
  6429. (funcall outline-level)))))
  6430. (and level (outline-hide-sublevels level)))))
  6431. (defun org-content (&optional arg)
  6432. "Show all headlines in the buffer, like a table of contents.
  6433. With numerical argument N, show content up to level N."
  6434. (interactive "P")
  6435. (org-overview)
  6436. (save-excursion
  6437. ;; Visit all headings and show their offspring
  6438. (and (integerp arg) (org-overview))
  6439. (goto-char (point-max))
  6440. (catch 'exit
  6441. (while (and (progn (condition-case nil
  6442. (outline-previous-visible-heading 1)
  6443. (error (goto-char (point-min))))
  6444. t)
  6445. (looking-at org-outline-regexp))
  6446. (if (integerp arg)
  6447. (org-show-children (1- arg))
  6448. (outline-show-branches))
  6449. (when (bobp) (throw 'exit nil))))))
  6450. (defun org-optimize-window-after-visibility-change (state)
  6451. "Adjust the window after a change in outline visibility.
  6452. This function is the default value of the hook `org-cycle-hook'."
  6453. (when (get-buffer-window (current-buffer))
  6454. (cond
  6455. ((eq state 'content) nil)
  6456. ((eq state 'all) nil)
  6457. ((eq state 'folded) nil)
  6458. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6459. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6460. (defun org-clean-visibility-after-subtree-move ()
  6461. "Fix visibility issues after moving a subtree."
  6462. ;; First, find a reasonable region to look at:
  6463. ;; Start two siblings above, end three below
  6464. (let* ((beg (save-excursion
  6465. (and (org-get-last-sibling)
  6466. (org-get-last-sibling))
  6467. (point)))
  6468. (end (save-excursion
  6469. (and (org-get-next-sibling)
  6470. (org-get-next-sibling)
  6471. (org-get-next-sibling))
  6472. (if (org-at-heading-p)
  6473. (point-at-eol)
  6474. (point))))
  6475. (level (looking-at "\\*+"))
  6476. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6477. (save-excursion
  6478. (save-restriction
  6479. (narrow-to-region beg end)
  6480. (when re
  6481. ;; Properly fold already folded siblings
  6482. (goto-char (point-min))
  6483. (while (re-search-forward re nil t)
  6484. (when (and (not (org-invisible-p))
  6485. (org-invisible-p (line-end-position)))
  6486. (outline-hide-entry))))
  6487. (org-cycle-hide-drawers 'all)
  6488. (org-cycle-show-empty-lines 'overview)))))
  6489. (defun org-cycle-show-empty-lines (state)
  6490. "Show empty lines above all visible headlines.
  6491. The region to be covered depends on STATE when called through
  6492. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6493. entire buffer covered. Note that an empty line is only shown if there
  6494. are at least `org-cycle-separator-lines' empty lines before the headline."
  6495. (when (/= org-cycle-separator-lines 0)
  6496. (save-excursion
  6497. (let* ((n (abs org-cycle-separator-lines))
  6498. (re (cond
  6499. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6500. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6501. (t (let ((ns (number-to-string (- n 2))))
  6502. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6503. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6504. beg end)
  6505. (cond
  6506. ((memq state '(overview contents t))
  6507. (setq beg (point-min) end (point-max)))
  6508. ((memq state '(children folded))
  6509. (setq beg (point)
  6510. end (progn (org-end-of-subtree t t)
  6511. (line-beginning-position 2)))))
  6512. (when beg
  6513. (goto-char beg)
  6514. (while (re-search-forward re end t)
  6515. (unless (get-char-property (match-end 1) 'invisible)
  6516. (let ((e (match-end 1))
  6517. (b (if (>= org-cycle-separator-lines 0)
  6518. (match-beginning 1)
  6519. (save-excursion
  6520. (goto-char (match-beginning 0))
  6521. (skip-chars-backward " \t\n")
  6522. (line-end-position)))))
  6523. (org-flag-region b e nil 'outline))))))))
  6524. ;; Never hide empty lines at the end of the file.
  6525. (save-excursion
  6526. (goto-char (point-max))
  6527. (outline-previous-heading)
  6528. (outline-end-of-heading)
  6529. (when (and (looking-at "[ \t\n]+")
  6530. (= (match-end 0) (point-max)))
  6531. (org-flag-region (point) (match-end 0) nil 'outline))))
  6532. ;;;; Reveal point location
  6533. (defun org-show-context (&optional key)
  6534. "Make sure point and context are visible.
  6535. Optional argument KEY, when non-nil, is a symbol. See
  6536. `org-show-context-detail' for allowed values and how much is to
  6537. be shown."
  6538. (org-show-set-visibility
  6539. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6540. ((cdr (assq key org-show-context-detail)))
  6541. (t (cdr (assq 'default org-show-context-detail))))))
  6542. (defun org-show-set-visibility (detail)
  6543. "Set visibility around point according to DETAIL.
  6544. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6545. `tree', `canonical' or t. See `org-show-context-detail' for more
  6546. information."
  6547. ;; Show current heading and possibly its entry, following headline
  6548. ;; or all children.
  6549. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6550. (org-flag-heading nil)
  6551. (org-show-entry)
  6552. ;; If point is hidden within a drawer or a block, make sure to
  6553. ;; expose it.
  6554. (dolist (o (overlays-at (point)))
  6555. (when (memq (overlay-get o 'invisible)
  6556. '(org-hide-block org-hide-drawer outline))
  6557. (delete-overlay o)))
  6558. (unless (org-before-first-heading-p)
  6559. (org-with-limited-levels
  6560. (cl-case detail
  6561. ((tree canonical t) (org-show-children))
  6562. ((nil minimal ancestors))
  6563. (t (save-excursion
  6564. (outline-next-heading)
  6565. (org-flag-heading nil)))))))
  6566. ;; Show all siblings.
  6567. (when (eq detail 'lineage) (org-show-siblings))
  6568. ;; Show ancestors, possibly with their children.
  6569. (when (memq detail '(ancestors lineage tree canonical t))
  6570. (save-excursion
  6571. (while (org-up-heading-safe)
  6572. (org-flag-heading nil)
  6573. (when (memq detail '(canonical t)) (org-show-entry))
  6574. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6575. (defvar org-reveal-start-hook nil
  6576. "Hook run before revealing a location.")
  6577. (defun org-reveal (&optional siblings)
  6578. "Show current entry, hierarchy above it, and the following headline.
  6579. This can be used to show a consistent set of context around
  6580. locations exposed with `org-show-context'.
  6581. With optional argument SIBLINGS, on each level of the hierarchy all
  6582. siblings are shown. This repairs the tree structure to what it would
  6583. look like when opened with hierarchical calls to `org-cycle'.
  6584. With a \\[universal-argument] \\[universal-argument] prefix, \
  6585. go to the parent and show the entire tree."
  6586. (interactive "P")
  6587. (run-hooks 'org-reveal-start-hook)
  6588. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6589. ((equal siblings '(16))
  6590. (save-excursion
  6591. (when (org-up-heading-safe)
  6592. (org-show-subtree)
  6593. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6594. (t (org-show-set-visibility 'lineage))))
  6595. ;;; Indirect buffer display of subtrees
  6596. (defvar org-indirect-dedicated-frame nil
  6597. "This is the frame being used for indirect tree display.")
  6598. (defvar org-last-indirect-buffer nil)
  6599. (defun org-tree-to-indirect-buffer (&optional arg)
  6600. "Create indirect buffer and narrow it to current subtree.
  6601. With a numerical prefix ARG, go up to this level and then take that tree.
  6602. If ARG is negative, go up that many levels.
  6603. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6604. indirect buffer previously made with this command, to avoid proliferation of
  6605. indirect buffers. However, when you call the command with a \
  6606. `\\[universal-argument]' prefix, or
  6607. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6608. so that you can work with several indirect buffers at the same time. If
  6609. `org-indirect-buffer-display' is `dedicated-frame', the \
  6610. `\\[universal-argument]' prefix also
  6611. requests that a new frame be made for the new buffer, so that the dedicated
  6612. frame is not changed."
  6613. (interactive "P")
  6614. (let ((cbuf (current-buffer))
  6615. (cwin (selected-window))
  6616. (pos (point))
  6617. beg end level heading ibuf)
  6618. (save-excursion
  6619. (org-back-to-heading t)
  6620. (when (numberp arg)
  6621. (setq level (org-outline-level))
  6622. (when (< arg 0) (setq arg (+ level arg)))
  6623. (while (> (setq level (org-outline-level)) arg)
  6624. (org-up-heading-safe)))
  6625. (setq beg (point)
  6626. heading (org-get-heading 'no-tags))
  6627. (org-end-of-subtree t t)
  6628. (when (org-at-heading-p) (backward-char 1))
  6629. (setq end (point)))
  6630. (when (and (buffer-live-p org-last-indirect-buffer)
  6631. (not (eq org-indirect-buffer-display 'new-frame))
  6632. (not arg))
  6633. (kill-buffer org-last-indirect-buffer))
  6634. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6635. org-last-indirect-buffer ibuf)
  6636. (cond
  6637. ((or (eq org-indirect-buffer-display 'new-frame)
  6638. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6639. (select-frame (make-frame))
  6640. (delete-other-windows)
  6641. (pop-to-buffer-same-window ibuf)
  6642. (org-set-frame-title heading))
  6643. ((eq org-indirect-buffer-display 'dedicated-frame)
  6644. (raise-frame
  6645. (select-frame (or (and org-indirect-dedicated-frame
  6646. (frame-live-p org-indirect-dedicated-frame)
  6647. org-indirect-dedicated-frame)
  6648. (setq org-indirect-dedicated-frame (make-frame)))))
  6649. (delete-other-windows)
  6650. (pop-to-buffer-same-window ibuf)
  6651. (org-set-frame-title (concat "Indirect: " heading)))
  6652. ((eq org-indirect-buffer-display 'current-window)
  6653. (pop-to-buffer-same-window ibuf))
  6654. ((eq org-indirect-buffer-display 'other-window)
  6655. (pop-to-buffer ibuf))
  6656. (t (error "Invalid value")))
  6657. (narrow-to-region beg end)
  6658. (org-show-all '(headings blocks))
  6659. (goto-char pos)
  6660. (run-hook-with-args 'org-cycle-hook 'all)
  6661. (and (window-live-p cwin) (select-window cwin))))
  6662. (defun org-get-indirect-buffer (&optional buffer heading)
  6663. (setq buffer (or buffer (current-buffer)))
  6664. (let ((n 1) (base (buffer-name buffer)) bname)
  6665. (while (buffer-live-p
  6666. (get-buffer
  6667. (setq bname
  6668. (concat base "-"
  6669. (if heading (concat heading "-" (number-to-string n))
  6670. (number-to-string n))))))
  6671. (setq n (1+ n)))
  6672. (condition-case nil
  6673. (make-indirect-buffer buffer bname 'clone)
  6674. (error (make-indirect-buffer buffer bname)))))
  6675. (defun org-set-frame-title (title)
  6676. "Set the title of the current frame to the string TITLE."
  6677. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6678. ;;;; Structure editing
  6679. ;;; Inserting headlines
  6680. (defun org--line-empty-p (n)
  6681. "Is the Nth next line empty?
  6682. Counts the current line as N = 1 and the previous line as N = 0;
  6683. see `beginning-of-line'."
  6684. (save-excursion
  6685. (and (not (bobp))
  6686. (or (beginning-of-line n) t)
  6687. (save-match-data
  6688. (looking-at "[ \t]*$")))))
  6689. (defun org-previous-line-empty-p ()
  6690. "Is the previous line a blank line?
  6691. When NEXT is non-nil, check the next line instead."
  6692. (org--line-empty-p 0))
  6693. (defun org-next-line-empty-p ()
  6694. "Is the previous line a blank line?
  6695. When NEXT is non-nil, check the next line instead."
  6696. (org--line-empty-p 2))
  6697. (defun org--blank-before-heading-p (&optional parent)
  6698. "Non-nil when an empty line should precede a new heading here.
  6699. When optional argument PARENT is non-nil, consider parent
  6700. headline instead of current one."
  6701. (pcase (assq 'heading org-blank-before-new-entry)
  6702. (`(heading . auto)
  6703. (save-excursion
  6704. (org-with-limited-levels
  6705. (unless (and (org-before-first-heading-p)
  6706. (not (outline-next-heading)))
  6707. (org-back-to-heading t)
  6708. (when parent (org-up-heading-safe))
  6709. (cond ((not (bobp))
  6710. (org-previous-line-empty-p))
  6711. ((outline-next-heading)
  6712. (org-previous-line-empty-p))
  6713. ;; Ignore trailing spaces on last buffer line.
  6714. ((progn (skip-chars-backward " \t") (bolp))
  6715. (org-previous-line-empty-p))
  6716. (t nil))))))
  6717. (`(heading . ,value) value)
  6718. (_ nil)))
  6719. (defun org-insert-heading (&optional arg invisible-ok top)
  6720. "Insert a new heading or an item with the same depth at point.
  6721. If point is at the beginning of a heading, insert a new heading
  6722. or a new headline above the current one. When at the beginning
  6723. of a regular line of text, turn it into a heading.
  6724. If point is in the middle of a line, split it and create a new
  6725. headline with the text in the current line after point (see
  6726. `org-M-RET-may-split-line' on how to modify this behavior). As
  6727. a special case, on a headline, splitting can only happen on the
  6728. title itself. E.g., this excludes breaking stars or tags.
  6729. With a `\\[universal-argument]' prefix, set \
  6730. `org-insert-heading-respect-content' to
  6731. a non-nil value for the duration of the command. This forces the
  6732. insertion of a heading after the current subtree, independently
  6733. on the location of point.
  6734. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6735. insert the heading at the end of the tree
  6736. above the current heading. For example, if point is within a
  6737. 2nd-level heading, then it will insert a 2nd-level heading at
  6738. the end of the 1st-level parent subtree.
  6739. When INVISIBLE-OK is set, stop at invisible headlines when going
  6740. back. This is important for non-interactive uses of the
  6741. command.
  6742. When optional argument TOP is non-nil, insert a level 1 heading,
  6743. unconditionally."
  6744. (interactive "P")
  6745. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6746. (level (org-current-level))
  6747. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6748. (cond
  6749. ((or org-insert-heading-respect-content
  6750. (member arg '((4) (16)))
  6751. (and (not invisible-ok)
  6752. (invisible-p (max (1- (point)) (point-min)))))
  6753. ;; Position point at the location of insertion.
  6754. (if (not level) ;before first headline
  6755. (org-with-limited-levels (outline-next-heading))
  6756. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6757. ;; is nil.
  6758. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6759. (cond ((equal arg '(16))
  6760. (org-up-heading-safe)
  6761. (org-end-of-subtree t t))
  6762. (t
  6763. (org-end-of-subtree t t))))
  6764. (unless (bolp) (insert "\n")) ;ensure final newline
  6765. (unless (and blank? (org-previous-line-empty-p))
  6766. (org-N-empty-lines-before-current (if blank? 1 0)))
  6767. (insert stars " \n")
  6768. (forward-char -1))
  6769. ;; At a headline...
  6770. ((org-at-heading-p)
  6771. (cond ((bolp)
  6772. (when blank? (save-excursion (insert "\n")))
  6773. (save-excursion (insert stars " \n"))
  6774. (unless (and blank? (org-previous-line-empty-p))
  6775. (org-N-empty-lines-before-current (if blank? 1 0)))
  6776. (end-of-line))
  6777. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6778. (org-match-line org-complex-heading-regexp)
  6779. (org-pos-in-match-range (point) 4))
  6780. ;; Grab the text that should moved to the new headline.
  6781. ;; Preserve tags.
  6782. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6783. (if (looking-at "[ \t]*$") (replace-match "")
  6784. (org-align-tags))
  6785. (end-of-line)
  6786. (when blank? (insert "\n"))
  6787. (insert "\n" stars " ")
  6788. (when (org-string-nw-p split) (insert split))
  6789. (when (eobp) (save-excursion (insert "\n")))))
  6790. (t
  6791. (end-of-line)
  6792. (when blank? (insert "\n"))
  6793. (insert "\n" stars " ")
  6794. (when (eobp) (save-excursion (insert "\n"))))))
  6795. ;; On regular text, turn line into a headline or split, if
  6796. ;; appropriate.
  6797. ((bolp)
  6798. (insert stars " ")
  6799. (unless (and blank? (org-previous-line-empty-p))
  6800. (org-N-empty-lines-before-current (if blank? 1 0))))
  6801. (t
  6802. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6803. (end-of-line))
  6804. (insert "\n" stars " ")
  6805. (unless (and blank? (org-previous-line-empty-p))
  6806. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6807. (run-hooks 'org-insert-heading-hook))
  6808. (defun org-N-empty-lines-before-current (n)
  6809. "Make the number of empty lines before current exactly N.
  6810. So this will delete or add empty lines."
  6811. (let ((column (current-column)))
  6812. (beginning-of-line)
  6813. (unless (bobp)
  6814. (let ((start (save-excursion
  6815. (skip-chars-backward " \r\t\n")
  6816. (line-end-position))))
  6817. (delete-region start (line-end-position 0))))
  6818. (insert (make-string n ?\n))
  6819. (move-to-column column)))
  6820. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6821. "Return the heading of the current entry, without the stars.
  6822. When NO-TAGS is non-nil, don't include tags.
  6823. When NO-TODO is non-nil, don't include TODO keywords.
  6824. When NO-PRIORITY is non-nil, don't include priority cookie.
  6825. When NO-COMMENT is non-nil, don't include COMMENT string.
  6826. Return nil before first heading."
  6827. (unless (org-before-first-heading-p)
  6828. (save-excursion
  6829. (org-back-to-heading t)
  6830. (let ((case-fold-search nil))
  6831. (looking-at org-complex-heading-regexp)
  6832. (let ((todo (and (not no-todo) (match-string 2)))
  6833. (priority (and (not no-priority) (match-string 3)))
  6834. (headline (pcase (match-string 4)
  6835. (`nil "")
  6836. ((and (guard no-comment) h)
  6837. (replace-regexp-in-string
  6838. (eval-when-compile
  6839. (format "\\`%s[ \t]+" org-comment-string))
  6840. "" h))
  6841. (h h)))
  6842. (tags (and (not no-tags) (match-string 5))))
  6843. (mapconcat #'identity
  6844. (delq nil (list todo priority headline tags))
  6845. " "))))))
  6846. (defun org-heading-components ()
  6847. "Return the components of the current heading.
  6848. This is a list with the following elements:
  6849. - the level as an integer
  6850. - the reduced level, different if `org-odd-levels-only' is set.
  6851. - the TODO keyword, or nil
  6852. - the priority character, like ?A, or nil if no priority is given
  6853. - the headline text itself, or the tags string if no headline text
  6854. - the tags string, or nil."
  6855. (save-excursion
  6856. (org-back-to-heading t)
  6857. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6858. (list (length (match-string 1))
  6859. (org-reduced-level (length (match-string 1)))
  6860. (match-string-no-properties 2)
  6861. (and (match-end 3) (aref (match-string 3) 2))
  6862. (match-string-no-properties 4)
  6863. (match-string-no-properties 5)))))
  6864. (defun org-get-entry ()
  6865. "Get the entry text, after heading, entire subtree."
  6866. (save-excursion
  6867. (org-back-to-heading t)
  6868. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6869. (defun org-edit-headline (&optional heading)
  6870. "Edit the current headline.
  6871. Set it to HEADING when provided."
  6872. (interactive)
  6873. (org-with-wide-buffer
  6874. (org-back-to-heading t)
  6875. (let ((case-fold-search nil))
  6876. (when (looking-at org-complex-heading-regexp)
  6877. (let* ((old (match-string-no-properties 4))
  6878. (new (save-match-data
  6879. (org-trim (or heading (read-string "Edit: " old))))))
  6880. (unless (equal old new)
  6881. (if old (replace-match new t t nil 4)
  6882. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6883. (insert " " new))
  6884. (org-align-tags)
  6885. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6886. (defun org-insert-heading-after-current ()
  6887. "Insert a new heading with same level as current, after current subtree."
  6888. (interactive)
  6889. (org-back-to-heading)
  6890. (org-insert-heading)
  6891. (org-move-subtree-down)
  6892. (end-of-line 1))
  6893. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6894. "Insert heading with `org-insert-heading-respect-content' set to t."
  6895. (interactive)
  6896. (org-insert-heading '(4) invisible-ok))
  6897. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6898. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6899. (interactive)
  6900. (org-insert-todo-heading force-state '(4)))
  6901. (defun org-insert-todo-heading (arg &optional force-heading)
  6902. "Insert a new heading with the same level and TODO state as current heading.
  6903. If the heading has no TODO state, or if the state is DONE, use
  6904. the first state (TODO by default). Also with one prefix arg,
  6905. force first state. With two prefix args, force inserting at the
  6906. end of the parent subtree.
  6907. When called at a plain list item, insert a new item with an
  6908. unchecked check box."
  6909. (interactive "P")
  6910. (when (or force-heading (not (org-insert-item 'checkbox)))
  6911. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6912. force-heading))
  6913. (save-excursion
  6914. (org-forward-heading-same-level -1)
  6915. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6916. (let* ((new-mark-x
  6917. (if (or (equal arg '(4))
  6918. (not (match-beginning 2))
  6919. (member (match-string 2) org-done-keywords))
  6920. (car org-todo-keywords-1)
  6921. (match-string 2)))
  6922. (new-mark
  6923. (or
  6924. (run-hook-with-args-until-success
  6925. 'org-todo-get-default-hook new-mark-x nil)
  6926. new-mark-x)))
  6927. (beginning-of-line 1)
  6928. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6929. (if org-treat-insert-todo-heading-as-state-change
  6930. (org-todo new-mark)
  6931. (insert new-mark " "))))
  6932. (when org-provide-todo-statistics
  6933. (org-update-parent-todo-statistics))))
  6934. (defun org-insert-subheading (arg)
  6935. "Insert a new subheading and demote it.
  6936. Works for outline headings and for plain lists alike."
  6937. (interactive "P")
  6938. (org-insert-heading arg)
  6939. (cond
  6940. ((org-at-heading-p) (org-do-demote))
  6941. ((org-at-item-p) (org-indent-item))))
  6942. (defun org-insert-todo-subheading (arg)
  6943. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6944. Works for outline headings and for plain lists alike."
  6945. (interactive "P")
  6946. (org-insert-todo-heading arg)
  6947. (cond
  6948. ((org-at-heading-p) (org-do-demote))
  6949. ((org-at-item-p) (org-indent-item))))
  6950. ;;; Promotion and Demotion
  6951. (defvar org-after-demote-entry-hook nil
  6952. "Hook run after an entry has been demoted.
  6953. The cursor will be at the beginning of the entry.
  6954. When a subtree is being demoted, the hook will be called for each node.")
  6955. (defvar org-after-promote-entry-hook nil
  6956. "Hook run after an entry has been promoted.
  6957. The cursor will be at the beginning of the entry.
  6958. When a subtree is being promoted, the hook will be called for each node.")
  6959. (defun org-promote-subtree ()
  6960. "Promote the entire subtree.
  6961. See also `org-promote'."
  6962. (interactive)
  6963. (save-excursion
  6964. (org-with-limited-levels (org-map-tree 'org-promote)))
  6965. (org-fix-position-after-promote))
  6966. (defun org-demote-subtree ()
  6967. "Demote the entire subtree.
  6968. See `org-demote' and `org-promote'."
  6969. (interactive)
  6970. (save-excursion
  6971. (org-with-limited-levels (org-map-tree 'org-demote)))
  6972. (org-fix-position-after-promote))
  6973. (defun org-do-promote ()
  6974. "Promote the current heading higher up the tree.
  6975. If the region is active in `transient-mark-mode', promote all
  6976. headings in the region."
  6977. (interactive)
  6978. (save-excursion
  6979. (if (org-region-active-p)
  6980. (org-map-region 'org-promote (region-beginning) (region-end))
  6981. (org-promote)))
  6982. (org-fix-position-after-promote))
  6983. (defun org-do-demote ()
  6984. "Demote the current heading lower down the tree.
  6985. If the region is active in `transient-mark-mode', demote all
  6986. headings in the region."
  6987. (interactive)
  6988. (save-excursion
  6989. (if (org-region-active-p)
  6990. (org-map-region 'org-demote (region-beginning) (region-end))
  6991. (org-demote)))
  6992. (org-fix-position-after-promote))
  6993. (defun org-fix-position-after-promote ()
  6994. "Fix cursor position and indentation after demoting/promoting."
  6995. (let ((pos (point)))
  6996. (when (save-excursion
  6997. (beginning-of-line)
  6998. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6999. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7000. (cond ((eobp) (insert " "))
  7001. ((eolp) (insert " "))
  7002. ((equal (char-after) ?\s) (forward-char 1))))))
  7003. (defun org-current-level ()
  7004. "Return the level of the current entry, or nil if before the first headline.
  7005. The level is the number of stars at the beginning of the
  7006. headline. Use `org-reduced-level' to remove the effect of
  7007. `org-odd-levels'. Unlike to `org-outline-level', this function
  7008. ignores inlinetasks."
  7009. (let ((level (org-with-limited-levels (org-outline-level))))
  7010. (and (> level 0) level)))
  7011. (defun org-get-previous-line-level ()
  7012. "Return the outline depth of the last headline before the current line.
  7013. Returns 0 for the first headline in the buffer, and nil if before the
  7014. first headline."
  7015. (and (org-current-level)
  7016. (or (and (/= (line-beginning-position) (point-min))
  7017. (save-excursion (beginning-of-line 0) (org-current-level)))
  7018. 0)))
  7019. (defun org-reduced-level (l)
  7020. "Compute the effective level of a heading.
  7021. This takes into account the setting of `org-odd-levels-only'."
  7022. (cond
  7023. ((zerop l) 0)
  7024. (org-odd-levels-only (1+ (floor (/ l 2))))
  7025. (t l)))
  7026. (defun org-level-increment ()
  7027. "Return the number of stars that will be added or removed at a
  7028. time to headlines when structure editing, based on the value of
  7029. `org-odd-levels-only'."
  7030. (if org-odd-levels-only 2 1))
  7031. (defun org-get-valid-level (level &optional change)
  7032. "Rectify a level change under the influence of `org-odd-levels-only'.
  7033. LEVEL is a current level, CHANGE is by how much the level should
  7034. be modified. Even if CHANGE is nil, LEVEL may be returned
  7035. modified because even level numbers will become the next higher
  7036. odd number. Returns values greater than 0."
  7037. (if org-odd-levels-only
  7038. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7039. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7040. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7041. (max 1 (+ level (or change 0)))))
  7042. (defun org-promote ()
  7043. "Promote the current heading higher up the tree."
  7044. (org-with-wide-buffer
  7045. (org-back-to-heading t)
  7046. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7047. after-change-functions))
  7048. (level (save-match-data (funcall outline-level)))
  7049. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7050. (diff (abs (- level (length up-head) -1))))
  7051. (cond
  7052. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7053. (replace-match "# " nil t))
  7054. ((= level 1)
  7055. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7056. (t (replace-match up-head nil t)))
  7057. (unless (= level 1)
  7058. (when org-auto-align-tags (org-align-tags))
  7059. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7060. (run-hooks 'org-after-promote-entry-hook))))
  7061. (defun org-demote ()
  7062. "Demote the current heading lower down the tree."
  7063. (org-with-wide-buffer
  7064. (org-back-to-heading t)
  7065. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7066. after-change-functions))
  7067. (level (save-match-data (funcall outline-level)))
  7068. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7069. (diff (abs (- level (length down-head) -1))))
  7070. (replace-match down-head nil t)
  7071. (when org-auto-align-tags (org-align-tags))
  7072. (when org-adapt-indentation (org-fixup-indentation diff))
  7073. (run-hooks 'org-after-demote-entry-hook))))
  7074. (defun org-cycle-level ()
  7075. "Cycle the level of an empty headline through possible states.
  7076. This goes first to child, then to parent, level, then up the hierarchy.
  7077. After top level, it switches back to sibling level."
  7078. (interactive)
  7079. (let ((org-adapt-indentation nil))
  7080. (when (org-point-at-end-of-empty-headline)
  7081. (setq this-command 'org-cycle-level) ; Only needed for caching
  7082. (let ((cur-level (org-current-level))
  7083. (prev-level (org-get-previous-line-level)))
  7084. (cond
  7085. ;; If first headline in file, promote to top-level.
  7086. ((= prev-level 0)
  7087. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7088. do (org-do-promote)))
  7089. ;; If same level as prev, demote one.
  7090. ((= prev-level cur-level)
  7091. (org-do-demote))
  7092. ;; If parent is top-level, promote to top level if not already.
  7093. ((= prev-level 1)
  7094. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7095. do (org-do-promote)))
  7096. ;; If top-level, return to prev-level.
  7097. ((= cur-level 1)
  7098. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7099. do (org-do-demote)))
  7100. ;; If less than prev-level, promote one.
  7101. ((< cur-level prev-level)
  7102. (org-do-promote))
  7103. ;; If deeper than prev-level, promote until higher than
  7104. ;; prev-level.
  7105. ((> cur-level prev-level)
  7106. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7107. do (org-do-promote))))
  7108. t))))
  7109. (defun org-map-tree (fun)
  7110. "Call FUN for every heading underneath the current one."
  7111. (org-back-to-heading t)
  7112. (let ((level (funcall outline-level)))
  7113. (save-excursion
  7114. (funcall fun)
  7115. (while (and (progn
  7116. (outline-next-heading)
  7117. (> (funcall outline-level) level))
  7118. (not (eobp)))
  7119. (funcall fun)))))
  7120. (defun org-map-region (fun beg end)
  7121. "Call FUN for every heading between BEG and END."
  7122. (let ((org-ignore-region t))
  7123. (save-excursion
  7124. (setq end (copy-marker end))
  7125. (goto-char beg)
  7126. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7127. (< (point) end))
  7128. (funcall fun))
  7129. (while (and (progn
  7130. (outline-next-heading)
  7131. (< (point) end))
  7132. (not (eobp)))
  7133. (funcall fun)))))
  7134. (defun org-fixup-indentation (diff)
  7135. "Change the indentation in the current entry by DIFF.
  7136. DIFF is an integer. Indentation is done according to the
  7137. following rules:
  7138. - Planning information and property drawers are always indented
  7139. according to the new level of the headline;
  7140. - Footnote definitions and their contents are ignored;
  7141. - Inlinetasks' boundaries are not shifted;
  7142. - Empty lines are ignored;
  7143. - Other lines' indentation are shifted by DIFF columns, unless
  7144. it would introduce a structural change in the document, in
  7145. which case no shifting is done at all.
  7146. Assume point is at a heading or an inlinetask beginning."
  7147. (org-with-wide-buffer
  7148. (narrow-to-region (line-beginning-position)
  7149. (save-excursion
  7150. (if (org-with-limited-levels (org-at-heading-p))
  7151. (org-with-limited-levels (outline-next-heading))
  7152. (org-inlinetask-goto-end))
  7153. (point)))
  7154. (forward-line)
  7155. ;; Indent properly planning info and property drawer.
  7156. (when (looking-at-p org-planning-line-re)
  7157. (org-indent-line)
  7158. (forward-line))
  7159. (when (looking-at org-property-drawer-re)
  7160. (goto-char (match-end 0))
  7161. (forward-line)
  7162. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7163. (catch 'no-shift
  7164. (when (zerop diff) (throw 'no-shift nil))
  7165. ;; If DIFF is negative, first check if a shift is possible at all
  7166. ;; (e.g., it doesn't break structure). This can only happen if
  7167. ;; some contents are not properly indented.
  7168. (let ((case-fold-search t))
  7169. (when (< diff 0)
  7170. (let ((diff (- diff))
  7171. (forbidden-re (concat org-outline-regexp
  7172. "\\|"
  7173. (substring org-footnote-definition-re 1))))
  7174. (save-excursion
  7175. (while (not (eobp))
  7176. (cond
  7177. ((looking-at-p "[ \t]*$") (forward-line))
  7178. ((and (looking-at-p org-footnote-definition-re)
  7179. (let ((e (org-element-at-point)))
  7180. (and (eq (org-element-type e) 'footnote-definition)
  7181. (goto-char (org-element-property :end e))))))
  7182. ((looking-at-p org-outline-regexp) (forward-line))
  7183. ;; Give up if shifting would move before column 0 or
  7184. ;; if it would introduce a headline or a footnote
  7185. ;; definition.
  7186. (t
  7187. (skip-chars-forward " \t")
  7188. (let ((ind (current-column)))
  7189. (when (or (< ind diff)
  7190. (and (= ind diff) (looking-at-p forbidden-re)))
  7191. (throw 'no-shift nil)))
  7192. ;; Ignore contents of example blocks and source
  7193. ;; blocks if their indentation is meant to be
  7194. ;; preserved. Jump to block's closing line.
  7195. (beginning-of-line)
  7196. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7197. (let ((e (org-element-at-point)))
  7198. (and (memq (org-element-type e)
  7199. '(example-block src-block))
  7200. (or org-src-preserve-indentation
  7201. (org-element-property :preserve-indent e))
  7202. (goto-char (org-element-property :end e))
  7203. (progn (skip-chars-backward " \r\t\n")
  7204. (beginning-of-line)
  7205. t))))
  7206. (forward-line))))))))
  7207. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7208. ;; by DIFF. Also skip contents of source or example blocks
  7209. ;; when indentation is meant to be preserved.
  7210. (while (not (eobp))
  7211. (cond
  7212. ((and (looking-at-p org-footnote-definition-re)
  7213. (let ((e (org-element-at-point)))
  7214. (and (eq (org-element-type e) 'footnote-definition)
  7215. (goto-char (org-element-property :end e))))))
  7216. ((looking-at-p org-outline-regexp) (forward-line))
  7217. ((looking-at-p "[ \t]*$") (forward-line))
  7218. (t
  7219. (indent-line-to (+ (current-indentation) diff))
  7220. (beginning-of-line)
  7221. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7222. (let ((e (org-element-at-point)))
  7223. (and (memq (org-element-type e)
  7224. '(example-block src-block))
  7225. (or org-src-preserve-indentation
  7226. (org-element-property :preserve-indent e))
  7227. (goto-char (org-element-property :end e))
  7228. (progn (skip-chars-backward " \r\t\n")
  7229. (beginning-of-line)
  7230. t))))
  7231. (forward-line)))))))))
  7232. (defun org-convert-to-odd-levels ()
  7233. "Convert an Org file with all levels allowed to one with odd levels.
  7234. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7235. level 5 etc."
  7236. (interactive)
  7237. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7238. (let ((outline-level 'org-outline-level)
  7239. (org-odd-levels-only nil) n)
  7240. (save-excursion
  7241. (goto-char (point-min))
  7242. (while (re-search-forward "^\\*\\*+ " nil t)
  7243. (setq n (- (length (match-string 0)) 2))
  7244. (while (>= (setq n (1- n)) 0)
  7245. (org-demote))
  7246. (end-of-line 1))))))
  7247. (defun org-convert-to-oddeven-levels ()
  7248. "Convert an Org file with only odd levels to one with odd/even levels.
  7249. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7250. file contains a section with an even level, conversion would
  7251. destroy the structure of the file. An error is signaled in this
  7252. case."
  7253. (interactive)
  7254. (goto-char (point-min))
  7255. ;; First check if there are no even levels
  7256. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7257. (org-show-set-visibility 'canonical)
  7258. (error "Not all levels are odd in this file. Conversion not possible"))
  7259. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7260. (let ((outline-regexp org-outline-regexp)
  7261. (outline-level 'org-outline-level)
  7262. (org-odd-levels-only nil) n)
  7263. (save-excursion
  7264. (goto-char (point-min))
  7265. (while (re-search-forward "^\\*\\*+ " nil t)
  7266. (setq n (/ (1- (length (match-string 0))) 2))
  7267. (while (>= (setq n (1- n)) 0)
  7268. (org-promote))
  7269. (end-of-line 1))))))
  7270. (defun org-tr-level (n)
  7271. "Make N odd if required."
  7272. (if org-odd-levels-only (1+ (/ n 2)) n))
  7273. ;;; Vertical tree motion, cutting and pasting of subtrees
  7274. (defun org-move-subtree-up (&optional arg)
  7275. "Move the current subtree up past ARG headlines of the same level."
  7276. (interactive "p")
  7277. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7278. (defun org-move-subtree-down (&optional arg)
  7279. "Move the current subtree down past ARG headlines of the same level."
  7280. (interactive "p")
  7281. (setq arg (prefix-numeric-value arg))
  7282. (org-preserve-local-variables
  7283. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7284. 'org-get-last-sibling))
  7285. (ins-point (make-marker))
  7286. (cnt (abs arg))
  7287. (col (current-column))
  7288. beg end txt folded)
  7289. ;; Select the tree
  7290. (org-back-to-heading)
  7291. (setq beg (point))
  7292. (save-match-data
  7293. (save-excursion (outline-end-of-heading)
  7294. (setq folded (org-invisible-p)))
  7295. (progn (org-end-of-subtree nil t)
  7296. (unless (eobp) (backward-char))))
  7297. (outline-next-heading)
  7298. (setq end (point))
  7299. (goto-char beg)
  7300. ;; Find insertion point, with error handling
  7301. (while (> cnt 0)
  7302. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7303. (goto-char beg)
  7304. (user-error "Cannot move past superior level or buffer limit"))
  7305. (setq cnt (1- cnt)))
  7306. (when (> arg 0)
  7307. ;; Moving forward - still need to move over subtree
  7308. (org-end-of-subtree t t)
  7309. (save-excursion
  7310. (org-back-over-empty-lines)
  7311. (or (bolp) (newline))))
  7312. (move-marker ins-point (point))
  7313. (setq txt (buffer-substring beg end))
  7314. (org-save-markers-in-region beg end)
  7315. (delete-region beg end)
  7316. (org-remove-empty-overlays-at beg)
  7317. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7318. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7319. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7320. (let ((bbb (point)))
  7321. (insert-before-markers txt)
  7322. (org-reinstall-markers-in-region bbb)
  7323. (move-marker ins-point bbb))
  7324. (or (bolp) (insert "\n"))
  7325. (goto-char ins-point)
  7326. (org-skip-whitespace)
  7327. (move-marker ins-point nil)
  7328. (if folded
  7329. (outline-hide-subtree)
  7330. (org-show-entry)
  7331. (org-show-children))
  7332. (org-clean-visibility-after-subtree-move)
  7333. ;; move back to the initial column we were at
  7334. (move-to-column col))))
  7335. (defvar org-subtree-clip ""
  7336. "Clipboard for cut and paste of subtrees.
  7337. This is actually only a copy of the kill, because we use the normal kill
  7338. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7339. (defvar org-subtree-clip-folded nil
  7340. "Was the last copied subtree folded?
  7341. This is used to fold the tree back after pasting.")
  7342. (defun org-cut-subtree (&optional n)
  7343. "Cut the current subtree into the clipboard.
  7344. With prefix arg N, cut this many sequential subtrees.
  7345. This is a short-hand for marking the subtree and then cutting it."
  7346. (interactive "p")
  7347. (org-copy-subtree n 'cut))
  7348. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7349. "Copy the current subtree into the clipboard.
  7350. With prefix arg N, copy this many sequential subtrees.
  7351. This is a short-hand for marking the subtree and then copying it.
  7352. If CUT is non-nil, actually cut the subtree.
  7353. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7354. of some markers in the region, even if CUT is non-nil. This is
  7355. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7356. (interactive "p")
  7357. (org-preserve-local-variables
  7358. (let (beg end folded (beg0 (point)))
  7359. (if (called-interactively-p 'any)
  7360. (org-back-to-heading nil) ; take what looks like a subtree
  7361. (org-back-to-heading t)) ; take what is really there
  7362. (setq beg (point))
  7363. (skip-chars-forward " \t\r\n")
  7364. (save-match-data
  7365. (if nosubtrees
  7366. (outline-next-heading)
  7367. (save-excursion (outline-end-of-heading)
  7368. (setq folded (org-invisible-p)))
  7369. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7370. (org-end-of-subtree t t)))
  7371. ;; Include the end of an inlinetask
  7372. (when (and (featurep 'org-inlinetask)
  7373. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7374. "END[ \t]*$")))
  7375. (end-of-line))
  7376. (setq end (point))
  7377. (goto-char beg0)
  7378. (when (> end beg)
  7379. (setq org-subtree-clip-folded folded)
  7380. (when (or cut force-store-markers)
  7381. (org-save-markers-in-region beg end))
  7382. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7383. (setq org-subtree-clip (current-kill 0))
  7384. (message "%s: Subtree(s) with %d characters"
  7385. (if cut "Cut" "Copied")
  7386. (length org-subtree-clip))))))
  7387. (defun org-paste-subtree (&optional level tree for-yank remove)
  7388. "Paste the clipboard as a subtree, with modification of headline level.
  7389. The entire subtree is promoted or demoted in order to match a new headline
  7390. level.
  7391. If the cursor is at the beginning of a headline, the same level as
  7392. that headline is used to paste the tree.
  7393. If not, the new level is derived from the *visible* headings
  7394. before and after the insertion point, and taken to be the inferior headline
  7395. level of the two. So if the previous visible heading is level 3 and the
  7396. next is level 4 (or vice versa), level 4 will be used for insertion.
  7397. This makes sure that the subtree remains an independent subtree and does
  7398. not swallow low level entries.
  7399. You can also force a different level, either by using a numeric prefix
  7400. argument, or by inserting the heading marker by hand. For example, if the
  7401. cursor is after \"*****\", then the tree will be shifted to level 5.
  7402. If optional TREE is given, use this text instead of the kill ring.
  7403. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7404. move back over whitespace before inserting, and move point to the end of
  7405. the inserted text when done.
  7406. When REMOVE is non-nil, remove the subtree from the clipboard."
  7407. (interactive "P")
  7408. (setq tree (or tree (and kill-ring (current-kill 0))))
  7409. (unless (org-kill-is-subtree-p tree)
  7410. (user-error
  7411. (substitute-command-keys
  7412. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7413. (org-with-limited-levels
  7414. (let* ((visp (not (org-invisible-p)))
  7415. (txt tree)
  7416. (old-level (if (string-match org-outline-regexp-bol txt)
  7417. (- (match-end 0) (match-beginning 0) 1)
  7418. -1))
  7419. (force-level
  7420. (cond
  7421. (level (prefix-numeric-value level))
  7422. ;; When point is right after the stars in an otherwise
  7423. ;; empty headline, use stars as the forced level.
  7424. ((and (looking-at-p "[ \t]*$")
  7425. (string-match-p "^\\*+ *"
  7426. (buffer-substring (line-beginning-position)
  7427. (point))))
  7428. (org-outline-level))
  7429. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7430. (previous-level
  7431. (save-excursion
  7432. (org-previous-visible-heading 1)
  7433. (if (org-at-heading-p) (org-outline-level) 1)))
  7434. (next-level
  7435. (save-excursion
  7436. (if (org-at-heading-p) (org-outline-level)
  7437. (org-next-visible-heading 1)
  7438. (if (org-at-heading-p) (org-outline-level) 1))))
  7439. (new-level (or force-level (max previous-level next-level)))
  7440. (shift (if (or (= old-level -1)
  7441. (= new-level -1)
  7442. (= old-level new-level))
  7443. 0
  7444. (- new-level old-level)))
  7445. (delta (if (> shift 0) -1 1))
  7446. (func (if (> shift 0) #'org-demote #'org-promote))
  7447. (org-odd-levels-only nil)
  7448. beg end newend)
  7449. ;; Remove the forced level indicator.
  7450. (when (and force-level (not level))
  7451. (delete-region (line-beginning-position) (point)))
  7452. ;; Paste before the next visible heading or at end of buffer,
  7453. ;; unless point is at the beginning of a headline.
  7454. (unless (and (bolp) (org-at-heading-p))
  7455. (org-next-visible-heading 1)
  7456. (unless (bolp) (insert "\n")))
  7457. (setq beg (point))
  7458. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7459. (insert-before-markers txt)
  7460. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7461. (setq newend (point))
  7462. (org-reinstall-markers-in-region beg)
  7463. (setq end (point))
  7464. (goto-char beg)
  7465. (skip-chars-forward " \t\n\r")
  7466. (setq beg (point))
  7467. (when (and (org-invisible-p) visp)
  7468. (save-excursion (outline-show-heading)))
  7469. ;; Shift if necessary.
  7470. (unless (= shift 0)
  7471. (save-restriction
  7472. (narrow-to-region beg end)
  7473. (while (not (= shift 0))
  7474. (org-map-region func (point-min) (point-max))
  7475. (setq shift (+ delta shift)))
  7476. (goto-char (point-min))
  7477. (setq newend (point-max))))
  7478. (when (or for-yank (called-interactively-p 'interactive))
  7479. (message "Clipboard pasted as level %d subtree" new-level))
  7480. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7481. kill-ring
  7482. (equal org-subtree-clip (current-kill 0))
  7483. org-subtree-clip-folded)
  7484. ;; The tree was folded before it was killed/copied
  7485. (outline-hide-subtree))
  7486. (when for-yank (goto-char newend))
  7487. (when remove (pop kill-ring)))))
  7488. (defun org-kill-is-subtree-p (&optional txt)
  7489. "Check if the current kill is an outline subtree, or a set of trees.
  7490. Returns nil if kill does not start with a headline, or if the first
  7491. headline level is not the largest headline level in the tree.
  7492. So this will actually accept several entries of equal levels as well,
  7493. which is OK for `org-paste-subtree'.
  7494. If optional TXT is given, check this string instead of the current kill."
  7495. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7496. (re (org-get-limited-outline-regexp))
  7497. (^re (concat "^" re))
  7498. (start-level (and kill
  7499. (string-match
  7500. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7501. kill)
  7502. (- (match-end 2) (match-beginning 2) 1)))
  7503. (start (1+ (or (match-beginning 2) -1))))
  7504. (if (not start-level)
  7505. (progn
  7506. nil) ;; does not even start with a heading
  7507. (catch 'exit
  7508. (while (setq start (string-match ^re kill (1+ start)))
  7509. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7510. (throw 'exit nil)))
  7511. t))))
  7512. (defvar org-markers-to-move nil
  7513. "Markers that should be moved with a cut-and-paste operation.
  7514. Those markers are stored together with their positions relative to
  7515. the start of the region.")
  7516. (defun org-save-markers-in-region (beg end)
  7517. "Check markers in region.
  7518. If these markers are between BEG and END, record their position relative
  7519. to BEG, so that after moving the block of text, we can put the markers back
  7520. into place.
  7521. This function gets called just before an entry or tree gets cut from the
  7522. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7523. called immediately, to move the markers with the entries."
  7524. (setq org-markers-to-move nil)
  7525. (when (featurep 'org-clock)
  7526. (org-clock-save-markers-for-cut-and-paste beg end))
  7527. (when (featurep 'org-agenda)
  7528. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7529. (defun org-check-and-save-marker (marker beg end)
  7530. "Check if MARKER is between BEG and END.
  7531. If yes, remember the marker and the distance to BEG."
  7532. (when (and (marker-buffer marker)
  7533. (equal (marker-buffer marker) (current-buffer))
  7534. (>= marker beg) (< marker end))
  7535. (push (cons marker (- marker beg)) org-markers-to-move)))
  7536. (defun org-reinstall-markers-in-region (beg)
  7537. "Move all remembered markers to their position relative to BEG."
  7538. (dolist (x org-markers-to-move)
  7539. (move-marker (car x) (+ beg (cdr x))))
  7540. (setq org-markers-to-move nil))
  7541. (defun org-narrow-to-subtree ()
  7542. "Narrow buffer to the current subtree."
  7543. (interactive)
  7544. (save-excursion
  7545. (save-match-data
  7546. (org-with-limited-levels
  7547. (narrow-to-region
  7548. (progn (org-back-to-heading t) (point))
  7549. (progn (org-end-of-subtree t t)
  7550. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7551. (point)))))))
  7552. (defun org-toggle-narrow-to-subtree ()
  7553. "Narrow to the subtree at point or widen a narrowed buffer."
  7554. (interactive)
  7555. (if (buffer-narrowed-p)
  7556. (widen)
  7557. (org-narrow-to-subtree)))
  7558. (defun org-narrow-to-block ()
  7559. "Narrow buffer to the current block."
  7560. (interactive)
  7561. (let* ((case-fold-search t)
  7562. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7563. "^[ \t]*#\\+end_.*")))
  7564. (if blockp
  7565. (narrow-to-region (car blockp) (cdr blockp))
  7566. (user-error "Not in a block"))))
  7567. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7568. "Clone the task (subtree) at point N times.
  7569. The clones will be inserted as siblings.
  7570. In interactive use, the user will be prompted for the number of
  7571. clones to be produced. If the entry has a timestamp, the user
  7572. will also be prompted for a time shift, which may be a repeater
  7573. as used in time stamps, for example `+3d'. To disable this,
  7574. you can call the function with a universal prefix argument.
  7575. When a valid repeater is given and the entry contains any time
  7576. stamps, the clones will become a sequence in time, with time
  7577. stamps in the subtree shifted for each clone produced. If SHIFT
  7578. is nil or the empty string, time stamps will be left alone. The
  7579. ID property of the original subtree is removed.
  7580. In each clone, all the CLOCK entries will be removed. This
  7581. prevents Org from considering that the clocked times overlap.
  7582. If the original subtree did contain time stamps with a repeater,
  7583. the following will happen:
  7584. - the repeater will be removed in each clone
  7585. - an additional clone will be produced, with the current, unshifted
  7586. date(s) in the entry.
  7587. - the original entry will be placed *after* all the clones, with
  7588. repeater intact.
  7589. - the start days in the repeater in the original entry will be shifted
  7590. to past the last clone.
  7591. In this way you can spell out a number of instances of a repeating task,
  7592. and still retain the repeater to cover future instances of the task.
  7593. As described above, N+1 clones are produced when the original
  7594. subtree has a repeater. Setting N to 0, then, can be used to
  7595. remove the repeater from a subtree and create a shifted clone
  7596. with the original repeater."
  7597. (interactive "nNumber of clones to produce: ")
  7598. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7599. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7600. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7601. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7602. (shift
  7603. (or shift
  7604. (if (and (not (equal current-prefix-arg '(4)))
  7605. (save-excursion
  7606. (goto-char beg)
  7607. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7608. (read-from-minibuffer
  7609. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7610. ""))) ;No time shift
  7611. (doshift
  7612. (and (org-string-nw-p shift)
  7613. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7614. shift)
  7615. (user-error "Invalid shift specification %s" shift)))))
  7616. (goto-char end-of-tree)
  7617. (unless (bolp) (insert "\n"))
  7618. (let* ((end (point))
  7619. (template (buffer-substring beg end))
  7620. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7621. (shift-what (pcase (and doshift (match-string 2 shift))
  7622. (`nil nil)
  7623. ("d" 'day)
  7624. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7625. ("m" 'month)
  7626. ("y" 'year)
  7627. (_ (error "Unsupported time unit"))))
  7628. (nmin 1)
  7629. (nmax n)
  7630. (n-no-remove -1)
  7631. (idprop (org-entry-get nil "ID")))
  7632. (when (and doshift
  7633. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7634. template))
  7635. (delete-region beg end)
  7636. (setq end beg)
  7637. (setq nmin 0)
  7638. (setq nmax (1+ nmax))
  7639. (setq n-no-remove nmax))
  7640. (goto-char end)
  7641. (cl-loop for n from nmin to nmax do
  7642. (insert
  7643. ;; Prepare clone.
  7644. (with-temp-buffer
  7645. (insert template)
  7646. (org-mode)
  7647. (goto-char (point-min))
  7648. (org-show-subtree)
  7649. (and idprop (if org-clone-delete-id
  7650. (org-entry-delete nil "ID")
  7651. (org-id-get-create t)))
  7652. (unless (= n 0)
  7653. (while (re-search-forward org-clock-line-re nil t)
  7654. (delete-region (line-beginning-position)
  7655. (line-beginning-position 2)))
  7656. (goto-char (point-min))
  7657. (while (re-search-forward org-drawer-regexp nil t)
  7658. (org-remove-empty-drawer-at (point))))
  7659. (goto-char (point-min))
  7660. (when doshift
  7661. (while (re-search-forward org-ts-regexp-both nil t)
  7662. (org-timestamp-change (* n shift-n) shift-what))
  7663. (unless (= n n-no-remove)
  7664. (goto-char (point-min))
  7665. (while (re-search-forward org-ts-regexp nil t)
  7666. (save-excursion
  7667. (goto-char (match-beginning 0))
  7668. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7669. (delete-region (match-beginning 1) (match-end 1)))))))
  7670. (buffer-string)))))
  7671. (goto-char beg)))
  7672. ;;; Outline Sorting
  7673. (defun org-sort (&optional with-case)
  7674. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7675. Optional argument WITH-CASE means sort case-sensitively."
  7676. (interactive "P")
  7677. (org-call-with-arg
  7678. (cond ((org-at-table-p) #'org-table-sort-lines)
  7679. ((org-at-item-p) #'org-sort-list)
  7680. (t #'org-sort-entries))
  7681. with-case))
  7682. (defun org-sort-remove-invisible (s)
  7683. "Remove invisible part of links and emphasis markers from string S."
  7684. (remove-text-properties 0 (length s) org-rm-props s)
  7685. (replace-regexp-in-string
  7686. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7687. (replace-regexp-in-string
  7688. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7689. (org-link-display-format s)
  7690. t t) t t))
  7691. (defvar org-priority-regexp) ; defined later in the file
  7692. (defvar org-after-sorting-entries-or-items-hook nil
  7693. "Hook that is run after a bunch of entries or items have been sorted.
  7694. When children are sorted, the cursor is in the parent line when this
  7695. hook gets called. When a region or a plain list is sorted, the cursor
  7696. will be in the first entry of the sorted region/list.")
  7697. (defun org-sort-entries
  7698. (&optional with-case sorting-type getkey-func compare-func property
  7699. interactive?)
  7700. "Sort entries on a certain level of an outline tree.
  7701. If there is an active region, the entries in the region are sorted.
  7702. Else, if the cursor is before the first entry, sort the top-level items.
  7703. Else, the children of the entry at point are sorted.
  7704. Sorting can be alphabetically, numerically, by date/time as given by
  7705. a time stamp, by a property, by priority order, or by a custom function.
  7706. The command prompts for the sorting type unless it has been given to the
  7707. function through the SORTING-TYPE argument, which needs to be a character,
  7708. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7709. the precise meaning of each character:
  7710. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7711. c By creation time, which is assumed to be the first inactive time stamp
  7712. at the beginning of a line.
  7713. d By deadline date/time.
  7714. k By clocking time.
  7715. n Numerically, by converting the beginning of the entry/item to a number.
  7716. o By order of TODO keywords.
  7717. p By priority according to the cookie.
  7718. r By the value of a property.
  7719. s By scheduled date/time.
  7720. t By date/time, either the first active time stamp in the entry, or, if
  7721. none exist, by the first inactive one.
  7722. Capital letters will reverse the sort order.
  7723. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7724. called with point at the beginning of the record. It must return a
  7725. value that is compatible with COMPARE-FUNC, the function used to
  7726. compare entries.
  7727. Comparing entries ignores case by default. However, with an optional argument
  7728. WITH-CASE, the sorting considers case as well.
  7729. Sorting is done against the visible part of the headlines, it ignores hidden
  7730. links.
  7731. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7732. A non-nil value for INTERACTIVE? is used to signal that this
  7733. function is being called interactively."
  7734. (interactive (list current-prefix-arg nil nil nil nil t))
  7735. (let ((case-func (if with-case 'identity 'downcase))
  7736. start beg end stars re re2
  7737. txt what tmp)
  7738. ;; Find beginning and end of region to sort
  7739. (cond
  7740. ((org-region-active-p)
  7741. ;; we will sort the region
  7742. (setq end (region-end)
  7743. what "region")
  7744. (goto-char (region-beginning))
  7745. (unless (org-at-heading-p) (outline-next-heading))
  7746. (setq start (point)))
  7747. ((or (org-at-heading-p)
  7748. (ignore-errors (progn (org-back-to-heading) t)))
  7749. ;; we will sort the children of the current headline
  7750. (org-back-to-heading)
  7751. (setq start (point)
  7752. end (progn (org-end-of-subtree t t)
  7753. (or (bolp) (insert "\n"))
  7754. (when (>= (org-back-over-empty-lines) 1)
  7755. (forward-line 1))
  7756. (point))
  7757. what "children")
  7758. (goto-char start)
  7759. (outline-show-subtree)
  7760. (outline-next-heading))
  7761. (t
  7762. ;; we will sort the top-level entries in this file
  7763. (goto-char (point-min))
  7764. (or (org-at-heading-p) (outline-next-heading))
  7765. (setq start (point))
  7766. (goto-char (point-max))
  7767. (beginning-of-line 1)
  7768. (when (looking-at ".*?\\S-")
  7769. ;; File ends in a non-white line
  7770. (end-of-line 1)
  7771. (insert "\n"))
  7772. (setq end (point-max))
  7773. (setq what "top-level")
  7774. (goto-char start)
  7775. (org-show-all '(headings blocks))))
  7776. (setq beg (point))
  7777. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7778. (looking-at "\\(\\*+\\)")
  7779. (setq stars (match-string 1)
  7780. re (concat "^" (regexp-quote stars) " +")
  7781. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7782. txt (buffer-substring beg end))
  7783. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7784. (when (and (not (equal stars "*")) (string-match re2 txt))
  7785. (user-error "Region to sort contains a level above the first entry"))
  7786. (unless sorting-type
  7787. (message
  7788. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7789. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7790. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7791. what)
  7792. (setq sorting-type (read-char-exclusive)))
  7793. (unless getkey-func
  7794. (and (= (downcase sorting-type) ?f)
  7795. (setq getkey-func
  7796. (or (and interactive?
  7797. (org-read-function
  7798. "Function for extracting keys: "))
  7799. (error "Missing key extractor")))))
  7800. (and (= (downcase sorting-type) ?r)
  7801. (not property)
  7802. (setq property
  7803. (completing-read "Property: "
  7804. (mapcar #'list (org-buffer-property-keys t))
  7805. nil t)))
  7806. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7807. (message "Sorting entries...")
  7808. (save-restriction
  7809. (narrow-to-region start end)
  7810. (let ((restore-clock?
  7811. ;; The clock marker is lost when using `sort-subr'; mark
  7812. ;; the clock with temporary `:org-clock-marker-backup'
  7813. ;; text property.
  7814. (when (and (eq (org-clock-is-active) (current-buffer))
  7815. (<= start (marker-position org-clock-marker))
  7816. (>= end (marker-position org-clock-marker)))
  7817. (with-silent-modifications
  7818. (put-text-property (1- org-clock-marker) org-clock-marker
  7819. :org-clock-marker-backup t))
  7820. t))
  7821. (dcst (downcase sorting-type))
  7822. (case-fold-search nil)
  7823. (now (current-time)))
  7824. (org-preserve-local-variables
  7825. (sort-subr
  7826. (/= dcst sorting-type)
  7827. ;; This function moves to the beginning character of the
  7828. ;; "record" to be sorted.
  7829. (lambda nil
  7830. (if (re-search-forward re nil t)
  7831. (goto-char (match-beginning 0))
  7832. (goto-char (point-max))))
  7833. ;; This function moves to the last character of the "record" being
  7834. ;; sorted.
  7835. (lambda nil
  7836. (save-match-data
  7837. (condition-case nil
  7838. (outline-forward-same-level 1)
  7839. (error
  7840. (goto-char (point-max))))))
  7841. ;; This function returns the value that gets sorted against.
  7842. (lambda ()
  7843. (cond
  7844. ((= dcst ?n)
  7845. (string-to-number
  7846. (org-sort-remove-invisible (org-get-heading t t t t))))
  7847. ((= dcst ?a)
  7848. (funcall case-func
  7849. (org-sort-remove-invisible (org-get-heading t t t t))))
  7850. ((= dcst ?k)
  7851. (or (get-text-property (point) :org-clock-minutes) 0))
  7852. ((= dcst ?t)
  7853. (let ((end (save-excursion (outline-next-heading) (point))))
  7854. (if (or (re-search-forward org-ts-regexp end t)
  7855. (re-search-forward org-ts-regexp-both end t))
  7856. (org-time-string-to-seconds (match-string 0))
  7857. (float-time now))))
  7858. ((= dcst ?c)
  7859. (let ((end (save-excursion (outline-next-heading) (point))))
  7860. (if (re-search-forward
  7861. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7862. end t)
  7863. (org-time-string-to-seconds (match-string 0))
  7864. (float-time now))))
  7865. ((= dcst ?s)
  7866. (let ((end (save-excursion (outline-next-heading) (point))))
  7867. (if (re-search-forward org-scheduled-time-regexp end t)
  7868. (org-time-string-to-seconds (match-string 1))
  7869. (float-time now))))
  7870. ((= dcst ?d)
  7871. (let ((end (save-excursion (outline-next-heading) (point))))
  7872. (if (re-search-forward org-deadline-time-regexp end t)
  7873. (org-time-string-to-seconds (match-string 1))
  7874. (float-time now))))
  7875. ((= dcst ?p)
  7876. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7877. (string-to-char (match-string 2))
  7878. org-default-priority))
  7879. ((= dcst ?r)
  7880. (or (org-entry-get nil property) ""))
  7881. ((= dcst ?o)
  7882. (when (looking-at org-complex-heading-regexp)
  7883. (let* ((m (match-string 2))
  7884. (s (if (member m org-done-keywords) '- '+)))
  7885. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7886. ((= dcst ?f)
  7887. (if getkey-func
  7888. (progn
  7889. (setq tmp (funcall getkey-func))
  7890. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7891. tmp)
  7892. (error "Invalid key function `%s'" getkey-func)))
  7893. (t (error "Invalid sorting type `%c'" sorting-type))))
  7894. nil
  7895. (cond
  7896. ((= dcst ?a) 'org-string-collate-lessp)
  7897. ((= dcst ?f)
  7898. (or compare-func
  7899. (and interactive?
  7900. (org-read-function
  7901. (concat "Function for comparing keys "
  7902. "(empty for default `sort-subr' predicate): ")
  7903. 'allow-empty))))
  7904. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7905. (when restore-clock?
  7906. (move-marker org-clock-marker
  7907. (1+ (next-single-property-change
  7908. start :org-clock-marker-backup)))
  7909. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7910. '(:org-clock-marker-backup t)))))
  7911. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7912. (message "Sorting entries...done")))
  7913. (defun org-contextualize-keys (alist contexts)
  7914. "Return valid elements in ALIST depending on CONTEXTS.
  7915. `org-agenda-custom-commands' or `org-capture-templates' are the
  7916. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7917. or `org-capture-templates-contexts' are the associated contexts
  7918. definitions."
  7919. (let ((contexts
  7920. ;; normalize contexts
  7921. (mapcar
  7922. (lambda(c) (cond ((listp (cadr c))
  7923. (list (car c) (car c) (nth 1 c)))
  7924. ((string= "" (cadr c))
  7925. (list (car c) (car c) (nth 2 c)))
  7926. (t c)))
  7927. contexts))
  7928. (a alist) r s)
  7929. ;; loop over all commands or templates
  7930. (dolist (c a)
  7931. (let (vrules repl)
  7932. (cond
  7933. ((not (assoc (car c) contexts))
  7934. (push c r))
  7935. ((and (assoc (car c) contexts)
  7936. (setq vrules (org-contextualize-validate-key
  7937. (car c) contexts)))
  7938. (mapc (lambda (vr)
  7939. (unless (equal (car vr) (cadr vr))
  7940. (setq repl vr)))
  7941. vrules)
  7942. (if (not repl) (push c r)
  7943. (push (cadr repl) s)
  7944. (push
  7945. (cons (car c)
  7946. (cdr (or (assoc (cadr repl) alist)
  7947. (error "Undefined key `%s' as contextual replacement for `%s'"
  7948. (cadr repl) (car c)))))
  7949. r))))))
  7950. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7951. (delq
  7952. nil
  7953. (delete-dups
  7954. (mapcar (lambda (x)
  7955. (let ((tpl (car x)))
  7956. (unless (delq
  7957. nil
  7958. (mapcar (lambda (y)
  7959. (equal y tpl))
  7960. s))
  7961. x)))
  7962. (reverse r))))))
  7963. (defun org-contextualize-validate-key (key contexts)
  7964. "Check CONTEXTS for agenda or capture KEY."
  7965. (let (res)
  7966. (dolist (r contexts)
  7967. (dolist (rr (car (last r)))
  7968. (when
  7969. (and (equal key (car r))
  7970. (if (functionp rr) (funcall rr)
  7971. (or (and (eq (car rr) 'in-file)
  7972. (buffer-file-name)
  7973. (string-match (cdr rr) (buffer-file-name)))
  7974. (and (eq (car rr) 'in-mode)
  7975. (string-match (cdr rr) (symbol-name major-mode)))
  7976. (and (eq (car rr) 'in-buffer)
  7977. (string-match (cdr rr) (buffer-name)))
  7978. (when (and (eq (car rr) 'not-in-file)
  7979. (buffer-file-name))
  7980. (not (string-match (cdr rr) (buffer-file-name))))
  7981. (when (eq (car rr) 'not-in-mode)
  7982. (not (string-match (cdr rr) (symbol-name major-mode))))
  7983. (when (eq (car rr) 'not-in-buffer)
  7984. (not (string-match (cdr rr) (buffer-name)))))))
  7985. (push r res))))
  7986. (delete-dups (delq nil res))))
  7987. ;; Defined to provide a value for defcustom, since there is no
  7988. ;; string-collate-greaterp in Emacs.
  7989. (defun org-string-collate-greaterp (s1 s2)
  7990. "Return non-nil if S1 is greater than S2 in collation order."
  7991. (not (org-string-collate-lessp s1 s2)))
  7992. ;;;###autoload
  7993. (defun org-run-like-in-org-mode (cmd)
  7994. "Run a command, pretending that the current buffer is in Org mode.
  7995. This will temporarily bind local variables that are typically bound in
  7996. Org mode to the values they have in Org mode, and then interactively
  7997. call CMD."
  7998. (org-load-modules-maybe)
  7999. (let (binds)
  8000. (dolist (var (org-get-local-variables))
  8001. (when (or (not (boundp (car var)))
  8002. (eq (symbol-value (car var))
  8003. (default-value (car var))))
  8004. (push (list (car var) `(quote ,(cadr var))) binds)))
  8005. (eval `(let ,binds
  8006. (call-interactively (quote ,cmd))))))
  8007. (defun org-get-category (&optional pos force-refresh)
  8008. "Get the category applying to position POS."
  8009. (save-match-data
  8010. (when force-refresh (org-refresh-category-properties))
  8011. (let ((pos (or pos (point))))
  8012. (or (get-text-property pos 'org-category)
  8013. (progn (org-refresh-category-properties)
  8014. (get-text-property pos 'org-category))))))
  8015. ;;; Refresh properties
  8016. (defun org-refresh-properties (dprop tprop)
  8017. "Refresh buffer text properties.
  8018. DPROP is the drawer property and TPROP is either the
  8019. corresponding text property to set, or an alist with each element
  8020. being a text property (as a symbol) and a function to apply to
  8021. the value of the drawer property."
  8022. (let* ((case-fold-search t)
  8023. (inhibit-read-only t)
  8024. (inherit? (org-property-inherit-p dprop))
  8025. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8026. (global (and inherit? (org--property-global-value dprop nil))))
  8027. (with-silent-modifications
  8028. (org-with-point-at 1
  8029. ;; Set global values (e.g., values defined through
  8030. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8031. (when global (put-text-property (point-min) (point-max) tprop global))
  8032. ;; Set local values.
  8033. (while (re-search-forward property-re nil t)
  8034. (when (org-at-property-p)
  8035. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8036. (outline-next-heading))))))
  8037. (defun org-refresh-property (tprop p &optional inherit)
  8038. "Refresh the buffer text property TPROP from the drawer property P.
  8039. The refresh happens only for the current headline, or the whole
  8040. sub-tree if optional argument INHERIT is non-nil."
  8041. (unless (org-before-first-heading-p)
  8042. (save-excursion
  8043. (org-back-to-heading t)
  8044. (let ((start (point))
  8045. (end (save-excursion
  8046. (if inherit (org-end-of-subtree t t)
  8047. (or (outline-next-heading) (point-max))))))
  8048. (if (symbolp tprop)
  8049. ;; TPROP is a text property symbol.
  8050. (put-text-property start end tprop p)
  8051. ;; TPROP is an alist with (property . function) elements.
  8052. (pcase-dolist (`(,prop . ,f) tprop)
  8053. (put-text-property start end prop (funcall f p))))))))
  8054. (defun org-refresh-category-properties ()
  8055. "Refresh category text properties in the buffer."
  8056. (let ((case-fold-search t)
  8057. (inhibit-read-only t)
  8058. (default-category
  8059. (cond ((null org-category)
  8060. (if buffer-file-name
  8061. (file-name-sans-extension
  8062. (file-name-nondirectory buffer-file-name))
  8063. "???"))
  8064. ((symbolp org-category) (symbol-name org-category))
  8065. (t org-category))))
  8066. (with-silent-modifications
  8067. (org-with-wide-buffer
  8068. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8069. ;; This is the default category for the buffer. If none is
  8070. ;; found, fall-back to `org-category' or buffer file name.
  8071. (put-text-property
  8072. (point-min) (point-max)
  8073. 'org-category
  8074. (catch 'buffer-category
  8075. (goto-char (point-max))
  8076. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8077. (let ((element (org-element-at-point)))
  8078. (when (eq (org-element-type element) 'keyword)
  8079. (throw 'buffer-category
  8080. (org-element-property :value element)))))
  8081. default-category))
  8082. ;; Set sub-tree specific categories.
  8083. (goto-char (point-min))
  8084. (let ((regexp (org-re-property "CATEGORY")))
  8085. (while (re-search-forward regexp nil t)
  8086. (let ((value (match-string-no-properties 3)))
  8087. (when (org-at-property-p)
  8088. (put-text-property
  8089. (save-excursion (org-back-to-heading t) (point))
  8090. (save-excursion (org-end-of-subtree t t) (point))
  8091. 'org-category
  8092. value)))))))))
  8093. (defun org-refresh-stats-properties ()
  8094. "Refresh stats text properties in the buffer."
  8095. (with-silent-modifications
  8096. (org-with-point-at 1
  8097. (let ((regexp (concat org-outline-regexp-bol
  8098. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8099. (while (re-search-forward regexp nil t)
  8100. (let* ((numerator (string-to-number (match-string 1)))
  8101. (denominator (and (match-end 2)
  8102. (string-to-number (match-string 2))))
  8103. (stats (cond ((not denominator) numerator) ;percent
  8104. ((= denominator 0) 0)
  8105. (t (/ (* numerator 100) denominator)))))
  8106. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8107. 'org-stats stats)))))))
  8108. (defun org-refresh-effort-properties ()
  8109. "Refresh effort properties"
  8110. (org-refresh-properties
  8111. org-effort-property
  8112. '((effort . identity)
  8113. (effort-minutes . org-duration-to-minutes))))
  8114. ;;;; Link Stuff
  8115. ;;; Link abbreviations
  8116. (defun org-link-expand-abbrev (link)
  8117. "Apply replacements as defined in `org-link-abbrev-alist'."
  8118. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8119. (let* ((key (match-string 1 link))
  8120. (as (or (assoc key org-link-abbrev-alist-local)
  8121. (assoc key org-link-abbrev-alist)))
  8122. (tag (and (match-end 2) (match-string 3 link)))
  8123. rpl)
  8124. (if (not as)
  8125. link
  8126. (setq rpl (cdr as))
  8127. (cond
  8128. ((symbolp rpl) (funcall rpl tag))
  8129. ((string-match "%(\\([^)]+\\))" rpl)
  8130. (replace-match
  8131. (save-match-data
  8132. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8133. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8134. ((string-match "%h" rpl)
  8135. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8136. (t (concat rpl tag)))))
  8137. link))
  8138. ;;; Storing and inserting links
  8139. (defvar org-insert-link-history nil
  8140. "Minibuffer history for links inserted with `org-insert-link'.")
  8141. (defvar org-stored-links nil
  8142. "Contains the links stored with `org-store-link'.")
  8143. (defvar org-store-link-plist nil
  8144. "Plist with info about the most recently link created with `org-store-link'.")
  8145. (defun org-store-link-functions ()
  8146. "Return a list of functions that are called to create and store a link.
  8147. The functions defined in the :store property of
  8148. `org-link-parameters'.
  8149. Each function will be called in turn until one returns a non-nil
  8150. value. Each function should check if it is responsible for
  8151. creating this link (for example by looking at the major mode).
  8152. If not, it must exit and return nil. If yes, it should return
  8153. a non-nil value after calling `org-store-link-props' with a list
  8154. of properties and values. Special properties are:
  8155. :type The link prefix, like \"http\". This must be given.
  8156. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8157. This is obligatory as well.
  8158. :description Optional default description for the second pair
  8159. of brackets in an Org mode link. The user can still change
  8160. this when inserting this link into an Org mode buffer.
  8161. In addition to these, any additional properties can be specified
  8162. and then used in capture templates."
  8163. (cl-loop for link in org-link-parameters
  8164. with store-func
  8165. do (setq store-func (org-link-get-parameter (car link) :store))
  8166. if store-func
  8167. collect store-func))
  8168. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8169. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8170. ;;;###autoload
  8171. (defun org-store-link (arg &optional interactive?)
  8172. "Store a link to the current location.
  8173. \\<org-mode-map>
  8174. This link is added to `org-stored-links' and can later be inserted
  8175. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8176. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8177. A single
  8178. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8179. `org-gnus-prefer-web-links' for links to Usenet articles.
  8180. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8181. skipping storing functions that are not
  8182. part of Org core.
  8183. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8184. prefix ARG forces storing a link for each line in the
  8185. active region.
  8186. Assume the function is called interactively if INTERACTIVE? is
  8187. non-nil."
  8188. (interactive "P\np")
  8189. (org-load-modules-maybe)
  8190. (if (and (equal arg '(64)) (org-region-active-p))
  8191. (save-excursion
  8192. (let ((end (region-end)))
  8193. (goto-char (region-beginning))
  8194. (set-mark (point))
  8195. (while (< (point-at-eol) end)
  8196. (move-end-of-line 1) (activate-mark)
  8197. (let (current-prefix-arg)
  8198. (call-interactively 'org-store-link))
  8199. (move-beginning-of-line 2)
  8200. (set-mark (point)))))
  8201. (setq org-store-link-plist nil)
  8202. (let (link cpltxt desc description search txt custom-id agenda-link)
  8203. (cond
  8204. ;; Store a link using an external link type, if any function is
  8205. ;; available. If more than one can generate a link from current
  8206. ;; location, ask which one to use.
  8207. ((and (not (equal arg '(16)))
  8208. (let ((results-alist nil))
  8209. (dolist (f (org-store-link-functions))
  8210. (when (funcall f)
  8211. ;; XXX: return value is not link's plist, so we
  8212. ;; store the new value before it is modified. It
  8213. ;; would be cleaner to ask store link functions to
  8214. ;; return the plist instead.
  8215. (push (cons f (copy-sequence org-store-link-plist))
  8216. results-alist)))
  8217. (pcase results-alist
  8218. (`nil nil)
  8219. (`((,_ . ,_)) t) ;single choice: nothing to do
  8220. (`((,name . ,_) . ,_)
  8221. ;; Reinstate link plist associated to the chosen
  8222. ;; function.
  8223. (apply #'org-store-link-props
  8224. (cdr (assoc-string
  8225. (completing-read
  8226. "Which function for creating the link? "
  8227. (mapcar #'car results-alist)
  8228. nil t (symbol-name name))
  8229. results-alist)))
  8230. t))))
  8231. (setq link (plist-get org-store-link-plist :link))
  8232. (setq desc (or (plist-get org-store-link-plist :description)
  8233. link)))
  8234. ;; Store a link from a source code buffer.
  8235. ((org-src-edit-buffer-p)
  8236. (let ((coderef-format (org-src-coderef-format)))
  8237. (cond ((org-match-line (org-src-coderef-regexp coderef-format))
  8238. (setq link (format "(%s)" (match-string-no-properties 3))))
  8239. (interactive?
  8240. (let ((label (read-string "Code line label: ")))
  8241. (end-of-line)
  8242. (setq link (format coderef-format label))
  8243. (let ((gc (- 79 (length link))))
  8244. (if (< (current-column) gc)
  8245. (org-move-to-column gc t)
  8246. (insert " ")))
  8247. (insert link)
  8248. (setq link (concat "(" label ")"))
  8249. (setq desc nil)))
  8250. (t (setq link nil)))))
  8251. ;; We are in the agenda, link to referenced location
  8252. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8253. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8254. (get-text-property (point) 'org-marker))))
  8255. (when m
  8256. (org-with-point-at m
  8257. (setq agenda-link (org-store-link nil interactive?))))))
  8258. ((eq major-mode 'calendar-mode)
  8259. (let ((cd (calendar-cursor-to-date)))
  8260. (setq link
  8261. (format-time-string
  8262. (car org-time-stamp-formats)
  8263. (apply 'encode-time
  8264. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8265. nil nil nil))))
  8266. (org-store-link-props :type "calendar" :date cd)))
  8267. ((eq major-mode 'help-mode)
  8268. (setq link (concat "help:" (save-excursion
  8269. (goto-char (point-min))
  8270. (looking-at "^[^ ]+")
  8271. (match-string 0))))
  8272. (org-store-link-props :type "help"))
  8273. ((eq major-mode 'w3-mode)
  8274. (setq cpltxt (if (and (buffer-name)
  8275. (not (string-match "Untitled" (buffer-name))))
  8276. (buffer-name)
  8277. (url-view-url t))
  8278. link (url-view-url t))
  8279. (org-store-link-props :type "w3" :url (url-view-url t)))
  8280. ((eq major-mode 'image-mode)
  8281. (setq cpltxt (concat "file:"
  8282. (abbreviate-file-name buffer-file-name))
  8283. link cpltxt)
  8284. (org-store-link-props :type "image" :file buffer-file-name))
  8285. ;; In dired, store a link to the file of the current line
  8286. ((derived-mode-p 'dired-mode)
  8287. (let ((file (dired-get-filename nil t)))
  8288. (setq file (if file
  8289. (abbreviate-file-name
  8290. (expand-file-name (dired-get-filename nil t)))
  8291. ;; otherwise, no file so use current directory.
  8292. default-directory))
  8293. (setq cpltxt (concat "file:" file)
  8294. link cpltxt)))
  8295. ((setq search (run-hook-with-args-until-success
  8296. 'org-create-file-search-functions))
  8297. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8298. "::" search))
  8299. (setq cpltxt (or description link)))
  8300. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8301. (org-with-limited-levels
  8302. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8303. (cond
  8304. ;; Store a link using the target at point
  8305. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8306. (setq cpltxt
  8307. (concat "file:"
  8308. (abbreviate-file-name
  8309. (buffer-file-name (buffer-base-buffer)))
  8310. "::" (match-string 1))
  8311. link cpltxt))
  8312. ((and (featurep 'org-id)
  8313. (or (eq org-id-link-to-org-use-id t)
  8314. (and interactive?
  8315. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8316. (and (eq org-id-link-to-org-use-id
  8317. 'create-if-interactive-and-no-custom-id)
  8318. (not custom-id))))
  8319. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8320. ;; Store a link using the ID at point
  8321. (setq link (condition-case nil
  8322. (prog1 (org-id-store-link)
  8323. (setq desc (or (plist-get org-store-link-plist
  8324. :description)
  8325. "")))
  8326. (error
  8327. ;; Probably before first headline, link only to file
  8328. (concat "file:"
  8329. (abbreviate-file-name
  8330. (buffer-file-name (buffer-base-buffer))))))))
  8331. (t
  8332. ;; Just link to current headline
  8333. (setq cpltxt (concat "file:"
  8334. (abbreviate-file-name
  8335. (buffer-file-name (buffer-base-buffer)))))
  8336. ;; Add a context search string
  8337. (when (org-xor org-context-in-file-links
  8338. (equal arg '(4)))
  8339. (let* ((element (org-element-at-point))
  8340. (name (org-element-property :name element)))
  8341. (setq txt (cond
  8342. ((org-at-heading-p) nil)
  8343. (name)
  8344. ((org-region-active-p)
  8345. (buffer-substring (region-beginning) (region-end)))))
  8346. (when (or (null txt) (string-match "\\S-" txt))
  8347. (setq cpltxt
  8348. (concat cpltxt "::"
  8349. (condition-case nil
  8350. (org-make-org-heading-search-string txt)
  8351. (error "")))
  8352. desc (or name
  8353. (nth 4 (ignore-errors (org-heading-components)))
  8354. "NONE")))))
  8355. (when (string-match "::\\'" cpltxt)
  8356. (setq cpltxt (substring cpltxt 0 -2)))
  8357. (setq link cpltxt)))))
  8358. ((buffer-file-name (buffer-base-buffer))
  8359. ;; Just link to this file here.
  8360. (setq cpltxt (concat "file:"
  8361. (abbreviate-file-name
  8362. (buffer-file-name (buffer-base-buffer)))))
  8363. ;; Add a context string.
  8364. (when (org-xor org-context-in-file-links
  8365. (equal arg '(4)))
  8366. (setq txt (if (org-region-active-p)
  8367. (buffer-substring (region-beginning) (region-end))
  8368. (buffer-substring (point-at-bol) (point-at-eol))))
  8369. ;; Only use search option if there is some text.
  8370. (when (string-match "\\S-" txt)
  8371. (setq cpltxt
  8372. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8373. desc "NONE")))
  8374. (setq link cpltxt))
  8375. (interactive?
  8376. (user-error "No method for storing a link from this buffer"))
  8377. (t (setq link nil)))
  8378. ;; We're done setting link and desc, clean up
  8379. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8380. (setq link (or link cpltxt)
  8381. desc (or desc cpltxt))
  8382. (cond ((not desc))
  8383. ((equal desc "NONE") (setq desc nil))
  8384. (t (setq desc
  8385. (replace-regexp-in-string
  8386. org-bracket-link-analytic-regexp
  8387. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8388. desc))))
  8389. ;; Return the link
  8390. (if (not (and interactive? link))
  8391. (or agenda-link (and link (org-make-link-string link desc)))
  8392. (push (list link desc) org-stored-links)
  8393. (message "Stored: %s" (or desc link))
  8394. (when custom-id
  8395. (setq link (concat "file:" (abbreviate-file-name
  8396. (buffer-file-name)) "::#" custom-id))
  8397. (push (list link desc) org-stored-links))
  8398. (car org-stored-links)))))
  8399. (defun org-store-link-props (&rest plist)
  8400. "Store link properties.
  8401. The properties are pre-processed by extracting names, addresses
  8402. and dates."
  8403. (let ((x (plist-get plist :from)))
  8404. (when x
  8405. (let ((adr (mail-extract-address-components x)))
  8406. (setq plist (plist-put plist :fromname (car adr)))
  8407. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8408. (let ((x (plist-get plist :to)))
  8409. (when x
  8410. (let ((adr (mail-extract-address-components x)))
  8411. (setq plist (plist-put plist :toname (car adr)))
  8412. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8413. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8414. (when x
  8415. (setq plist (plist-put plist :date-timestamp
  8416. (format-time-string
  8417. (org-time-stamp-format t) x)))
  8418. (setq plist (plist-put plist :date-timestamp-inactive
  8419. (format-time-string
  8420. (org-time-stamp-format t t) x)))))
  8421. (let ((from (plist-get plist :from))
  8422. (to (plist-get plist :to)))
  8423. (when (and from to org-from-is-user-regexp)
  8424. (setq plist
  8425. (plist-put plist :fromto
  8426. (if (string-match org-from-is-user-regexp from)
  8427. (concat "to %t")
  8428. (concat "from %f"))))))
  8429. (setq org-store-link-plist plist))
  8430. (defun org-add-link-props (&rest plist)
  8431. "Add these properties to the link property list."
  8432. (let (key value)
  8433. (while plist
  8434. (setq key (pop plist) value (pop plist))
  8435. (setq org-store-link-plist
  8436. (plist-put org-store-link-plist key value)))))
  8437. (defun org-email-link-description (&optional fmt)
  8438. "Return the description part of an email link.
  8439. This takes information from `org-store-link-plist' and formats it
  8440. according to FMT (default from `org-email-link-description-format')."
  8441. (setq fmt (or fmt org-email-link-description-format))
  8442. (let* ((p org-store-link-plist)
  8443. (to (plist-get p :toaddress))
  8444. (from (plist-get p :fromaddress))
  8445. (table
  8446. (list
  8447. (cons "%c" (plist-get p :fromto))
  8448. (cons "%F" (plist-get p :from))
  8449. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8450. (cons "%T" (plist-get p :to))
  8451. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8452. (cons "%s" (plist-get p :subject))
  8453. (cons "%d" (plist-get p :date))
  8454. (cons "%m" (plist-get p :message-id)))))
  8455. (when (string-match "%c" fmt)
  8456. ;; Check if the user wrote this message
  8457. (if (and org-from-is-user-regexp from to
  8458. (save-match-data (string-match org-from-is-user-regexp from)))
  8459. (setq fmt (replace-match "to %t" t t fmt))
  8460. (setq fmt (replace-match "from %f" t t fmt))))
  8461. (org-replace-escapes fmt table)))
  8462. (defun org-make-org-heading-search-string (&optional string)
  8463. "Make search string for the current headline or STRING."
  8464. (let ((s (or string
  8465. (and (derived-mode-p 'org-mode)
  8466. (save-excursion
  8467. (org-back-to-heading t)
  8468. (org-element-property :raw-value (org-element-at-point))))))
  8469. (lines org-context-in-file-links))
  8470. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8471. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8472. (when (and string (integerp lines) (> lines 0))
  8473. (let ((slines (org-split-string s "\n")))
  8474. (when (< lines (length slines))
  8475. (setq s (mapconcat
  8476. 'identity
  8477. (reverse (nthcdr (- (length slines) lines)
  8478. (reverse slines))) "\n")))))
  8479. (mapconcat #'identity (split-string s) " ")))
  8480. (defconst org-link-escape-chars
  8481. ;;%20 %5B %5D %25
  8482. '(?\s ?\[ ?\] ?%)
  8483. "List of characters that should be escaped in a link when stored to Org.
  8484. This is the list that is used for internal purposes.")
  8485. (defun org-make-link-string (link &optional description)
  8486. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8487. (unless (org-string-nw-p link) (error "Empty link"))
  8488. (let ((uri (cond ((string-match org-link-types-re link)
  8489. (concat (match-string 1 link)
  8490. (org-link-escape (substring link (match-end 1)))))
  8491. ((or (file-name-absolute-p link)
  8492. (string-match-p "\\`\\.\\.?/" link))
  8493. (org-link-escape link))
  8494. ;; For readability, do not encode space characters
  8495. ;; in fuzzy links.
  8496. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8497. (description
  8498. (and (org-string-nw-p description)
  8499. ;; Remove brackets from description, as they are fatal.
  8500. (replace-regexp-in-string
  8501. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8502. (org-trim description)))))
  8503. (format "[[%s]%s]"
  8504. uri
  8505. (if description (format "[%s]" description) ""))))
  8506. (defun org-link-escape (text &optional table merge)
  8507. "Return percent escaped representation of TEXT.
  8508. TEXT is a string with the text to escape.
  8509. Optional argument TABLE is a list with characters that should be
  8510. escaped. When nil, `org-link-escape-chars' is used.
  8511. If optional argument MERGE is set, merge TABLE into
  8512. `org-link-escape-chars'."
  8513. (let ((characters-to-encode
  8514. (cond ((null table) org-link-escape-chars)
  8515. (merge (append org-link-escape-chars table))
  8516. (t table))))
  8517. (mapconcat
  8518. (lambda (c)
  8519. (if (or (memq c characters-to-encode)
  8520. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8521. (mapconcat (lambda (e) (format "%%%.2X" e))
  8522. (or (encode-coding-char c 'utf-8)
  8523. (error "Unable to percent escape character: %c" c))
  8524. "")
  8525. (char-to-string c)))
  8526. text "")))
  8527. (defun org-link-unescape (str)
  8528. "Unhex hexified Unicode parts in string STR.
  8529. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8530. reciprocal of `org-link-escape', which see."
  8531. (if (org-string-nw-p str)
  8532. (replace-regexp-in-string
  8533. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8534. str))
  8535. (defun org-link-unescape-compound (hex)
  8536. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8537. Note: this function also decodes single byte encodings like
  8538. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8539. (save-match-data
  8540. (let* ((bytes (cdr (split-string hex "%")))
  8541. (ret "")
  8542. (eat 0)
  8543. (sum 0))
  8544. (while bytes
  8545. (let* ((val (string-to-number (pop bytes) 16))
  8546. (shift-xor
  8547. (if (= 0 eat)
  8548. (cond
  8549. ((>= val 252) (cons 6 252))
  8550. ((>= val 248) (cons 5 248))
  8551. ((>= val 240) (cons 4 240))
  8552. ((>= val 224) (cons 3 224))
  8553. ((>= val 192) (cons 2 192))
  8554. (t (cons 0 0)))
  8555. (cons 6 128))))
  8556. (when (>= val 192) (setq eat (car shift-xor)))
  8557. (setq val (logxor val (cdr shift-xor)))
  8558. (setq sum (+ (lsh sum (car shift-xor)) val))
  8559. (when (> eat 0) (setq eat (- eat 1)))
  8560. (cond
  8561. ((= 0 eat) ;multi byte
  8562. (setq ret (concat ret (char-to-string sum)))
  8563. (setq sum 0))
  8564. ((not bytes) ; single byte(s)
  8565. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8566. ret)))
  8567. (defun org-link-unescape-single-byte-sequence (hex)
  8568. "Unhexify hex-encoded single byte character sequences."
  8569. (mapconcat (lambda (byte)
  8570. (char-to-string (string-to-number byte 16)))
  8571. (cdr (split-string hex "%")) ""))
  8572. (defun org-fixup-message-id-for-http (s)
  8573. "Replace special characters in a message id, so it can be used in an http query."
  8574. (when (string-match "%" s)
  8575. (setq s (mapconcat (lambda (c)
  8576. (if (eq c ?%)
  8577. "%25"
  8578. (char-to-string c)))
  8579. s "")))
  8580. (while (string-match "<" s)
  8581. (setq s (replace-match "%3C" t t s)))
  8582. (while (string-match ">" s)
  8583. (setq s (replace-match "%3E" t t s)))
  8584. (while (string-match "@" s)
  8585. (setq s (replace-match "%40" t t s)))
  8586. s)
  8587. (defun org-link-prettify (link)
  8588. "Return a human-readable representation of LINK.
  8589. The car of LINK must be a raw link.
  8590. The cdr of LINK must be either a link description or nil."
  8591. (let ((desc (or (cadr link) "<no description>")))
  8592. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8593. "<" (car link) ">")))
  8594. ;;;###autoload
  8595. (defun org-insert-link-global ()
  8596. "Insert a link like Org mode does.
  8597. This command can be called in any mode to insert a link in Org syntax."
  8598. (interactive)
  8599. (org-load-modules-maybe)
  8600. (org-run-like-in-org-mode 'org-insert-link))
  8601. (defun org-insert-all-links (arg &optional pre post)
  8602. "Insert all links in `org-stored-links'.
  8603. When a universal prefix, do not delete the links from `org-stored-links'.
  8604. When `ARG' is a number, insert the last N link(s).
  8605. `PRE' and `POST' are optional arguments to define a string to
  8606. prepend or to append."
  8607. (interactive "P")
  8608. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8609. (links (copy-sequence org-stored-links))
  8610. (pr (or pre "- "))
  8611. (po (or post "\n"))
  8612. (cnt 1) l)
  8613. (if (null org-stored-links)
  8614. (message "No link to insert")
  8615. (while (and (or (listp arg) (>= arg cnt))
  8616. (setq l (if (listp arg)
  8617. (pop links)
  8618. (pop org-stored-links))))
  8619. (setq cnt (1+ cnt))
  8620. (insert pr)
  8621. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8622. (insert po)))))
  8623. (defun org-insert-last-stored-link (arg)
  8624. "Insert the last link stored in `org-stored-links'."
  8625. (interactive "p")
  8626. (org-insert-all-links arg "" "\n"))
  8627. (defun org-link-fontify-links-to-this-file ()
  8628. "Fontify links to the current file in `org-stored-links'."
  8629. (let ((f (buffer-file-name)) a b)
  8630. (setq a (mapcar (lambda(l)
  8631. (let ((ll (car l)))
  8632. (when (and (string-match "^file:\\(.+\\)::" ll)
  8633. (equal f (expand-file-name (match-string 1 ll))))
  8634. ll)))
  8635. org-stored-links))
  8636. (when (featurep 'org-id)
  8637. (setq b (mapcar (lambda(l)
  8638. (let ((ll (car l)))
  8639. (when (and (string-match "^id:\\(.+\\)$" ll)
  8640. (equal f (expand-file-name
  8641. (or (org-id-find-id-file
  8642. (match-string 1 ll)) ""))))
  8643. ll)))
  8644. org-stored-links)))
  8645. (mapcar (lambda(l)
  8646. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8647. (delq nil (append a b)))))
  8648. (defvar org--links-history nil)
  8649. (defun org-insert-link (&optional complete-file link-location default-description)
  8650. "Insert a link. At the prompt, enter the link.
  8651. Completion can be used to insert any of the link protocol prefixes in use.
  8652. The history can be used to select a link previously stored with
  8653. `org-store-link'. When the empty string is entered (i.e. if you just
  8654. press `RET' at the prompt), the link defaults to the most recently
  8655. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8656. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8657. You will also be prompted for a description, and if one is given, it will
  8658. be displayed in the buffer instead of the link.
  8659. If there is already a link at point, this command will allow you to edit
  8660. link and description parts.
  8661. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8662. file name can be
  8663. selected using completion. The path to the file will be relative to the
  8664. current directory if the file is in the current directory or a subdirectory.
  8665. Otherwise, the link will be the absolute path as completed in the minibuffer
  8666. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8667. option `org-link-file-path-type'.
  8668. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8669. absolute path even if the file is in
  8670. the current directory or below.
  8671. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8672. prefix negates `org-keep-stored-link-after-insertion'.
  8673. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8674. the link location instead of reading one interactively.
  8675. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8676. be used as the default description. Otherwise, if
  8677. `org-make-link-description-function' is non-nil, this function
  8678. will be called with the link target, and the result will be the
  8679. default link description. When called non-interactivily, don't
  8680. allow to edit the default description."
  8681. (interactive "P")
  8682. (let* ((wcf (current-window-configuration))
  8683. (origbuf (current-buffer))
  8684. (region (when (org-region-active-p)
  8685. (buffer-substring (region-beginning) (region-end))))
  8686. (remove (and region (list (region-beginning) (region-end))))
  8687. (desc region)
  8688. (link link-location)
  8689. (abbrevs org-link-abbrev-alist-local)
  8690. entry all-prefixes auto-desc)
  8691. (cond
  8692. (link-location) ; specified by arg, just use it.
  8693. ((org-in-regexp org-bracket-link-regexp 1)
  8694. ;; We do have a link at point, and we are going to edit it.
  8695. (setq remove (list (match-beginning 0) (match-end 0)))
  8696. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8697. (setq link (read-string "Link: "
  8698. (org-link-unescape
  8699. (match-string-no-properties 1)))))
  8700. ((or (org-in-regexp org-angle-link-re)
  8701. (org-in-regexp org-plain-link-re))
  8702. ;; Convert to bracket link
  8703. (setq remove (list (match-beginning 0) (match-end 0))
  8704. link (read-string "Link: "
  8705. (org-unbracket-string "<" ">" (match-string 0)))))
  8706. ((member complete-file '((4) (16)))
  8707. ;; Completing read for file names.
  8708. (setq link (org-file-complete-link complete-file)))
  8709. (t
  8710. ;; Read link, with completion for stored links.
  8711. (org-link-fontify-links-to-this-file)
  8712. (org-switch-to-buffer-other-window "*Org Links*")
  8713. (with-current-buffer "*Org Links*"
  8714. (erase-buffer)
  8715. (insert "Insert a link.
  8716. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8717. (when org-stored-links
  8718. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8719. (insert (mapconcat 'org-link-prettify
  8720. (reverse org-stored-links) "\n")))
  8721. (goto-char (point-min)))
  8722. (let ((cw (selected-window)))
  8723. (select-window (get-buffer-window "*Org Links*" 'visible))
  8724. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8725. (unless (pos-visible-in-window-p (point-max))
  8726. (org-fit-window-to-buffer))
  8727. (and (window-live-p cw) (select-window cw)))
  8728. (setq all-prefixes (append (mapcar 'car abbrevs)
  8729. (mapcar 'car org-link-abbrev-alist)
  8730. (org-link-types)))
  8731. (unwind-protect
  8732. ;; Fake a link history, containing the stored links.
  8733. (let ((org--links-history
  8734. (append (mapcar #'car org-stored-links)
  8735. org-insert-link-history)))
  8736. (setq link
  8737. (org-completing-read
  8738. "Link: "
  8739. (append
  8740. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8741. (mapcar #'car org-stored-links))
  8742. nil nil nil
  8743. 'org--links-history
  8744. (caar org-stored-links)))
  8745. (unless (org-string-nw-p link) (user-error "No link selected"))
  8746. (dolist (l org-stored-links)
  8747. (when (equal link (cadr l))
  8748. (setq link (car l))
  8749. (setq auto-desc t)))
  8750. (when (or (member link all-prefixes)
  8751. (and (equal ":" (substring link -1))
  8752. (member (substring link 0 -1) all-prefixes)
  8753. (setq link (substring link 0 -1))))
  8754. (setq link (with-current-buffer origbuf
  8755. (org-link-try-special-completion link)))))
  8756. (set-window-configuration wcf)
  8757. (kill-buffer "*Org Links*"))
  8758. (setq entry (assoc link org-stored-links))
  8759. (or entry (push link org-insert-link-history))
  8760. (setq desc (or desc (nth 1 entry)))))
  8761. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8762. (not org-keep-stored-link-after-insertion))
  8763. (setq org-stored-links (delq (assoc link org-stored-links)
  8764. org-stored-links)))
  8765. (when (and (string-match org-plain-link-re link)
  8766. (not (string-match org-ts-regexp link)))
  8767. ;; URL-like link, normalize the use of angular brackets.
  8768. (setq link (org-unbracket-string "<" ">" link)))
  8769. ;; Check if we are linking to the current file with a search
  8770. ;; option If yes, simplify the link by using only the search
  8771. ;; option.
  8772. (when (and buffer-file-name
  8773. (let ((case-fold-search nil))
  8774. (string-match "\\`file:\\(.+?\\)::" link)))
  8775. (let ((path (match-string-no-properties 1 link))
  8776. (search (substring-no-properties link (match-end 0))))
  8777. (save-match-data
  8778. (when (equal (file-truename buffer-file-name) (file-truename path))
  8779. ;; We are linking to this same file, with a search option
  8780. (setq link search)))))
  8781. ;; Check if we can/should use a relative path. If yes, simplify
  8782. ;; the link.
  8783. (let ((case-fold-search nil))
  8784. (when (string-match "\\`\\(file\\|docview\\):" link)
  8785. (let* ((type (match-string-no-properties 0 link))
  8786. (path-start (match-end 0))
  8787. (search (and (string-match "::\\(.*\\)\\'" link)
  8788. (match-string 1 link)))
  8789. (path
  8790. (if search
  8791. (substring-no-properties
  8792. link path-start (match-beginning 0))
  8793. (substring-no-properties link (match-end 0))))
  8794. (origpath path))
  8795. (cond
  8796. ((or (eq org-link-file-path-type 'absolute)
  8797. (equal complete-file '(16)))
  8798. (setq path (abbreviate-file-name (expand-file-name path))))
  8799. ((eq org-link-file-path-type 'noabbrev)
  8800. (setq path (expand-file-name path)))
  8801. ((eq org-link-file-path-type 'relative)
  8802. (setq path (file-relative-name path)))
  8803. (t
  8804. (save-match-data
  8805. (if (string-match (concat "^" (regexp-quote
  8806. (expand-file-name
  8807. (file-name-as-directory
  8808. default-directory))))
  8809. (expand-file-name path))
  8810. ;; We are linking a file with relative path name.
  8811. (setq path (substring (expand-file-name path)
  8812. (match-end 0)))
  8813. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8814. (setq link (concat type path (and search (concat "::" search))))
  8815. (when (equal desc origpath)
  8816. (setq desc path)))))
  8817. (unless auto-desc
  8818. (let ((initial-input
  8819. (cond
  8820. (default-description)
  8821. ((not org-make-link-description-function) desc)
  8822. (t (condition-case nil
  8823. (funcall org-make-link-description-function link desc)
  8824. (error
  8825. (message "Can't get link description from `%s'"
  8826. (symbol-name org-make-link-description-function))
  8827. (sit-for 2)
  8828. nil))))))
  8829. (setq desc (if (called-interactively-p 'any)
  8830. (read-string "Description: " initial-input)
  8831. initial-input))))
  8832. (unless (string-match "\\S-" desc) (setq desc nil))
  8833. (when remove (apply 'delete-region remove))
  8834. (insert (org-make-link-string link desc))
  8835. ;; Redisplay so as the new link has proper invisible characters.
  8836. (sit-for 0)))
  8837. (defun org-link-try-special-completion (type)
  8838. "If there is completion support for link type TYPE, offer it."
  8839. (let ((fun (org-link-get-parameter type :complete)))
  8840. (if (functionp fun)
  8841. (funcall fun)
  8842. (read-string "Link (no completion support): " (concat type ":")))))
  8843. (defun org-file-complete-link (&optional arg)
  8844. "Create a file link using completion."
  8845. (let ((file (read-file-name "File: "))
  8846. (pwd (file-name-as-directory (expand-file-name ".")))
  8847. (pwd1 (file-name-as-directory (abbreviate-file-name
  8848. (expand-file-name ".")))))
  8849. (cond ((equal arg '(16))
  8850. (concat "file:"
  8851. (abbreviate-file-name (expand-file-name file))))
  8852. ((string-match
  8853. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8854. (concat "file:" (match-string 1 file)))
  8855. ((string-match
  8856. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8857. (expand-file-name file))
  8858. (concat "file:"
  8859. (match-string 1 (expand-file-name file))))
  8860. (t (concat "file:" file)))))
  8861. ;;; Opening/following a link
  8862. (defvar org-link-search-failed nil)
  8863. (defvar org-open-link-functions nil
  8864. "Hook for functions finding a plain text link.
  8865. These functions must take a single argument, the link content.
  8866. They will be called for links that look like [[link text][description]]
  8867. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8868. like a filename (e.g. \"./blue.png\").
  8869. These functions will be called *before* Org attempts to resolve the
  8870. link by doing text searches in the current buffer - so if you want a
  8871. link \"[[target]]\" to still find \"<<target>>\", your function should
  8872. handle this as a special case.
  8873. When the function does handle the link, it must return a non-nil value.
  8874. If it decides that it is not responsible for this link, it must return
  8875. nil to indicate that that Org can continue with other options like
  8876. exact and fuzzy text search.")
  8877. (defun org-next-link (&optional search-backward)
  8878. "Move forward to the next link.
  8879. If the link is in hidden text, expose it."
  8880. (interactive "P")
  8881. (when (and org-link-search-failed (eq this-command last-command))
  8882. (goto-char (point-min))
  8883. (message "Link search wrapped back to beginning of buffer"))
  8884. (setq org-link-search-failed nil)
  8885. (let* ((pos (point))
  8886. (ct (org-context))
  8887. (a (assq :link ct))
  8888. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8889. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8890. ((looking-at org-any-link-re)
  8891. ;; Don't stay stuck at link without an org-link face
  8892. (forward-char (if search-backward -1 1))))
  8893. (if (funcall srch-fun org-any-link-re nil t)
  8894. (progn
  8895. (goto-char (match-beginning 0))
  8896. (when (org-invisible-p) (org-show-context)))
  8897. (goto-char pos)
  8898. (setq org-link-search-failed t)
  8899. (message "No further link found"))))
  8900. (defun org-previous-link ()
  8901. "Move backward to the previous link.
  8902. If the link is in hidden text, expose it."
  8903. (interactive)
  8904. (org-next-link t))
  8905. (defun org-translate-link (s)
  8906. "Translate a link string if a translation function has been defined."
  8907. (with-temp-buffer
  8908. (insert (org-trim s))
  8909. (org-trim (org-element-interpret-data (org-element-context)))))
  8910. (defun org-translate-link-from-planner (type path)
  8911. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8912. This is still an experimental function, your mileage may vary."
  8913. (cond
  8914. ((member type '("http" "https" "news" "ftp"))
  8915. ;; standard Internet links are the same.
  8916. nil)
  8917. ((and (equal type "irc") (string-match "^//" path))
  8918. ;; Planner has two / at the beginning of an irc link, we have 1.
  8919. ;; We should have zero, actually....
  8920. (setq path (substring path 1)))
  8921. ((and (equal type "lisp") (string-match "^/" path))
  8922. ;; Planner has a slash, we do not.
  8923. (setq type "elisp" path (substring path 1)))
  8924. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8925. ;; A typical message link. Planner has the id after the final slash,
  8926. ;; we separate it with a hash mark
  8927. (setq path (concat (match-string 1 path) "#"
  8928. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8929. (cons type path))
  8930. (defun org-find-file-at-mouse (ev)
  8931. "Open file link or URL at mouse."
  8932. (interactive "e")
  8933. (mouse-set-point ev)
  8934. (org-open-at-point 'in-emacs))
  8935. (defun org-open-at-mouse (ev)
  8936. "Open file link or URL at mouse.
  8937. See the docstring of `org-open-file' for details."
  8938. (interactive "e")
  8939. (mouse-set-point ev)
  8940. (when (eq major-mode 'org-agenda-mode)
  8941. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8942. (org-open-at-point))
  8943. (defvar org-window-config-before-follow-link nil
  8944. "The window configuration before following a link.
  8945. This is saved in case the need arises to restore it.")
  8946. ;;;###autoload
  8947. (defun org-open-at-point-global ()
  8948. "Follow a link or a time-stamp like Org mode does.
  8949. Also follow links and emails as seen by `thing-at-point'.
  8950. This command can be called in any mode to follow an external
  8951. link or a time-stamp that has Org mode syntax. Its behavior
  8952. is undefined when called on internal links like fuzzy links.
  8953. Raise a user error when there is nothing to follow."
  8954. (interactive)
  8955. (let ((tap-url (thing-at-point 'url))
  8956. (tap-email (thing-at-point 'email)))
  8957. (cond ((org-in-regexp org-any-link-re)
  8958. (org-open-link-from-string (match-string-no-properties 0)))
  8959. ((or (org-in-regexp org-ts-regexp-both nil t)
  8960. (org-in-regexp org-tsr-regexp-both nil t))
  8961. (org-follow-timestamp-link))
  8962. (tap-url (org-open-link-from-string tap-url))
  8963. (tap-email (org-open-link-from-string
  8964. (concat "mailto:" tap-email)))
  8965. (t (user-error "No link found")))))
  8966. ;;;###autoload
  8967. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8968. "Open a link in the string S, as if it was in Org mode."
  8969. (interactive "sLink: \nP")
  8970. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8971. (with-temp-buffer
  8972. (let ((org-inhibit-startup (not reference-buffer)))
  8973. (org-mode)
  8974. (insert s)
  8975. (goto-char (point-min))
  8976. (when reference-buffer
  8977. (setq org-link-abbrev-alist-local
  8978. (with-current-buffer reference-buffer
  8979. org-link-abbrev-alist-local)))
  8980. (org-open-at-point arg reference-buffer)))))
  8981. (defvar org-open-at-point-functions nil
  8982. "Hook that is run when following a link at point.
  8983. Functions in this hook must return t if they identify and follow
  8984. a link at point. If they don't find anything interesting at point,
  8985. they must return nil.")
  8986. (defvar org-link-search-inhibit-query nil)
  8987. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8988. (defun org--open-doi-link (path)
  8989. "Open a \"doi\" type link.
  8990. PATH is a the path to search for, as a string."
  8991. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8992. (defun org--open-elisp-link (path)
  8993. "Open a \"elisp\" type link.
  8994. PATH is the sexp to evaluate, as a string."
  8995. (let ((cmd path))
  8996. (if (or (and (org-string-nw-p
  8997. org-confirm-elisp-link-not-regexp)
  8998. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8999. (not org-confirm-elisp-link-function)
  9000. (funcall org-confirm-elisp-link-function
  9001. (format "Execute \"%s\" as elisp? "
  9002. (org-add-props cmd nil 'face 'org-warning))))
  9003. (message "%s => %s" cmd
  9004. (if (eq (string-to-char cmd) ?\()
  9005. (eval (read cmd))
  9006. (call-interactively (read cmd))))
  9007. (user-error "Abort"))))
  9008. (defun org--open-help-link (path)
  9009. "Open a \"help\" type link.
  9010. PATH is a symbol name, as a string."
  9011. (pcase (intern path)
  9012. ((and (pred fboundp) variable) (describe-function variable))
  9013. ((and (pred boundp) function) (describe-variable function))
  9014. (name (user-error "Unknown function or variable: %s" name))))
  9015. (defun org--open-shell-link (path)
  9016. "Open a \"shell\" type link.
  9017. PATH is the command to execute, as a string."
  9018. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9019. (cmd path))
  9020. (if (or (and (org-string-nw-p
  9021. org-confirm-shell-link-not-regexp)
  9022. (string-match
  9023. org-confirm-shell-link-not-regexp cmd))
  9024. (not org-confirm-shell-link-function)
  9025. (funcall org-confirm-shell-link-function
  9026. (format "Execute \"%s\" in shell? "
  9027. (org-add-props cmd nil
  9028. 'face 'org-warning))))
  9029. (progn
  9030. (message "Executing %s" cmd)
  9031. (shell-command cmd buf)
  9032. (when (featurep 'midnight)
  9033. (setq clean-buffer-list-kill-buffer-names
  9034. (cons (buffer-name buf)
  9035. clean-buffer-list-kill-buffer-names))))
  9036. (user-error "Abort"))))
  9037. (defun org-open-at-point (&optional arg reference-buffer)
  9038. "Open link, timestamp, footnote or tags at point.
  9039. When point is on a link, follow it. Normally, files will be
  9040. opened by an appropriate application. If the optional prefix
  9041. argument ARG is non-nil, Emacs will visit the file. With
  9042. a double prefix argument, try to open outside of Emacs, in the
  9043. application the system uses for this file type.
  9044. When point is on a timestamp, open the agenda at the day
  9045. specified.
  9046. When point is a footnote definition, move to the first reference
  9047. found. If it is on a reference, move to the associated
  9048. definition.
  9049. When point is on a headline, display a list of every link in the
  9050. entry, so it is possible to pick one, or all, of them. If point
  9051. is on a tag, call `org-tags-view' instead.
  9052. When optional argument REFERENCE-BUFFER is non-nil, it should
  9053. specify a buffer from where the link search should happen. This
  9054. is used internally by `org-open-link-from-string'.
  9055. On top of syntactically correct links, this function also tries
  9056. to open links and time-stamps in comments, node properties, and
  9057. keywords if point is on something looking like a timestamp or
  9058. a link."
  9059. (interactive "P")
  9060. (org-load-modules-maybe)
  9061. (setq org-window-config-before-follow-link (current-window-configuration))
  9062. (org-remove-occur-highlights nil nil t)
  9063. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9064. (let* ((context
  9065. ;; Only consider supported types, even if they are not the
  9066. ;; closest one.
  9067. (org-element-lineage
  9068. (org-element-context)
  9069. '(clock comment comment-block footnote-definition
  9070. footnote-reference headline inline-src-block inlinetask
  9071. keyword link node-property src-block timestamp)
  9072. t))
  9073. (type (org-element-type context))
  9074. (value (org-element-property :value context)))
  9075. (cond
  9076. ((not type) (user-error "No link found"))
  9077. ;; No valid link at point. For convenience, look if something
  9078. ;; looks like a link under point in some specific places.
  9079. ((memq type '(comment comment-block node-property keyword))
  9080. (call-interactively #'org-open-at-point-global))
  9081. ;; On a headline or an inlinetask, but not on a timestamp,
  9082. ;; a link, a footnote reference.
  9083. ((memq type '(headline inlinetask))
  9084. (org-match-line org-complex-heading-regexp)
  9085. (if (and (match-beginning 5)
  9086. (>= (point) (match-beginning 5))
  9087. (< (point) (match-end 5)))
  9088. ;; On tags.
  9089. (org-tags-view arg (substring (match-string 5) 0 -1))
  9090. ;; Not on tags.
  9091. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9092. (`(nil . ,_)
  9093. (require 'org-attach)
  9094. (org-attach-reveal 'if-exists))
  9095. (`(,links . ,links-end)
  9096. (dolist (link (if (stringp links) (list links) links))
  9097. (search-forward link nil links-end)
  9098. (goto-char (match-beginning 0))
  9099. (org-open-at-point))))))
  9100. ;; On a footnote reference or at definition's label.
  9101. ((or (eq type 'footnote-reference)
  9102. (and (eq type 'footnote-definition)
  9103. (save-excursion
  9104. ;; Do not validate action when point is on the
  9105. ;; spaces right after the footnote label, in order
  9106. ;; to be on par with behavior on links.
  9107. (skip-chars-forward " \t")
  9108. (let ((begin
  9109. (org-element-property :contents-begin context)))
  9110. (if begin (< (point) begin)
  9111. (= (org-element-property :post-affiliated context)
  9112. (line-beginning-position)))))))
  9113. (org-footnote-action))
  9114. ;; On a clock line, make sure point is on the timestamp
  9115. ;; before opening it.
  9116. ((and (eq type 'clock)
  9117. value
  9118. (>= (point) (org-element-property :begin value))
  9119. (<= (point) (org-element-property :end value)))
  9120. (org-follow-timestamp-link))
  9121. ((eq type 'src-block) (org-babel-open-src-block-result))
  9122. ;; Do nothing on white spaces after an object.
  9123. ((>= (point)
  9124. (save-excursion
  9125. (goto-char (org-element-property :end context))
  9126. (skip-chars-backward " \t")
  9127. (point)))
  9128. (user-error "No link found"))
  9129. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  9130. ((eq type 'timestamp) (org-follow-timestamp-link))
  9131. ((eq type 'link)
  9132. (let ((type (org-element-property :type context))
  9133. (path (org-link-unescape (org-element-property :path context))))
  9134. ;; Switch back to REFERENCE-BUFFER needed when called in
  9135. ;; a temporary buffer through `org-open-link-from-string'.
  9136. (with-current-buffer (or reference-buffer (current-buffer))
  9137. (cond
  9138. ((equal type "file")
  9139. (if (string-match "[*?{]" (file-name-nondirectory path))
  9140. (dired path)
  9141. ;; Look into `org-link-parameters' in order to find
  9142. ;; a DEDICATED-FUNCTION to open file. The function
  9143. ;; will be applied on raw link instead of parsed link
  9144. ;; due to the limitation in `org-add-link-type'
  9145. ;; ("open" function called with a single argument).
  9146. ;; If no such function is found, fallback to
  9147. ;; `org-open-file'.
  9148. (let* ((option (org-element-property :search-option context))
  9149. (app (org-element-property :application context))
  9150. (dedicated-function
  9151. (org-link-get-parameter
  9152. (if app (concat type "+" app) type)
  9153. :follow)))
  9154. (if dedicated-function
  9155. (funcall dedicated-function
  9156. (concat path
  9157. (and option (concat "::" option))))
  9158. (apply #'org-open-file
  9159. path
  9160. (cond (arg)
  9161. ((equal app "emacs") 'emacs)
  9162. ((equal app "sys") 'system))
  9163. (cond ((not option) nil)
  9164. ((string-match-p "\\`[0-9]+\\'" option)
  9165. (list (string-to-number option)))
  9166. (t (list nil
  9167. (org-link-unescape option)))))))))
  9168. ((functionp (org-link-get-parameter type :follow))
  9169. (funcall (org-link-get-parameter type :follow) path))
  9170. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9171. (unless (run-hook-with-args-until-success
  9172. 'org-open-link-functions path)
  9173. (if (not arg) (org-mark-ring-push)
  9174. (switch-to-buffer-other-window
  9175. (org-get-buffer-for-internal-link (current-buffer))))
  9176. (let ((destination
  9177. (org-with-wide-buffer
  9178. (if (equal type "radio")
  9179. (org-search-radio-target
  9180. (org-element-property :path context))
  9181. (org-link-search
  9182. (if (member type '("custom-id" "coderef"))
  9183. (org-element-property :raw-link context)
  9184. path)
  9185. ;; Prevent fuzzy links from matching
  9186. ;; themselves.
  9187. (and (equal type "fuzzy")
  9188. (+ 2 (org-element-property :begin context)))))
  9189. (point))))
  9190. (unless (and (<= (point-min) destination)
  9191. (>= (point-max) destination))
  9192. (widen))
  9193. (goto-char destination))))
  9194. (t (browse-url-at-point))))))
  9195. (t (user-error "No link found")))))
  9196. (run-hook-with-args 'org-follow-link-hook))
  9197. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9198. "Offer links in the current entry and return the selected link.
  9199. If there is only one link, return it.
  9200. If NTH is an integer, return the NTH link found.
  9201. If ZERO is a string, check also this string for a link, and if
  9202. there is one, return it."
  9203. (with-current-buffer buffer
  9204. (org-with-wide-buffer
  9205. (goto-char marker)
  9206. (let ((cnt ?0)
  9207. have-zero end links link c)
  9208. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9209. (push (match-string 0 zero) links)
  9210. (setq cnt (1- cnt) have-zero t))
  9211. (save-excursion
  9212. (org-back-to-heading t)
  9213. (setq end (save-excursion (outline-next-heading) (point)))
  9214. (while (re-search-forward org-any-link-re end t)
  9215. (push (match-string 0) links))
  9216. (setq links (org-uniquify (reverse links))))
  9217. (cond
  9218. ((null links)
  9219. (message "No links"))
  9220. ((equal (length links) 1)
  9221. (setq link (car links)))
  9222. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9223. (setq link (nth (if have-zero nth (1- nth)) links)))
  9224. (t ; we have to select a link
  9225. (save-excursion
  9226. (save-window-excursion
  9227. (delete-other-windows)
  9228. (with-output-to-temp-buffer "*Select Link*"
  9229. (dolist (l links)
  9230. (cond
  9231. ((not (string-match org-bracket-link-regexp l))
  9232. (princ (format "[%c] %s\n" (cl-incf cnt)
  9233. (org-unbracket-string "<" ">" l))))
  9234. ((match-end 3)
  9235. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9236. (match-string 3 l) (match-string 1 l))))
  9237. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9238. (match-string 1 l)))))))
  9239. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9240. (message "Select link to open, RET to open all:")
  9241. (setq c (read-char-exclusive))
  9242. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9243. (when (equal c ?q) (user-error "Abort"))
  9244. (if (equal c ?\C-m)
  9245. (setq link links)
  9246. (setq nth (- c ?0))
  9247. (when have-zero (setq nth (1+ nth)))
  9248. (unless (and (integerp nth) (>= (length links) nth))
  9249. (user-error "Invalid link selection"))
  9250. (setq link (nth (1- nth) links)))))
  9251. (cons link end)))))
  9252. ;; TODO: These functions are deprecated since `org-open-at-point'
  9253. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9254. (defun org-open-file-with-system (path)
  9255. "Open file at PATH using the system way of opening it."
  9256. (org-open-file path 'system))
  9257. (defun org-open-file-with-emacs (path)
  9258. "Open file at PATH in Emacs."
  9259. (org-open-file path 'emacs))
  9260. ;;; File search
  9261. (defvar org-create-file-search-functions nil
  9262. "List of functions to construct the right search string for a file link.
  9263. These functions are called in turn with point at the location to
  9264. which the link should point.
  9265. A function in the hook should first test if it would like to
  9266. handle this file type, for example by checking the `major-mode'
  9267. or the file extension. If it decides not to handle this file, it
  9268. should just return nil to give other functions a chance. If it
  9269. does handle the file, it must return the search string to be used
  9270. when following the link. The search string will be part of the
  9271. file link, given after a double colon, and `org-open-at-point'
  9272. will automatically search for it. If special measures must be
  9273. taken to make the search successful, another function should be
  9274. added to the companion hook `org-execute-file-search-functions',
  9275. which see.
  9276. A function in this hook may also use `setq' to set the variable
  9277. `description' to provide a suggestion for the descriptive text to
  9278. be used for this link when it gets inserted into an Org buffer
  9279. with \\[org-insert-link].")
  9280. (defvar org-execute-file-search-functions nil
  9281. "List of functions to execute a file search triggered by a link.
  9282. Functions added to this hook must accept a single argument, the
  9283. search string that was part of the file link, the part after the
  9284. double colon. The function must first check if it would like to
  9285. handle this search, for example by checking the `major-mode' or
  9286. the file extension. If it decides not to handle this search, it
  9287. should just return nil to give other functions a chance. If it
  9288. does handle the search, it must return a non-nil value to keep
  9289. other functions from trying.
  9290. Each function can access the current prefix argument through the
  9291. variable `current-prefix-arg'. Note that a single prefix is used
  9292. to force opening a link in Emacs, so it may be good to only use a
  9293. numeric or double prefix to guide the search function.
  9294. In case this is needed, a function in this hook can also restore
  9295. the window configuration before `org-open-at-point' was called using:
  9296. (set-window-configuration org-window-config-before-follow-link)")
  9297. (defun org-search-radio-target (target)
  9298. "Search a radio target matching TARGET in current buffer.
  9299. White spaces are not significant."
  9300. (let ((re (format "<<<%s>>>"
  9301. (mapconcat #'regexp-quote
  9302. (split-string target)
  9303. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9304. (origin (point)))
  9305. (goto-char (point-min))
  9306. (catch :radio-match
  9307. (while (re-search-forward re nil t)
  9308. (backward-char)
  9309. (let ((object (org-element-context)))
  9310. (when (eq (org-element-type object) 'radio-target)
  9311. (goto-char (org-element-property :begin object))
  9312. (org-show-context 'link-search)
  9313. (throw :radio-match nil))))
  9314. (goto-char origin)
  9315. (user-error "No match for radio target: %s" target))))
  9316. (defun org-link-search (s &optional avoid-pos stealth)
  9317. "Search for a search string S.
  9318. If S starts with \"#\", it triggers a custom ID search.
  9319. If S is enclosed within parenthesis, it initiates a coderef
  9320. search.
  9321. If S is surrounded by forward slashes, it is interpreted as
  9322. a regular expression. In Org mode files, this will create an
  9323. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9324. to list matches. If the current buffer is in `dired-mode', grep
  9325. will be used to search in all files.
  9326. When AVOID-POS is given, ignore matches near that position.
  9327. When optional argument STEALTH is non-nil, do not modify
  9328. visibility around point, thus ignoring `org-show-context-detail'
  9329. variable.
  9330. Search is case-insensitive and ignores white spaces. Return type
  9331. of matched result, which is either `dedicated' or `fuzzy'."
  9332. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9333. (let* ((case-fold-search t)
  9334. (origin (point))
  9335. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9336. (starred (eq (string-to-char normalized) ?*))
  9337. (words (split-string (if starred (substring s 1) s)))
  9338. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9339. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9340. type)
  9341. (cond
  9342. ;; Check if there are any special search functions.
  9343. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9344. ((eq (string-to-char s) ?#)
  9345. ;; Look for a custom ID S if S starts with "#".
  9346. (let* ((id (substring normalized 1))
  9347. (match (org-find-property "CUSTOM_ID" id)))
  9348. (if match (progn (goto-char match) (setf type 'dedicated))
  9349. (error "No match for custom ID: %s" id))))
  9350. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9351. ;; Look for coderef targets if S is enclosed within parenthesis.
  9352. (let ((coderef (match-string-no-properties 1 normalized))
  9353. (re (substring s-single-re 1 -1)))
  9354. (goto-char (point-min))
  9355. (catch :coderef-match
  9356. (while (re-search-forward re nil t)
  9357. (let ((element (org-element-at-point)))
  9358. (when (and (memq (org-element-type element)
  9359. '(example-block src-block))
  9360. ;; Build proper regexp according to current
  9361. ;; block's label format.
  9362. (let ((label-fmt
  9363. (regexp-quote
  9364. (or (org-element-property :label-fmt element)
  9365. org-coderef-label-format))))
  9366. (save-excursion
  9367. (beginning-of-line)
  9368. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9369. (format label-fmt coderef))))))
  9370. (setq type 'dedicated)
  9371. (goto-char (match-beginning 1))
  9372. (throw :coderef-match nil))))
  9373. (goto-char origin)
  9374. (error "No match for coderef: %s" coderef))))
  9375. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9376. ;; Look for a regular expression.
  9377. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9378. (match-string 1 s)))
  9379. ;; From here, we handle fuzzy links.
  9380. ;;
  9381. ;; Look for targets, only if not in a headline search.
  9382. ((and (not starred)
  9383. (let ((target (format "<<%s>>" s-multi-re)))
  9384. (catch :target-match
  9385. (goto-char (point-min))
  9386. (while (re-search-forward target nil t)
  9387. (backward-char)
  9388. (let ((context (org-element-context)))
  9389. (when (eq (org-element-type context) 'target)
  9390. (setq type 'dedicated)
  9391. (goto-char (org-element-property :begin context))
  9392. (throw :target-match t))))
  9393. nil))))
  9394. ;; Look for elements named after S, only if not in a headline
  9395. ;; search.
  9396. ((and (not starred)
  9397. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9398. (catch :name-match
  9399. (goto-char (point-min))
  9400. (while (re-search-forward name nil t)
  9401. (let ((element (org-element-at-point)))
  9402. (when (equal words
  9403. (split-string
  9404. (org-element-property :name element)))
  9405. (setq type 'dedicated)
  9406. (beginning-of-line)
  9407. (throw :name-match t))))
  9408. nil))))
  9409. ;; Regular text search. Prefer headlines in Org mode buffers.
  9410. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9411. ;; statistics cookies and tags.
  9412. ((and (derived-mode-p 'org-mode)
  9413. (let ((title-re
  9414. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9415. org-outline-regexp-bol
  9416. org-comment-string
  9417. (mapconcat #'regexp-quote words ".+")))
  9418. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9419. (comment-re (eval-when-compile
  9420. (format "\\`%s[ \t]+" org-comment-string))))
  9421. (goto-char (point-min))
  9422. (catch :found
  9423. (while (re-search-forward title-re nil t)
  9424. (when (equal words
  9425. (split-string
  9426. (replace-regexp-in-string
  9427. cookie-re ""
  9428. (replace-regexp-in-string
  9429. comment-re "" (org-get-heading t t t)))))
  9430. (throw :found t)))
  9431. nil)))
  9432. (beginning-of-line)
  9433. (setq type 'dedicated))
  9434. ;; Offer to create non-existent headline depending on
  9435. ;; `org-link-search-must-match-exact-headline'.
  9436. ((and (derived-mode-p 'org-mode)
  9437. (not org-link-search-inhibit-query)
  9438. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9439. (yes-or-no-p "No match - create this as a new heading? "))
  9440. (goto-char (point-max))
  9441. (unless (bolp) (newline))
  9442. (org-insert-heading nil t t)
  9443. (insert s "\n")
  9444. (beginning-of-line 0))
  9445. ;; Only headlines are looked after. No need to process
  9446. ;; further: throw an error.
  9447. ((and (derived-mode-p 'org-mode)
  9448. (or starred org-link-search-must-match-exact-headline))
  9449. (goto-char origin)
  9450. (error "No match for fuzzy expression: %s" normalized))
  9451. ;; Regular text search.
  9452. ((catch :fuzzy-match
  9453. (goto-char (point-min))
  9454. (while (re-search-forward s-multi-re nil t)
  9455. ;; Skip match if it contains AVOID-POS or it is included in
  9456. ;; a link with a description but outside the description.
  9457. (unless (or (and avoid-pos
  9458. (<= (match-beginning 0) avoid-pos)
  9459. (> (match-end 0) avoid-pos))
  9460. (and (save-match-data
  9461. (org-in-regexp org-bracket-link-regexp))
  9462. (match-beginning 3)
  9463. (or (> (match-beginning 3) (point))
  9464. (<= (match-end 3) (point)))
  9465. (org-element-lineage
  9466. (save-match-data (org-element-context))
  9467. '(link) t)))
  9468. (goto-char (match-beginning 0))
  9469. (setq type 'fuzzy)
  9470. (throw :fuzzy-match t)))
  9471. nil))
  9472. ;; All failed. Throw an error.
  9473. (t (goto-char origin)
  9474. (error "No match for fuzzy expression: %s" normalized)))
  9475. ;; Disclose surroundings of match, if appropriate.
  9476. (when (and (derived-mode-p 'org-mode) (not stealth))
  9477. (org-show-context 'link-search))
  9478. type))
  9479. (defun org-get-buffer-for-internal-link (buffer)
  9480. "Return a buffer to be used for displaying the link target of internal links."
  9481. (cond
  9482. ((not org-display-internal-link-with-indirect-buffer)
  9483. buffer)
  9484. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9485. (message "Buffer is already a clone, not making another one")
  9486. ;; we also do not modify visibility in this case
  9487. buffer)
  9488. (t ; make a new indirect buffer for displaying the link
  9489. (let* ((bn (buffer-name buffer))
  9490. (ibn (concat bn "(Clone)"))
  9491. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9492. (with-current-buffer ib (org-overview))
  9493. ib))))
  9494. (defun org-do-occur (regexp &optional cleanup)
  9495. "Call the Emacs command `occur'.
  9496. If CLEANUP is non-nil, remove the printout of the regular expression
  9497. in the *Occur* buffer. This is useful if the regex is long and not useful
  9498. to read."
  9499. (occur regexp)
  9500. (when cleanup
  9501. (let ((cwin (selected-window)) win beg end)
  9502. (when (setq win (get-buffer-window "*Occur*"))
  9503. (select-window win))
  9504. (goto-char (point-min))
  9505. (when (re-search-forward "match[a-z]+" nil t)
  9506. (setq beg (match-end 0))
  9507. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9508. (setq end (1- (match-beginning 0)))))
  9509. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9510. (goto-char (point-min))
  9511. (select-window cwin))))
  9512. ;;; The Mark Ring
  9513. (defvar org-mark-ring nil
  9514. "Mark ring for positions before jumps in Org mode.")
  9515. (defvar org-mark-ring-last-goto nil
  9516. "Last position in the mark ring used to go back.")
  9517. ;; Fill and close the ring
  9518. (setq org-mark-ring nil)
  9519. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9520. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9521. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9522. org-mark-ring)
  9523. (defun org-mark-ring-push (&optional pos buffer)
  9524. "Put the current position into the mark ring and rotate it.
  9525. Also push position into the Emacs mark ring. If optional
  9526. argument POS and BUFFER are not nil, mark this location instead."
  9527. (interactive)
  9528. (let ((pos (or pos (point)))
  9529. (buffer (or buffer (current-buffer))))
  9530. (with-current-buffer buffer
  9531. (org-with-point-at pos (push-mark nil t)))
  9532. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9533. (move-marker (car org-mark-ring) pos buffer))
  9534. (message
  9535. (substitute-command-keys
  9536. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9537. (defun org-mark-ring-goto (&optional n)
  9538. "Jump to the previous position in the mark ring.
  9539. With prefix arg N, jump back that many stored positions. When
  9540. called several times in succession, walk through the entire ring.
  9541. Org mode commands jumping to a different position in the current file,
  9542. or to another Org file, automatically push the old position onto the ring."
  9543. (interactive "p")
  9544. (let (p m)
  9545. (if (eq last-command this-command)
  9546. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9547. (setq p org-mark-ring))
  9548. (setq org-mark-ring-last-goto p)
  9549. (setq m (car p))
  9550. (pop-to-buffer-same-window (marker-buffer m))
  9551. (goto-char m)
  9552. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9553. (defun org-add-angle-brackets (s)
  9554. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9555. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9556. s)
  9557. ;;; Following specific links
  9558. (defvar org-agenda-buffer-tmp-name)
  9559. (defvar org-agenda-start-on-weekday)
  9560. (defun org-follow-timestamp-link ()
  9561. "Open an agenda view for the time-stamp date/range at point."
  9562. (cond
  9563. ((org-at-date-range-p t)
  9564. (let ((org-agenda-start-on-weekday)
  9565. (t1 (match-string 1))
  9566. (t2 (match-string 2)) tt1 tt2)
  9567. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9568. tt2 (time-to-days (org-time-string-to-time t2)))
  9569. (let ((org-agenda-buffer-tmp-name
  9570. (format "*Org Agenda(a:%s)"
  9571. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9572. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9573. ((org-at-timestamp-p 'lax)
  9574. (let ((org-agenda-buffer-tmp-name
  9575. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9576. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9577. (substring (match-string 1) 0 10)))
  9578. 1)))
  9579. (t (error "This should not happen"))))
  9580. ;;; Following file links
  9581. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9582. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9583. (declare-function mailcap-mime-info
  9584. "mailcap" (string &optional request no-decode))
  9585. (defvar org-wait nil)
  9586. (defun org-open-file (path &optional in-emacs line search)
  9587. "Open the file at PATH.
  9588. First, this expands any special file name abbreviations. Then the
  9589. configuration variable `org-file-apps' is checked if it contains an
  9590. entry for this file type, and if yes, the corresponding command is launched.
  9591. If no application is found, Emacs simply visits the file.
  9592. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9593. With a double \\[universal-argument] \\[universal-argument] \
  9594. prefix arg, Org tries to avoid opening in Emacs
  9595. and to use an external application to visit the file.
  9596. Optional LINE specifies a line to go to, optional SEARCH a string
  9597. to search for. If LINE or SEARCH is given, the file will be
  9598. opened in Emacs, unless an entry from org-file-apps that makes
  9599. use of groups in a regexp matches.
  9600. If you want to change the way frames are used when following a
  9601. link, please customize `org-link-frame-setup'.
  9602. If the file does not exist, an error is thrown."
  9603. (let* ((file (if (equal path "")
  9604. buffer-file-name
  9605. (substitute-in-file-name (expand-file-name path))))
  9606. (file-apps (append org-file-apps (org-default-apps)))
  9607. (apps (cl-remove-if
  9608. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9609. (apps-dlink (cl-remove-if-not
  9610. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9611. (remp (and (assq 'remote apps) (file-remote-p file)))
  9612. (dirp (unless remp (file-directory-p file)))
  9613. (file (if (and dirp org-open-directory-means-index-dot-org)
  9614. (concat (file-name-as-directory file) "index.org")
  9615. file))
  9616. (a-m-a-p (assq 'auto-mode apps))
  9617. (dfile (downcase file))
  9618. ;; Reconstruct the original link from the PATH, LINE and
  9619. ;; SEARCH args.
  9620. (link (cond (line (concat file "::" (number-to-string line)))
  9621. (search (concat file "::" search))
  9622. (t file)))
  9623. (dlink (downcase link))
  9624. (ext
  9625. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9626. (match-string 1 dfile)))
  9627. (save-position-maybe
  9628. (let ((old-buffer (current-buffer))
  9629. (old-pos (point))
  9630. (old-mode major-mode))
  9631. (lambda ()
  9632. (and (derived-mode-p 'org-mode)
  9633. (eq old-mode 'org-mode)
  9634. (or (not (eq old-buffer (current-buffer)))
  9635. (not (eq old-pos (point))))
  9636. (org-mark-ring-push old-pos old-buffer)))))
  9637. cmd link-match-data)
  9638. (cond
  9639. ((member in-emacs '((16) system))
  9640. (setq cmd (cdr (assq 'system apps))))
  9641. (in-emacs (setq cmd 'emacs))
  9642. (t
  9643. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9644. (and dirp (cdr (assq 'directory apps)))
  9645. ;; First, try matching against apps-dlink if we
  9646. ;; get a match here, store the match data for
  9647. ;; later.
  9648. (let ((match (assoc-default dlink apps-dlink
  9649. 'string-match)))
  9650. (if match
  9651. (progn (setq link-match-data (match-data))
  9652. match)
  9653. (progn (setq in-emacs (or in-emacs line search))
  9654. nil))) ; if we have no match in apps-dlink,
  9655. ; always open the file in emacs if line or search
  9656. ; is given (for backwards compatibility)
  9657. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9658. 'string-match)
  9659. (cdr (assoc ext apps))
  9660. (cdr (assq t apps))))))
  9661. (when (eq cmd 'system)
  9662. (setq cmd (cdr (assq 'system apps))))
  9663. (when (eq cmd 'default)
  9664. (setq cmd (cdr (assoc t apps))))
  9665. (when (eq cmd 'mailcap)
  9666. (require 'mailcap)
  9667. (mailcap-parse-mailcaps)
  9668. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9669. (command (mailcap-mime-info mime-type)))
  9670. (if (stringp command)
  9671. (setq cmd command)
  9672. (setq cmd 'emacs))))
  9673. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9674. (not (file-exists-p file))
  9675. (not org-open-non-existing-files))
  9676. (user-error "No such file: %s" file))
  9677. (cond
  9678. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9679. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9680. (while (string-match "['\"]%s['\"]" cmd)
  9681. (setq cmd (replace-match "%s" t t cmd)))
  9682. (setq cmd (replace-regexp-in-string
  9683. "%s"
  9684. (shell-quote-argument (convert-standard-filename file))
  9685. cmd
  9686. nil t))
  9687. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9688. (save-match-data
  9689. (let ((match-index 1)
  9690. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9691. (set-match-data link-match-data)
  9692. (while (<= match-index number-of-groups)
  9693. (let ((regex (concat "%" (number-to-string match-index)))
  9694. (replace-with (match-string match-index dlink)))
  9695. (while (string-match regex cmd)
  9696. (setq cmd (replace-match replace-with t t cmd))))
  9697. (setq match-index (+ match-index 1)))))
  9698. (save-window-excursion
  9699. (message "Running %s...done" cmd)
  9700. (start-process-shell-command cmd nil cmd)
  9701. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9702. ((or (stringp cmd)
  9703. (eq cmd 'emacs))
  9704. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9705. (widen)
  9706. (cond (line (org-goto-line line)
  9707. (when (derived-mode-p 'org-mode) (org-reveal)))
  9708. (search (condition-case err
  9709. (org-link-search search)
  9710. ;; Save position before error-ing out so user
  9711. ;; can easily move back to the original buffer.
  9712. (error (funcall save-position-maybe)
  9713. (error (nth 1 err)))))))
  9714. ((functionp cmd)
  9715. (save-match-data
  9716. (set-match-data link-match-data)
  9717. (condition-case nil
  9718. (funcall cmd file link)
  9719. ;; FIXME: Remove this check when most default installations
  9720. ;; of Emacs have at least Org 9.0.
  9721. ((debug wrong-number-of-arguments wrong-type-argument
  9722. invalid-function)
  9723. (user-error "Please see Org News for version 9.0 about \
  9724. `org-file-apps'--Lisp error: %S" cmd)))))
  9725. ((consp cmd)
  9726. ;; FIXME: Remove this check when most default installations of
  9727. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9728. ;; fall back to `org-link-frame-setup' for an old usage of
  9729. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9730. (user-error "Please see Org News for version 9.0 about \
  9731. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9732. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9733. (funcall save-position-maybe)))
  9734. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9735. "This function returns non-nil if `entry' uses a regular
  9736. expression which should be matched against the whole link by
  9737. org-open-file.
  9738. It assumes that is the case when the entry uses a regular
  9739. expression which has at least one grouping construct and the
  9740. action is either a lisp form or a command string containing
  9741. `%1', i.e. using at least one subexpression match as a
  9742. parameter."
  9743. (let ((selector (car entry))
  9744. (action (cdr entry)))
  9745. (if (stringp selector)
  9746. (and (> (regexp-opt-depth selector) 0)
  9747. (or (and (stringp action)
  9748. (string-match "%[0-9]" action))
  9749. (consp action)))
  9750. nil)))
  9751. (defun org-default-apps ()
  9752. "Return the default applications for this operating system."
  9753. (cond
  9754. ((eq system-type 'darwin)
  9755. org-file-apps-defaults-macosx)
  9756. ((eq system-type 'windows-nt)
  9757. org-file-apps-defaults-windowsnt)
  9758. (t org-file-apps-defaults-gnu)))
  9759. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9760. "Convert extensions to regular expressions in the cars of LIST.
  9761. Also, weed out any non-string entries, because the return value is used
  9762. only for regexp matching.
  9763. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9764. point to the symbol `emacs', indicating that the file should
  9765. be opened in Emacs."
  9766. (append
  9767. (delq nil
  9768. (mapcar (lambda (x)
  9769. (unless (not (stringp (car x)))
  9770. (if (string-match "\\W" (car x))
  9771. x
  9772. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9773. list))
  9774. (when add-auto-mode
  9775. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9776. ;;;; Refiling
  9777. (defun org-get-org-file ()
  9778. "Read a filename, with default directory `org-directory'."
  9779. (let ((default (or org-default-notes-file remember-data-file)))
  9780. (read-file-name (format "File name [%s]: " default)
  9781. (file-name-as-directory org-directory)
  9782. default)))
  9783. (defun org-notes-order-reversed-p ()
  9784. "Check if the current file should receive notes in reversed order."
  9785. (cond
  9786. ((not org-reverse-note-order) nil)
  9787. ((eq t org-reverse-note-order) t)
  9788. ((not (listp org-reverse-note-order)) nil)
  9789. (t (catch 'exit
  9790. (dolist (entry org-reverse-note-order)
  9791. (when (string-match (car entry) buffer-file-name)
  9792. (throw 'exit (cdr entry))))))))
  9793. (defvar org-refile-target-table nil
  9794. "The list of refile targets, created by `org-refile'.")
  9795. (defvar org-agenda-new-buffers nil
  9796. "Buffers created to visit agenda files.")
  9797. (defvar org-refile-cache nil
  9798. "Cache for refile targets.")
  9799. (defvar org-refile-markers nil
  9800. "All the markers used for caching refile locations.")
  9801. (defun org-refile-marker (pos)
  9802. "Get a new refile marker, but only if caching is in use."
  9803. (if (not org-refile-use-cache)
  9804. pos
  9805. (let ((m (make-marker)))
  9806. (move-marker m pos)
  9807. (push m org-refile-markers)
  9808. m)))
  9809. (defun org-refile-cache-clear ()
  9810. "Clear the refile cache and disable all the markers."
  9811. (dolist (m org-refile-markers) (move-marker m nil))
  9812. (setq org-refile-markers nil)
  9813. (setq org-refile-cache nil)
  9814. (message "Refile cache has been cleared"))
  9815. (defun org-refile-cache-check-set (set)
  9816. "Check if all the markers in the cache still have live buffers."
  9817. (let (marker)
  9818. (catch 'exit
  9819. (while (and set (setq marker (nth 3 (pop set))))
  9820. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9821. (when (and marker (null (marker-buffer marker)))
  9822. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9823. (sit-for 3)
  9824. (throw 'exit nil)))
  9825. t)))
  9826. (defun org-refile-cache-put (set &rest identifiers)
  9827. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9828. (let* ((key (sha1 (prin1-to-string identifiers)))
  9829. (entry (assoc key org-refile-cache)))
  9830. (if entry
  9831. (setcdr entry set)
  9832. (push (cons key set) org-refile-cache))))
  9833. (defun org-refile-cache-get (&rest identifiers)
  9834. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9835. (cond
  9836. ((not org-refile-cache) nil)
  9837. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9838. (t
  9839. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9840. org-refile-cache))))
  9841. (and set (org-refile-cache-check-set set) set)))))
  9842. (defvar org-outline-path-cache nil
  9843. "Alist between buffer positions and outline paths.
  9844. It value is an alist (POSITION . PATH) where POSITION is the
  9845. buffer position at the beginning of an entry and PATH is a list
  9846. of strings describing the outline path for that entry, in reverse
  9847. order.")
  9848. (defun org-refile-get-targets (&optional default-buffer)
  9849. "Produce a table with refile targets."
  9850. (let ((case-fold-search nil)
  9851. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9852. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9853. targets tgs files desc descre)
  9854. (message "Getting targets...")
  9855. (with-current-buffer (or default-buffer (current-buffer))
  9856. (dolist (entry entries)
  9857. (setq files (car entry) desc (cdr entry))
  9858. (cond
  9859. ((null files) (setq files (list (current-buffer))))
  9860. ((eq files 'org-agenda-files)
  9861. (setq files (org-agenda-files 'unrestricted)))
  9862. ((and (symbolp files) (fboundp files))
  9863. (setq files (funcall files)))
  9864. ((and (symbolp files) (boundp files))
  9865. (setq files (symbol-value files))))
  9866. (when (stringp files) (setq files (list files)))
  9867. (cond
  9868. ((eq (car desc) :tag)
  9869. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9870. ((eq (car desc) :todo)
  9871. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9872. ((eq (car desc) :regexp)
  9873. (setq descre (cdr desc)))
  9874. ((eq (car desc) :level)
  9875. (setq descre (concat "^\\*\\{" (number-to-string
  9876. (if org-odd-levels-only
  9877. (1- (* 2 (cdr desc)))
  9878. (cdr desc)))
  9879. "\\}[ \t]")))
  9880. ((eq (car desc) :maxlevel)
  9881. (setq descre (concat "^\\*\\{1," (number-to-string
  9882. (if org-odd-levels-only
  9883. (1- (* 2 (cdr desc)))
  9884. (cdr desc)))
  9885. "\\}[ \t]")))
  9886. (t (error "Bad refiling target description %s" desc)))
  9887. (dolist (f files)
  9888. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9889. (or
  9890. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9891. (progn
  9892. (when (bufferp f)
  9893. (setq f (buffer-file-name (buffer-base-buffer f))))
  9894. (setq f (and f (expand-file-name f)))
  9895. (when (eq org-refile-use-outline-path 'file)
  9896. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9897. (when (eq org-refile-use-outline-path 'buffer-name)
  9898. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9899. (when (eq org-refile-use-outline-path 'full-file-path)
  9900. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9901. (org-with-wide-buffer
  9902. (goto-char (point-min))
  9903. (setq org-outline-path-cache nil)
  9904. (while (re-search-forward descre nil t)
  9905. (beginning-of-line)
  9906. (let ((case-fold-search nil))
  9907. (looking-at org-complex-heading-regexp))
  9908. (let ((begin (point))
  9909. (heading (match-string-no-properties 4)))
  9910. (unless (or (and
  9911. org-refile-target-verify-function
  9912. (not
  9913. (funcall org-refile-target-verify-function)))
  9914. (not heading))
  9915. (let ((re (format org-complex-heading-regexp-format
  9916. (regexp-quote heading)))
  9917. (target
  9918. (if (not org-refile-use-outline-path) heading
  9919. (mapconcat
  9920. #'identity
  9921. (append
  9922. (pcase org-refile-use-outline-path
  9923. (`file (list (file-name-nondirectory
  9924. (buffer-file-name
  9925. (buffer-base-buffer)))))
  9926. (`full-file-path
  9927. (list (buffer-file-name
  9928. (buffer-base-buffer))))
  9929. (`buffer-name
  9930. (list (buffer-name
  9931. (buffer-base-buffer))))
  9932. (_ nil))
  9933. (mapcar (lambda (s) (replace-regexp-in-string
  9934. "/" "\\/" s nil t))
  9935. (org-get-outline-path t t)))
  9936. "/"))))
  9937. (push (list target f re (org-refile-marker (point)))
  9938. tgs)))
  9939. (when (= (point) begin)
  9940. ;; Verification function has not moved point.
  9941. (end-of-line)))))))
  9942. (when org-refile-use-cache
  9943. (org-refile-cache-put tgs (buffer-file-name) descre))
  9944. (setq targets (append tgs targets))))))
  9945. (message "Getting targets...done")
  9946. (delete-dups (nreverse targets))))
  9947. (defun org--get-outline-path-1 (&optional use-cache)
  9948. "Return outline path to current headline.
  9949. Outline path is a list of strings, in reverse order. When
  9950. optional argument USE-CACHE is non-nil, make use of a cache. See
  9951. `org-get-outline-path' for details.
  9952. Assume buffer is widened and point is on a headline."
  9953. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9954. (let ((p (point))
  9955. (heading (let ((case-fold-search nil))
  9956. (looking-at org-complex-heading-regexp)
  9957. (if (not (match-end 4)) ""
  9958. ;; Remove statistics cookies.
  9959. (org-trim
  9960. (org-link-display-format
  9961. (replace-regexp-in-string
  9962. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9963. (match-string-no-properties 4))))))))
  9964. (if (org-up-heading-safe)
  9965. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9966. (when use-cache
  9967. (push (cons p path) org-outline-path-cache))
  9968. path)
  9969. ;; This is a new root node. Since we assume we are moving
  9970. ;; forward, we can drop previous cache so as to limit number
  9971. ;; of associations there.
  9972. (let ((path (list heading)))
  9973. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9974. path)))))
  9975. (defun org-get-outline-path (&optional with-self use-cache)
  9976. "Return the outline path to the current entry.
  9977. An outline path is a list of ancestors for current headline, as
  9978. a list of strings. Statistics cookies are removed and links are
  9979. replaced with their description, if any, or their path otherwise.
  9980. When optional argument WITH-SELF is non-nil, the path also
  9981. includes the current headline.
  9982. When optional argument USE-CACHE is non-nil, cache outline paths
  9983. between calls to this function so as to avoid backtracking. This
  9984. argument is useful when planning to find more than one outline
  9985. path in the same document. In that case, there are two
  9986. conditions to satisfy:
  9987. - `org-outline-path-cache' is set to nil before starting the
  9988. process;
  9989. - outline paths are computed by increasing buffer positions."
  9990. (org-with-wide-buffer
  9991. (and (or (and with-self (org-back-to-heading t))
  9992. (org-up-heading-safe))
  9993. (reverse (org--get-outline-path-1 use-cache)))))
  9994. (defun org-format-outline-path (path &optional width prefix separator)
  9995. "Format the outline path PATH for display.
  9996. WIDTH is the maximum number of characters that is available.
  9997. PREFIX is a prefix to be included in the returned string,
  9998. such as the file name.
  9999. SEPARATOR is inserted between the different parts of the path,
  10000. the default is \"/\"."
  10001. (setq width (or width 79))
  10002. (setq path (delq nil path))
  10003. (unless (> width 0)
  10004. (user-error "Argument `width' must be positive"))
  10005. (setq separator (or separator "/"))
  10006. (let* ((org-odd-levels-only nil)
  10007. (fpath (concat
  10008. prefix (and prefix path separator)
  10009. (mapconcat
  10010. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10011. (cl-loop for head in path
  10012. for n from 0
  10013. collect (org-add-props
  10014. head nil 'face
  10015. (nth (% n org-n-level-faces) org-level-faces)))
  10016. separator))))
  10017. (when (> (length fpath) width)
  10018. (if (< width 7)
  10019. ;; It's unlikely that `width' will be this small, but don't
  10020. ;; waste characters by adding ".." if it is.
  10021. (setq fpath (substring fpath 0 width))
  10022. (setf (substring fpath (- width 2)) "..")))
  10023. fpath))
  10024. (defun org-display-outline-path (&optional file current separator just-return-string)
  10025. "Display the current outline path in the echo area.
  10026. If FILE is non-nil, prepend the output with the file name.
  10027. If CURRENT is non-nil, append the current heading to the output.
  10028. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10029. the different parts of the path and defaults to \"/\".
  10030. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10031. (interactive "P")
  10032. (let* (case-fold-search
  10033. (bfn (buffer-file-name (buffer-base-buffer)))
  10034. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10035. res)
  10036. (when current (setq path (append path
  10037. (save-excursion
  10038. (org-back-to-heading t)
  10039. (when (looking-at org-complex-heading-regexp)
  10040. (list (match-string 4)))))))
  10041. (setq res
  10042. (org-format-outline-path
  10043. path
  10044. (1- (frame-width))
  10045. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10046. separator))
  10047. (if just-return-string
  10048. (org-no-properties res)
  10049. (org-unlogged-message "%s" res))))
  10050. (defvar org-refile-history nil
  10051. "History for refiling operations.")
  10052. (defvar org-after-refile-insert-hook nil
  10053. "Hook run after `org-refile' has inserted its stuff at the new location.
  10054. Note that this is still *before* the stuff will be removed from
  10055. the *old* location.")
  10056. (defvar org-capture-last-stored-marker)
  10057. (defvar org-refile-keep nil
  10058. "Non-nil means `org-refile' will copy instead of refile.")
  10059. (defun org-copy ()
  10060. "Like `org-refile', but copy."
  10061. (interactive)
  10062. (let ((org-refile-keep t))
  10063. (org-refile nil nil nil "Copy")))
  10064. (defun org-refile (&optional arg default-buffer rfloc msg)
  10065. "Move the entry or entries at point to another heading.
  10066. The list of target headings is compiled using the information in
  10067. `org-refile-targets', which see.
  10068. At the target location, the entry is filed as a subitem of the
  10069. target heading. Depending on `org-reverse-note-order', the new
  10070. subitem will either be the first or the last subitem.
  10071. If there is an active region, all entries in that region will be
  10072. refiled. However, the region must fulfill the requirement that
  10073. the first heading sets the top-level of the moved text.
  10074. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10075. location
  10076. and not actually move anything.
  10077. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10078. location where the last
  10079. refiling operation has put the subtree.
  10080. With a numeric prefix argument of `2', refile to the running clock.
  10081. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10082. being set to t and copy to the target location, don't move it.
  10083. Beware that keeping refiled entries may result in duplicated ID
  10084. properties.
  10085. RFLOC can be a refile location obtained in a different way.
  10086. MSG is a string to replace \"Refile\" in the default prompt with
  10087. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10088. See also `org-refile-use-outline-path'.
  10089. If you are using target caching (see `org-refile-use-cache'), you
  10090. have to clear the target cache in order to find new targets.
  10091. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10092. prefix argument (`C-u C-u C-u C-c C-w')."
  10093. (interactive "P")
  10094. (if (member arg '(0 (64)))
  10095. (org-refile-cache-clear)
  10096. (let* ((actionmsg (cond (msg msg)
  10097. ((equal arg 3) "Refile (and keep)")
  10098. (t "Refile")))
  10099. (regionp (org-region-active-p))
  10100. (region-start (and regionp (region-beginning)))
  10101. (region-end (and regionp (region-end)))
  10102. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10103. pos it nbuf file level reversed)
  10104. (setq last-command nil)
  10105. (when regionp
  10106. (goto-char region-start)
  10107. (or (bolp) (goto-char (point-at-bol)))
  10108. (setq region-start (point))
  10109. (unless (or (org-kill-is-subtree-p
  10110. (buffer-substring region-start region-end))
  10111. (prog1 org-refile-active-region-within-subtree
  10112. (let ((s (point-at-eol)))
  10113. (org-toggle-heading)
  10114. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10115. (user-error "The region is not a (sequence of) subtree(s)")))
  10116. (if (equal arg '(16))
  10117. (org-refile-goto-last-stored)
  10118. (when (or
  10119. (and (equal arg 2)
  10120. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10121. (prog1
  10122. (setq it (list (or org-clock-heading "running clock")
  10123. (buffer-file-name
  10124. (marker-buffer org-clock-hd-marker))
  10125. ""
  10126. (marker-position org-clock-hd-marker)))
  10127. (setq arg nil)))
  10128. (setq it
  10129. (or rfloc
  10130. (let (heading-text)
  10131. (save-excursion
  10132. (unless (and arg (listp arg))
  10133. (org-back-to-heading t)
  10134. (setq heading-text
  10135. (replace-regexp-in-string
  10136. org-bracket-link-regexp
  10137. "\\3"
  10138. (or (nth 4 (org-heading-components))
  10139. ""))))
  10140. (org-refile-get-location
  10141. (cond ((and arg (listp arg)) "Goto")
  10142. (regionp (concat actionmsg " region to"))
  10143. (t (concat actionmsg " subtree \""
  10144. heading-text "\" to")))
  10145. default-buffer
  10146. (and (not (equal '(4) arg))
  10147. org-refile-allow-creating-parent-nodes)))))))
  10148. (setq file (nth 1 it)
  10149. pos (nth 3 it))
  10150. (when (and (not arg)
  10151. pos
  10152. (equal (buffer-file-name) file)
  10153. (if regionp
  10154. (and (>= pos region-start)
  10155. (<= pos region-end))
  10156. (and (>= pos (point))
  10157. (< pos (save-excursion
  10158. (org-end-of-subtree t t))))))
  10159. (error "Cannot refile to position inside the tree or region"))
  10160. (setq nbuf (or (find-buffer-visiting file)
  10161. (find-file-noselect file)))
  10162. (if (and arg (not (equal arg 3)))
  10163. (progn
  10164. (pop-to-buffer-same-window nbuf)
  10165. (goto-char (cond (pos)
  10166. ((org-notes-order-reversed-p) (point-min))
  10167. (t (point-max))))
  10168. (org-show-context 'org-goto))
  10169. (if regionp
  10170. (progn
  10171. (org-kill-new (buffer-substring region-start region-end))
  10172. (org-save-markers-in-region region-start region-end))
  10173. (org-copy-subtree 1 nil t))
  10174. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10175. (find-file-noselect file)))
  10176. (setq reversed (org-notes-order-reversed-p))
  10177. (org-with-wide-buffer
  10178. (if pos
  10179. (progn
  10180. (goto-char pos)
  10181. (setq level (org-get-valid-level (funcall outline-level) 1))
  10182. (goto-char
  10183. (if reversed
  10184. (or (outline-next-heading) (point-max))
  10185. (or (save-excursion (org-get-next-sibling))
  10186. (org-end-of-subtree t t)
  10187. (point-max)))))
  10188. (setq level 1)
  10189. (if (not reversed)
  10190. (goto-char (point-max))
  10191. (goto-char (point-min))
  10192. (or (outline-next-heading) (goto-char (point-max)))))
  10193. (unless (bolp) (newline))
  10194. (org-paste-subtree level nil nil t)
  10195. (when org-log-refile
  10196. (org-add-log-setup 'refile nil nil org-log-refile)
  10197. (unless (eq org-log-refile 'note)
  10198. (save-excursion (org-add-log-note))))
  10199. (and org-auto-align-tags
  10200. (let ((org-loop-over-headlines-in-active-region nil))
  10201. (org-align-tags)))
  10202. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10203. :last-refile)))
  10204. (when bookmark-name
  10205. (with-demoted-errors
  10206. (bookmark-set bookmark-name))))
  10207. ;; If we are refiling for capture, make sure that the
  10208. ;; last-capture pointers point here
  10209. (when (bound-and-true-p org-capture-is-refiling)
  10210. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10211. :last-capture-marker)))
  10212. (when bookmark-name
  10213. (with-demoted-errors
  10214. (bookmark-set bookmark-name))))
  10215. (move-marker org-capture-last-stored-marker (point)))
  10216. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10217. (run-hooks 'org-after-refile-insert-hook)))
  10218. (unless org-refile-keep
  10219. (if regionp
  10220. (delete-region (point) (+ (point) (- region-end region-start)))
  10221. (org-preserve-local-variables
  10222. (delete-region
  10223. (and (org-back-to-heading t) (point))
  10224. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10225. (when (featurep 'org-inlinetask)
  10226. (org-inlinetask-remove-END-maybe))
  10227. (setq org-markers-to-move nil)
  10228. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10229. (defun org-refile-goto-last-stored ()
  10230. "Go to the location where the last refile was stored."
  10231. (interactive)
  10232. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10233. (message "This is the location of the last refile"))
  10234. (defun org-refile--get-location (refloc tbl)
  10235. "When user refile to REFLOC, find the associated target in TBL.
  10236. Also check `org-refile-target-table'."
  10237. (car (delq
  10238. nil
  10239. (mapcar
  10240. (lambda (r) (or (assoc r tbl)
  10241. (assoc r org-refile-target-table)))
  10242. (list (replace-regexp-in-string "/$" "" refloc)
  10243. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10244. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10245. "Prompt the user for a refile location, using PROMPT.
  10246. PROMPT should not be suffixed with a colon and a space, because
  10247. this function appends the default value from
  10248. `org-refile-history' automatically, if that is not empty."
  10249. (let ((org-refile-targets org-refile-targets)
  10250. (org-refile-use-outline-path org-refile-use-outline-path))
  10251. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10252. (unless org-refile-target-table
  10253. (user-error "No refile targets"))
  10254. (let* ((cbuf (current-buffer))
  10255. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10256. (cfunc (if (and org-refile-use-outline-path
  10257. org-outline-path-complete-in-steps)
  10258. #'org-olpath-completing-read
  10259. #'completing-read))
  10260. (extra (if org-refile-use-outline-path "/" ""))
  10261. (cbnex (concat (buffer-name) extra))
  10262. (filename (and cfn (expand-file-name cfn)))
  10263. (tbl (mapcar
  10264. (lambda (x)
  10265. (if (and (not (member org-refile-use-outline-path
  10266. '(file full-file-path)))
  10267. (not (equal filename (nth 1 x))))
  10268. (cons (concat (car x) extra " ("
  10269. (file-name-nondirectory (nth 1 x)) ")")
  10270. (cdr x))
  10271. (cons (concat (car x) extra) (cdr x))))
  10272. org-refile-target-table))
  10273. (completion-ignore-case t)
  10274. cdef
  10275. (prompt (concat prompt
  10276. (or (and (car org-refile-history)
  10277. (concat " (default " (car org-refile-history) ")"))
  10278. (and (assoc cbnex tbl) (setq cdef cbnex)
  10279. (concat " (default " cbnex ")"))) ": "))
  10280. pa answ parent-target child parent old-hist)
  10281. (setq old-hist org-refile-history)
  10282. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10283. nil 'org-refile-history (or cdef (car org-refile-history))))
  10284. (if (setq pa (org-refile--get-location answ tbl))
  10285. (progn
  10286. (org-refile-check-position pa)
  10287. (when (or (not org-refile-history)
  10288. (not (eq old-hist org-refile-history))
  10289. (not (equal (car pa) (car org-refile-history))))
  10290. (setq org-refile-history
  10291. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10292. org-refile-history
  10293. (cdr org-refile-history))))
  10294. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10295. (pop org-refile-history)))
  10296. pa)
  10297. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10298. (progn
  10299. (setq parent (match-string 1 answ)
  10300. child (match-string 2 answ))
  10301. (setq parent-target (org-refile--get-location parent tbl))
  10302. (when (and parent-target
  10303. (or (eq new-nodes t)
  10304. (and (eq new-nodes 'confirm)
  10305. (y-or-n-p (format "Create new node \"%s\"? "
  10306. child)))))
  10307. (org-refile-new-child parent-target child)))
  10308. (user-error "Invalid target location")))))
  10309. (declare-function org-string-nw-p "org-macs" (s))
  10310. (defun org-refile-check-position (refile-pointer)
  10311. "Check if the refile pointer matches the headline to which it points."
  10312. (let* ((file (nth 1 refile-pointer))
  10313. (re (nth 2 refile-pointer))
  10314. (pos (nth 3 refile-pointer))
  10315. buffer)
  10316. (if (and (not (markerp pos)) (not file))
  10317. (user-error "Please indicate a target file in the refile path")
  10318. (when (org-string-nw-p re)
  10319. (setq buffer (if (markerp pos)
  10320. (marker-buffer pos)
  10321. (or (find-buffer-visiting file)
  10322. (find-file-noselect file))))
  10323. (with-current-buffer buffer
  10324. (org-with-wide-buffer
  10325. (goto-char pos)
  10326. (beginning-of-line 1)
  10327. (unless (looking-at-p re)
  10328. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10329. (defun org-refile-new-child (parent-target child)
  10330. "Use refile target PARENT-TARGET to add new CHILD below it."
  10331. (unless parent-target
  10332. (error "Cannot find parent for new node"))
  10333. (let ((file (nth 1 parent-target))
  10334. (pos (nth 3 parent-target))
  10335. level)
  10336. (with-current-buffer (or (find-buffer-visiting file)
  10337. (find-file-noselect file))
  10338. (org-with-wide-buffer
  10339. (if pos
  10340. (goto-char pos)
  10341. (goto-char (point-max))
  10342. (unless (bolp) (newline)))
  10343. (when (looking-at org-outline-regexp)
  10344. (setq level (funcall outline-level))
  10345. (org-end-of-subtree t t))
  10346. (org-back-over-empty-lines)
  10347. (insert "\n" (make-string
  10348. (if pos (org-get-valid-level level 1) 1) ?*)
  10349. " " child "\n")
  10350. (beginning-of-line 0)
  10351. (list (concat (car parent-target) "/" child) file "" (point))))))
  10352. (defun org-olpath-completing-read (prompt collection &rest args)
  10353. "Read an outline path like a file name."
  10354. (let ((thetable collection))
  10355. (apply #'completing-read
  10356. prompt
  10357. (lambda (string predicate &optional flag)
  10358. (cond
  10359. ((eq flag nil) (try-completion string thetable))
  10360. ((eq flag t)
  10361. (let ((l (length string)))
  10362. (mapcar (lambda (x)
  10363. (let ((r (substring x l))
  10364. (f (if (string-match " ([^)]*)$" x)
  10365. (match-string 0 x)
  10366. "")))
  10367. (if (string-match "/" r)
  10368. (concat string (substring r 0 (match-end 0)) f)
  10369. x)))
  10370. (all-completions string thetable predicate))))
  10371. ;; Exact match?
  10372. ((eq flag 'lambda) (assoc string thetable))))
  10373. args)))
  10374. ;;;; Dynamic blocks
  10375. (defun org-find-dblock (name)
  10376. "Find the first dynamic block with name NAME in the buffer.
  10377. If not found, stay at current position and return nil."
  10378. (let ((case-fold-search t) pos)
  10379. (save-excursion
  10380. (goto-char (point-min))
  10381. (setq pos (and (re-search-forward
  10382. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10383. (match-beginning 0))))
  10384. (when pos (goto-char pos))
  10385. pos))
  10386. (defun org-create-dblock (plist)
  10387. "Create a dynamic block section, with parameters taken from PLIST.
  10388. PLIST must contain a :name entry which is used as the name of the block."
  10389. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10390. (end-of-line 1)
  10391. (newline))
  10392. (let ((col (current-column))
  10393. (name (plist-get plist :name)))
  10394. (insert "#+BEGIN: " name)
  10395. (while plist
  10396. (if (eq (car plist) :name)
  10397. (setq plist (cddr plist))
  10398. (insert " " (prin1-to-string (pop plist)))))
  10399. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10400. (beginning-of-line -2)))
  10401. (defun org-prepare-dblock ()
  10402. "Prepare dynamic block for refresh.
  10403. This empties the block, puts the cursor at the insert position and returns
  10404. the property list including an extra property :name with the block name."
  10405. (unless (looking-at org-dblock-start-re)
  10406. (user-error "Not at a dynamic block"))
  10407. (let* ((begdel (1+ (match-end 0)))
  10408. (name (org-no-properties (match-string 1)))
  10409. (params (append (list :name name)
  10410. (read (concat "(" (match-string 3) ")")))))
  10411. (save-excursion
  10412. (beginning-of-line 1)
  10413. (skip-chars-forward " \t")
  10414. (setq params (plist-put params :indentation-column (current-column))))
  10415. (unless (re-search-forward org-dblock-end-re nil t)
  10416. (error "Dynamic block not terminated"))
  10417. (setq params
  10418. (append params
  10419. (list :content (buffer-substring
  10420. begdel (match-beginning 0)))))
  10421. (delete-region begdel (match-beginning 0))
  10422. (goto-char begdel)
  10423. (open-line 1)
  10424. params))
  10425. (defun org-map-dblocks (&optional command)
  10426. "Apply COMMAND to all dynamic blocks in the current buffer.
  10427. If COMMAND is not given, use `org-update-dblock'."
  10428. (let ((cmd (or command 'org-update-dblock)))
  10429. (save-excursion
  10430. (goto-char (point-min))
  10431. (while (re-search-forward org-dblock-start-re nil t)
  10432. (goto-char (match-beginning 0))
  10433. (save-excursion
  10434. (condition-case nil
  10435. (funcall cmd)
  10436. (error (message "Error during update of dynamic block"))))
  10437. (unless (re-search-forward org-dblock-end-re nil t)
  10438. (error "Dynamic block not terminated"))))))
  10439. (defun org-dblock-update (&optional arg)
  10440. "User command for updating dynamic blocks.
  10441. Update the dynamic block at point. With prefix ARG, update all dynamic
  10442. blocks in the buffer."
  10443. (interactive "P")
  10444. (if arg
  10445. (org-update-all-dblocks)
  10446. (or (looking-at org-dblock-start-re)
  10447. (org-beginning-of-dblock))
  10448. (org-update-dblock)))
  10449. (defun org-update-dblock ()
  10450. "Update the dynamic block at point.
  10451. This means to empty the block, parse for parameters and then call
  10452. the correct writing function."
  10453. (interactive)
  10454. (save-excursion
  10455. (let* ((win (selected-window))
  10456. (pos (point))
  10457. (line (org-current-line))
  10458. (params (org-prepare-dblock))
  10459. (name (plist-get params :name))
  10460. (indent (plist-get params :indentation-column))
  10461. (cmd (intern (concat "org-dblock-write:" name))))
  10462. (message "Updating dynamic block `%s' at line %d..." name line)
  10463. (funcall cmd params)
  10464. (message "Updating dynamic block `%s' at line %d...done" name line)
  10465. (goto-char pos)
  10466. (when (and indent (> indent 0))
  10467. (setq indent (make-string indent ?\ ))
  10468. (save-excursion
  10469. (select-window win)
  10470. (org-beginning-of-dblock)
  10471. (forward-line 1)
  10472. (while (not (looking-at org-dblock-end-re))
  10473. (insert indent)
  10474. (beginning-of-line 2))
  10475. (when (looking-at org-dblock-end-re)
  10476. (and (looking-at "[ \t]+")
  10477. (replace-match ""))
  10478. (insert indent)))))))
  10479. (defun org-beginning-of-dblock ()
  10480. "Find the beginning of the dynamic block at point.
  10481. Error if there is no such block at point."
  10482. (let ((pos (point))
  10483. beg)
  10484. (end-of-line 1)
  10485. (if (and (re-search-backward org-dblock-start-re nil t)
  10486. (setq beg (match-beginning 0))
  10487. (re-search-forward org-dblock-end-re nil t)
  10488. (> (match-end 0) pos))
  10489. (goto-char beg)
  10490. (goto-char pos)
  10491. (error "Not in a dynamic block"))))
  10492. (defun org-update-all-dblocks ()
  10493. "Update all dynamic blocks in the buffer.
  10494. This function can be used in a hook."
  10495. (interactive)
  10496. (when (derived-mode-p 'org-mode)
  10497. (org-map-dblocks 'org-update-dblock)))
  10498. ;;;; Completion
  10499. (declare-function org-export-backend-options "ox" (cl-x) t)
  10500. (defun org-get-export-keywords ()
  10501. "Return a list of all currently understood export keywords.
  10502. Export keywords include options, block names, attributes and
  10503. keywords relative to each registered export back-end."
  10504. (let (keywords)
  10505. (dolist (backend
  10506. (bound-and-true-p org-export-registered-backends)
  10507. (delq nil keywords))
  10508. ;; Back-end name (for keywords, like #+LATEX:)
  10509. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10510. (dolist (option-entry (org-export-backend-options backend))
  10511. ;; Back-end options.
  10512. (push (nth 1 option-entry) keywords)))))
  10513. (defconst org-options-keywords
  10514. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10515. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10516. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10517. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10518. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10519. (defcustom org-structure-template-alist
  10520. '(("a" . "export ascii")
  10521. ("c" . "center")
  10522. ("C" . "comment")
  10523. ("e" . "example")
  10524. ("E" . "export")
  10525. ("h" . "export html")
  10526. ("l" . "export latex")
  10527. ("q" . "quote")
  10528. ("s" . "src")
  10529. ("v" . "verse"))
  10530. "An alist of keys and block types.
  10531. `org-insert-structure-template' will display a menu with this
  10532. list of templates to choose from. The block type is inserted,
  10533. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  10534. The menu keys are defined by the car of each entry in this alist.
  10535. If two entries have the keys \"a\" and \"aa\" respectively, the
  10536. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10537. latter will be inserted by typing \"aa\". If an entry with the
  10538. key \"aab\" is later added, it can be inserted by typing \"ab\".
  10539. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10540. block can be inserted by pressing TAB after the string \"<KEY\"."
  10541. :group 'org-edit-structure
  10542. :type '(repeat
  10543. (cons (string :tag "Key")
  10544. (string :tag "Template")))
  10545. :package-version '(Org . "9.2"))
  10546. (defun org--check-org-structure-template-alist (&optional checklist)
  10547. "Check whether `org-structure-template-alist' is set up correctly.
  10548. In particular, check if the Org 9.2 format is used as opposed to
  10549. previous format.
  10550. "
  10551. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  10552. (or (eval checklist)
  10553. org-structure-template-alist))))
  10554. (when elm
  10555. (org-display-warning
  10556. (format "
  10557. Please update the entries of `%s'.
  10558. In Org 9.2 the format was changed from something like
  10559. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  10560. to something like
  10561. (\"s\" . \"src\")
  10562. Please refer to the documentation of `org-structure-template-alist'.
  10563. The following entries must be updated:
  10564. %s"
  10565. (or checklist 'org-structure-template-alist)
  10566. (pp-to-string elm))))))
  10567. (defun org--insert-structure-template-mks ()
  10568. "Present `org-structure-template-alist' with `org-mks'.
  10569. Menus are added if keys require more than one keystroke. Tabs
  10570. are added to single key entries when more than one stroke is
  10571. needed. Keys longer than two characters are reduced to two
  10572. characters."
  10573. (org--check-org-structure-template-alist)
  10574. (let* (case-fold-search
  10575. (templates (append org-structure-template-alist
  10576. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10577. (keys (mapcar #'car templates))
  10578. (start-letters
  10579. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10580. ;; Sort each element of `org-structure-template-alist' into
  10581. ;; sublists according to the first letter.
  10582. (superlist
  10583. (mapcar (lambda (letter)
  10584. (list letter
  10585. (cl-remove-if-not
  10586. (apply-partially #'string-match-p (concat "^" letter))
  10587. templates :key #'car)))
  10588. start-letters)))
  10589. (org-mks
  10590. (apply #'append
  10591. ;; Make an `org-mks' table. If only one element is
  10592. ;; present in a sublist, make it part of the top-menu,
  10593. ;; otherwise make a submenu according to the starting
  10594. ;; letter and populate it.
  10595. (mapcar (lambda (sublist)
  10596. (if (eq 1 (length (cadr sublist)))
  10597. (mapcar (lambda (elm)
  10598. (list (substring (car elm) 0 1)
  10599. (cdr elm) ""))
  10600. (cadr sublist))
  10601. ;; Create submenu.
  10602. (let* ((topkey (car sublist))
  10603. (elms (cadr sublist))
  10604. (keys (mapcar #'car elms))
  10605. (long (> (length elms) 3)))
  10606. (append
  10607. (list
  10608. ;; Make a description of the submenu.
  10609. (list topkey
  10610. (concat
  10611. (mapconcat #'cdr
  10612. (cl-subseq elms 0 (if long 3 (length elms)))
  10613. ", ")
  10614. (when long ", ..."))))
  10615. ;; List of entries in submenu.
  10616. (cl-mapcar #'list
  10617. (org--insert-structure-template-unique-keys keys)
  10618. (mapcar #'cdr elms)
  10619. (make-list (length elms) ""))))))
  10620. superlist))
  10621. "Select a key\n============"
  10622. "Key: ")))
  10623. (defun org--insert-structure-template-unique-keys (keys)
  10624. "Make a list of unique, two characters long elements from KEYS.
  10625. Elements of length one have a tab appended. Elements of length
  10626. two are kept as is. Longer elements are truncated to length two.
  10627. If an element cannot be made unique, an error is raised."
  10628. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10629. menu-keys)
  10630. (dolist (key orderd-keys)
  10631. (let ((potential-key
  10632. (cl-case (length key)
  10633. (1 (concat key "\t"))
  10634. (2 key)
  10635. (otherwise
  10636. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10637. (mapcar (apply-partially #'concat (substring key 0 1))
  10638. (split-string (substring key 1) "" t)))))))
  10639. (if (or (not potential-key) (assoc potential-key menu-keys))
  10640. (user-error "Could not make unique key for %s." key)
  10641. (push (cons potential-key key) menu-keys))))
  10642. (mapcar #'car
  10643. (cl-sort menu-keys #'<
  10644. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10645. (defun org-insert-structure-template (type)
  10646. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10647. Select a block from `org-structure-template-alist' then type
  10648. either RET, TAB or SPC to write the block type. With an active
  10649. region, wrap the region in the block. Otherwise, insert an empty
  10650. block."
  10651. (interactive
  10652. (list (pcase (org--insert-structure-template-mks)
  10653. (`("\t" . ,_) (read-string "Structure type: "))
  10654. (`(,_ ,choice . ,_) choice))))
  10655. (let* ((region? (use-region-p))
  10656. (region-start (and region? (region-beginning)))
  10657. (region-end (and region? (copy-marker (region-end))))
  10658. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  10659. (verbatim? (string-match-p
  10660. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10661. type)))
  10662. (when region? (goto-char region-start))
  10663. (let ((column (current-indentation)))
  10664. (if (save-excursion (skip-chars-backward " \t") (bolp))
  10665. (beginning-of-line)
  10666. (insert "\n"))
  10667. (save-excursion
  10668. (indent-to column)
  10669. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  10670. (when region?
  10671. (when verbatim? (org-escape-code-in-region (point) region-end))
  10672. (goto-char region-end)
  10673. ;; Ignore empty lines at the end of the region.
  10674. (skip-chars-backward " \r\t\n")
  10675. (end-of-line))
  10676. (unless (bolp) (insert "\n"))
  10677. (indent-to column)
  10678. (insert (format "#+end_%s" (car (split-string type))))
  10679. (if (looking-at "[ \t]*$") (replace-match "")
  10680. (insert "\n"))
  10681. (when (and (eobp) (not (bolp))) (insert "\n")))
  10682. (if extended? (end-of-line)
  10683. (forward-line)
  10684. (skip-chars-forward " \t")))))
  10685. ;;;; TODO, DEADLINE, Comments
  10686. (defun org-toggle-comment ()
  10687. "Change the COMMENT state of an entry."
  10688. (interactive)
  10689. (save-excursion
  10690. (org-back-to-heading)
  10691. (let ((case-fold-search nil))
  10692. (looking-at org-complex-heading-regexp))
  10693. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10694. (skip-chars-forward " \t")
  10695. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10696. (if (org-in-commented-heading-p t)
  10697. (delete-region (point)
  10698. (progn (search-forward " " (line-end-position) 'move)
  10699. (skip-chars-forward " \t")
  10700. (point)))
  10701. (insert org-comment-string)
  10702. (unless (eolp) (insert " ")))))
  10703. (defvar org-last-todo-state-is-todo nil
  10704. "This is non-nil when the last TODO state change led to a TODO state.
  10705. If the last change removed the TODO tag or switched to DONE, then
  10706. this is nil.")
  10707. (defvar org-todo-setup-filter-hook nil
  10708. "Hook for functions that pre-filter todo specs.
  10709. Each function takes a todo spec and returns either nil or the spec
  10710. transformed into canonical form." )
  10711. (defvar org-todo-get-default-hook nil
  10712. "Hook for functions that get a default item for todo.
  10713. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10714. nil or a string to be used for the todo mark." )
  10715. (defvar org-agenda-headline-snapshot-before-repeat)
  10716. (defun org-current-effective-time ()
  10717. "Return current time adjusted for `org-extend-today-until' variable."
  10718. (let* ((ct (org-current-time))
  10719. (dct (decode-time ct))
  10720. (ct1
  10721. (cond
  10722. (org-use-last-clock-out-time-as-effective-time
  10723. (or (org-clock-get-last-clock-out-time) ct))
  10724. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10725. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10726. (t ct))))
  10727. ct1))
  10728. (defun org-todo-yesterday (&optional arg)
  10729. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10730. (interactive "P")
  10731. (if (eq major-mode 'org-agenda-mode)
  10732. (apply 'org-agenda-todo-yesterday arg)
  10733. (let* ((org-use-effective-time t)
  10734. (hour (nth 2 (decode-time (org-current-time))))
  10735. (org-extend-today-until (1+ hour)))
  10736. (org-todo arg))))
  10737. (defvar org-block-entry-blocking ""
  10738. "First entry preventing the TODO state change.")
  10739. (defun org-cancel-repeater ()
  10740. "Cancel a repeater by setting its numeric value to zero."
  10741. (interactive)
  10742. (save-excursion
  10743. (org-back-to-heading t)
  10744. (let ((bound1 (point))
  10745. (bound0 (save-excursion (outline-next-heading) (point))))
  10746. (when (and (re-search-forward
  10747. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10748. org-deadline-time-regexp "\\)\\|\\("
  10749. org-ts-regexp "\\)")
  10750. bound0 t)
  10751. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10752. bound1 t))
  10753. (replace-match "0" t nil nil 1)))))
  10754. (defvar org-state)
  10755. (defvar org-blocked-by-checkboxes)
  10756. (defun org-todo (&optional arg)
  10757. "Change the TODO state of an item.
  10758. The state of an item is given by a keyword at the start of the heading,
  10759. like
  10760. *** TODO Write paper
  10761. *** DONE Call mom
  10762. The different keywords are specified in the variable `org-todo-keywords'.
  10763. By default the available states are \"TODO\" and \"DONE\". So, for this
  10764. example: when the item starts with TODO, it is changed to DONE.
  10765. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10766. DONE are present, add TODO at the beginning of the heading.
  10767. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10768. state.
  10769. With numeric prefix ARG, switch to that state.
  10770. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10771. next set of TODO \
  10772. keywords (nextset).
  10773. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10774. prefix, circumvent any state blocking.
  10775. With a numeric prefix arg of 0, inhibit note taking for the change.
  10776. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10777. When called through ELisp, arg is also interpreted in the following way:
  10778. `none' -> empty state
  10779. \"\" -> switch to empty state
  10780. `done' -> switch to DONE
  10781. `nextset' -> switch to the next set of keywords
  10782. `previousset' -> switch to the previous set of keywords
  10783. \"WAITING\" -> switch to the specified keyword, but only if it
  10784. really is a member of `org-todo-keywords'."
  10785. (interactive "P")
  10786. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10787. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10788. 'region-start-level 'region))
  10789. org-loop-over-headlines-in-active-region)
  10790. (org-map-entries
  10791. `(org-todo ,arg)
  10792. org-loop-over-headlines-in-active-region
  10793. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10794. (when (equal arg '(16)) (setq arg 'nextset))
  10795. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10796. (let ((org-blocker-hook org-blocker-hook)
  10797. commentp
  10798. case-fold-search)
  10799. (when (equal arg '(64))
  10800. (setq arg nil org-blocker-hook nil))
  10801. (when (and org-blocker-hook
  10802. (or org-inhibit-blocking
  10803. (org-entry-get nil "NOBLOCKING")))
  10804. (setq org-blocker-hook nil))
  10805. (save-excursion
  10806. (catch 'exit
  10807. (org-back-to-heading t)
  10808. (when (org-in-commented-heading-p t)
  10809. (org-toggle-comment)
  10810. (setq commentp t))
  10811. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10812. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10813. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10814. (let* ((match-data (match-data))
  10815. (startpos (copy-marker (line-beginning-position)))
  10816. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10817. (org-log-done org-log-done)
  10818. (org-log-repeat org-log-repeat)
  10819. (org-todo-log-states org-todo-log-states)
  10820. (org-inhibit-logging
  10821. (if (equal arg 0)
  10822. (progn (setq arg nil) 'note) org-inhibit-logging))
  10823. (this (match-string 1))
  10824. (hl-pos (match-beginning 0))
  10825. (head (org-get-todo-sequence-head this))
  10826. (ass (assoc head org-todo-kwd-alist))
  10827. (interpret (nth 1 ass))
  10828. (done-word (nth 3 ass))
  10829. (final-done-word (nth 4 ass))
  10830. (org-last-state (or this ""))
  10831. (completion-ignore-case t)
  10832. (member (member this org-todo-keywords-1))
  10833. (tail (cdr member))
  10834. (org-state (cond
  10835. ((and org-todo-key-trigger
  10836. (or (and (equal arg '(4))
  10837. (eq org-use-fast-todo-selection 'prefix))
  10838. (and (not arg) org-use-fast-todo-selection
  10839. (not (eq org-use-fast-todo-selection
  10840. 'prefix)))))
  10841. ;; Use fast selection.
  10842. (org-fast-todo-selection))
  10843. ((and (equal arg '(4))
  10844. (or (not org-use-fast-todo-selection)
  10845. (not org-todo-key-trigger)))
  10846. ;; Read a state with completion.
  10847. (completing-read
  10848. "State: " (mapcar #'list org-todo-keywords-1)
  10849. nil t))
  10850. ((eq arg 'right)
  10851. (if this
  10852. (if tail (car tail) nil)
  10853. (car org-todo-keywords-1)))
  10854. ((eq arg 'left)
  10855. (unless (equal member org-todo-keywords-1)
  10856. (if this
  10857. (nth (- (length org-todo-keywords-1)
  10858. (length tail) 2)
  10859. org-todo-keywords-1)
  10860. (org-last org-todo-keywords-1))))
  10861. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10862. (setq arg nil))) ;hack to fall back to cycling
  10863. (arg
  10864. ;; User or caller requests a specific state.
  10865. (cond
  10866. ((equal arg "") nil)
  10867. ((eq arg 'none) nil)
  10868. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10869. ((eq arg 'nextset)
  10870. (or (car (cdr (member head org-todo-heads)))
  10871. (car org-todo-heads)))
  10872. ((eq arg 'previousset)
  10873. (let ((org-todo-heads (reverse org-todo-heads)))
  10874. (or (car (cdr (member head org-todo-heads)))
  10875. (car org-todo-heads))))
  10876. ((car (member arg org-todo-keywords-1)))
  10877. ((stringp arg)
  10878. (user-error "State `%s' not valid in this file" arg))
  10879. ((nth (1- (prefix-numeric-value arg))
  10880. org-todo-keywords-1))))
  10881. ((null member) (or head (car org-todo-keywords-1)))
  10882. ((equal this final-done-word) nil) ;-> make empty
  10883. ((null tail) nil) ;-> first entry
  10884. ((memq interpret '(type priority))
  10885. (if (eq this-command last-command)
  10886. (car tail)
  10887. (if (> (length tail) 0)
  10888. (or done-word (car org-done-keywords))
  10889. nil)))
  10890. (t
  10891. (car tail))))
  10892. (org-state (or
  10893. (run-hook-with-args-until-success
  10894. 'org-todo-get-default-hook org-state org-last-state)
  10895. org-state))
  10896. (next (if org-state (concat " " org-state " ") " "))
  10897. (change-plist (list :type 'todo-state-change :from this :to org-state
  10898. :position startpos))
  10899. dolog now-done-p)
  10900. (when org-blocker-hook
  10901. (let (org-blocked-by-checkboxes block-reason)
  10902. (setq org-last-todo-state-is-todo
  10903. (not (member this org-done-keywords)))
  10904. (unless (save-excursion
  10905. (save-match-data
  10906. (org-with-wide-buffer
  10907. (run-hook-with-args-until-failure
  10908. 'org-blocker-hook change-plist))))
  10909. (setq block-reason (if org-blocked-by-checkboxes
  10910. "contained checkboxes"
  10911. (format "\"%s\"" org-block-entry-blocking)))
  10912. (if (called-interactively-p 'interactive)
  10913. (user-error "TODO state change from %s to %s blocked (by %s)"
  10914. this org-state block-reason)
  10915. ;; Fail silently.
  10916. (message "TODO state change from %s to %s blocked (by %s)"
  10917. this org-state block-reason)
  10918. (throw 'exit nil)))))
  10919. (store-match-data match-data)
  10920. (replace-match next t t)
  10921. (cond ((equal this org-state)
  10922. (message "TODO state was already %s" (org-trim next)))
  10923. ((not (pos-visible-in-window-p hl-pos))
  10924. (message "TODO state changed to %s" (org-trim next))))
  10925. (unless head
  10926. (setq head (org-get-todo-sequence-head org-state)
  10927. ass (assoc head org-todo-kwd-alist)
  10928. interpret (nth 1 ass)
  10929. done-word (nth 3 ass)
  10930. final-done-word (nth 4 ass)))
  10931. (when (memq arg '(nextset previousset))
  10932. (message "Keyword-Set %d/%d: %s"
  10933. (- (length org-todo-sets) -1
  10934. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10935. (length org-todo-sets)
  10936. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10937. (setq org-last-todo-state-is-todo
  10938. (not (member org-state org-done-keywords)))
  10939. (setq now-done-p (and (member org-state org-done-keywords)
  10940. (not (member this org-done-keywords))))
  10941. (and logging (org-local-logging logging))
  10942. (when (and (or org-todo-log-states org-log-done)
  10943. (not (eq org-inhibit-logging t))
  10944. (not (memq arg '(nextset previousset))))
  10945. ;; We need to look at recording a time and note.
  10946. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10947. (nth 2 (assoc this org-todo-log-states))))
  10948. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10949. (setq dolog 'time))
  10950. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10951. (and org-state
  10952. (member org-state org-not-done-keywords)
  10953. (not (member this org-not-done-keywords))))
  10954. ;; This is now a todo state and was not one before
  10955. ;; If there was a CLOSED time stamp, get rid of it.
  10956. (org-add-planning-info nil nil 'closed))
  10957. (when (and now-done-p org-log-done)
  10958. ;; It is now done, and it was not done before.
  10959. (org-add-planning-info 'closed (org-current-effective-time))
  10960. (when (and (not dolog) (eq 'note org-log-done))
  10961. (org-add-log-setup 'done org-state this 'note)))
  10962. (when (and org-state dolog)
  10963. ;; This is a non-nil state, and we need to log it.
  10964. (org-add-log-setup 'state org-state this dolog)))
  10965. ;; Fixup tag positioning.
  10966. (org-todo-trigger-tag-changes org-state)
  10967. (when org-auto-align-tags (org-align-tags))
  10968. (when org-provide-todo-statistics
  10969. (org-update-parent-todo-statistics))
  10970. (run-hooks 'org-after-todo-state-change-hook)
  10971. (when (and arg (not (member org-state org-done-keywords)))
  10972. (setq head (org-get-todo-sequence-head org-state)))
  10973. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10974. ;; Do we need to trigger a repeat?
  10975. (when now-done-p
  10976. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10977. ;; This is for the agenda, take a snapshot of the headline.
  10978. (save-match-data
  10979. (setq org-agenda-headline-snapshot-before-repeat
  10980. (org-get-heading))))
  10981. (org-auto-repeat-maybe org-state))
  10982. ;; Fixup cursor location if close to the keyword.
  10983. (when (and (outline-on-heading-p)
  10984. (not (bolp))
  10985. (save-excursion (beginning-of-line 1)
  10986. (looking-at org-todo-line-regexp))
  10987. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10988. (goto-char (or (match-end 2) (match-end 1)))
  10989. (and (looking-at " ") (just-one-space)))
  10990. (when org-trigger-hook
  10991. (save-excursion
  10992. (run-hook-with-args 'org-trigger-hook change-plist)))
  10993. (when commentp (org-toggle-comment))))))))
  10994. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10995. "Block turning an entry into a TODO, using the hierarchy.
  10996. This checks whether the current task should be blocked from state
  10997. changes. Such blocking occurs when:
  10998. 1. The task has children which are not all in a completed state.
  10999. 2. A task has a parent with the property :ORDERED:, and there
  11000. are siblings prior to the current task with incomplete
  11001. status.
  11002. 3. The parent of the task is blocked because it has siblings that should
  11003. be done first, or is child of a block grandparent TODO entry."
  11004. (if (not org-enforce-todo-dependencies)
  11005. t ; if locally turned off don't block
  11006. (catch 'dont-block
  11007. ;; If this is not a todo state change, or if this entry is already DONE,
  11008. ;; do not block
  11009. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11010. (member (plist-get change-plist :from)
  11011. (cons 'done org-done-keywords))
  11012. (member (plist-get change-plist :to)
  11013. (cons 'todo org-not-done-keywords))
  11014. (not (plist-get change-plist :to)))
  11015. (throw 'dont-block t))
  11016. ;; If this task has children, and any are undone, it's blocked
  11017. (save-excursion
  11018. (org-back-to-heading t)
  11019. (let ((this-level (funcall outline-level)))
  11020. (outline-next-heading)
  11021. (let ((child-level (funcall outline-level)))
  11022. (while (and (not (eobp))
  11023. (> child-level this-level))
  11024. ;; this todo has children, check whether they are all
  11025. ;; completed
  11026. (when (and (not (org-entry-is-done-p))
  11027. (org-entry-is-todo-p))
  11028. (setq org-block-entry-blocking (org-get-heading))
  11029. (throw 'dont-block nil))
  11030. (outline-next-heading)
  11031. (setq child-level (funcall outline-level))))))
  11032. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11033. ;; any previous siblings are undone, it's blocked
  11034. (save-excursion
  11035. (org-back-to-heading t)
  11036. (let* ((pos (point))
  11037. (parent-pos (and (org-up-heading-safe) (point)))
  11038. (case-fold-search nil))
  11039. (unless parent-pos (throw 'dont-block t)) ; no parent
  11040. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11041. (forward-line 1)
  11042. (re-search-forward org-not-done-heading-regexp pos t))
  11043. (setq org-block-entry-blocking (match-string 0))
  11044. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11045. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11046. (while t
  11047. (goto-char parent-pos)
  11048. (unless (looking-at org-not-done-heading-regexp)
  11049. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11050. (setq pos (point))
  11051. (setq parent-pos (and (org-up-heading-safe) (point)))
  11052. (unless parent-pos (throw 'dont-block t)) ; no parent
  11053. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11054. (forward-line 1)
  11055. (re-search-forward org-not-done-heading-regexp pos t)
  11056. (setq org-block-entry-blocking (org-get-heading)))
  11057. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11058. (defcustom org-track-ordered-property-with-tag nil
  11059. "Should the ORDERED property also be shown as a tag?
  11060. The ORDERED property decides if an entry should require subtasks to be
  11061. completed in sequence. Since a property is not very visible, setting
  11062. this option means that toggling the ORDERED property with the command
  11063. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11064. not relevant for the behavior, but it makes things more visible.
  11065. Note that toggling the tag with tags commands will not change the property
  11066. and therefore not influence behavior!
  11067. This can be t, meaning the tag ORDERED should be used, It can also be a
  11068. string to select a different tag for this task."
  11069. :group 'org-todo
  11070. :type '(choice
  11071. (const :tag "No tracking" nil)
  11072. (const :tag "Track with ORDERED tag" t)
  11073. (string :tag "Use other tag")))
  11074. (defun org-toggle-ordered-property ()
  11075. "Toggle the ORDERED property of the current entry.
  11076. For better visibility, you can track the value of this property with a tag.
  11077. See variable `org-track-ordered-property-with-tag'."
  11078. (interactive)
  11079. (let* ((t1 org-track-ordered-property-with-tag)
  11080. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11081. (save-excursion
  11082. (org-back-to-heading)
  11083. (if (org-entry-get nil "ORDERED")
  11084. (progn
  11085. (org-delete-property "ORDERED")
  11086. (and tag (org-toggle-tag tag 'off))
  11087. (message "Subtasks can be completed in arbitrary order"))
  11088. (org-entry-put nil "ORDERED" "t")
  11089. (and tag (org-toggle-tag tag 'on))
  11090. (message "Subtasks must be completed in sequence")))))
  11091. (defun org-block-todo-from-checkboxes (change-plist)
  11092. "Block turning an entry into a TODO, using checkboxes.
  11093. This checks whether the current task should be blocked from state
  11094. changes because there are unchecked boxes in this entry."
  11095. (if (not org-enforce-todo-checkbox-dependencies)
  11096. t ; if locally turned off don't block
  11097. (catch 'dont-block
  11098. ;; If this is not a todo state change, or if this entry is already DONE,
  11099. ;; do not block
  11100. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11101. (member (plist-get change-plist :from)
  11102. (cons 'done org-done-keywords))
  11103. (member (plist-get change-plist :to)
  11104. (cons 'todo org-not-done-keywords))
  11105. (not (plist-get change-plist :to)))
  11106. (throw 'dont-block t))
  11107. ;; If this task has checkboxes that are not checked, it's blocked
  11108. (save-excursion
  11109. (org-back-to-heading t)
  11110. (let ((beg (point)) end)
  11111. (outline-next-heading)
  11112. (setq end (point))
  11113. (goto-char beg)
  11114. (when (org-list-search-forward
  11115. (concat (org-item-beginning-re)
  11116. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11117. "\\[[- ]\\]")
  11118. end t)
  11119. (when (boundp 'org-blocked-by-checkboxes)
  11120. (setq org-blocked-by-checkboxes t))
  11121. (throw 'dont-block nil))))
  11122. t))) ; do not block
  11123. (defun org-entry-blocked-p ()
  11124. "Non-nil if entry at point is blocked."
  11125. (and (not (org-entry-get nil "NOBLOCKING"))
  11126. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11127. (not (run-hook-with-args-until-failure
  11128. 'org-blocker-hook
  11129. (list :type 'todo-state-change
  11130. :position (point)
  11131. :from 'todo
  11132. :to 'done)))))
  11133. (defun org-update-statistics-cookies (all)
  11134. "Update the statistics cookie, either from TODO or from checkboxes.
  11135. This should be called with the cursor in a line with a statistics
  11136. cookie. When called with a \\[universal-argument] prefix, update
  11137. all statistics cookies in the buffer."
  11138. (interactive "P")
  11139. (if all
  11140. (progn
  11141. (org-update-checkbox-count 'all)
  11142. (org-map-entries 'org-update-parent-todo-statistics))
  11143. (if (not (org-at-heading-p))
  11144. (org-update-checkbox-count)
  11145. (let ((pos (point-marker))
  11146. end l1 l2)
  11147. (ignore-errors (org-back-to-heading t))
  11148. (if (not (org-at-heading-p))
  11149. (org-update-checkbox-count)
  11150. (setq l1 (org-outline-level))
  11151. (setq end (save-excursion
  11152. (outline-next-heading)
  11153. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11154. (point)))
  11155. (if (and (save-excursion
  11156. (re-search-forward
  11157. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11158. (not (save-excursion (re-search-forward
  11159. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11160. (org-update-checkbox-count)
  11161. (if (and l2 (> l2 l1))
  11162. (progn
  11163. (goto-char end)
  11164. (org-update-parent-todo-statistics))
  11165. (goto-char pos)
  11166. (beginning-of-line 1)
  11167. (while (re-search-forward
  11168. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11169. (point-at-eol) t)
  11170. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11171. (goto-char pos)
  11172. (move-marker pos nil)))))
  11173. (defvar org-entry-property-inherited-from) ;; defined below
  11174. (defun org-update-parent-todo-statistics ()
  11175. "Update any statistics cookie in the parent of the current headline.
  11176. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11177. the entire subtree and this will travel up the hierarchy and update
  11178. statistics everywhere."
  11179. (let* ((prop (save-excursion (org-up-heading-safe)
  11180. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11181. (recursive (or (not org-hierarchical-todo-statistics)
  11182. (and prop (string-match "\\<recursive\\>" prop))))
  11183. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11184. 0))
  11185. (first t)
  11186. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11187. level ltoggle l1 new ndel
  11188. (cnt-all 0) (cnt-done 0) is-percent kwd
  11189. checkbox-beg cookie-present)
  11190. (catch 'exit
  11191. (save-excursion
  11192. (beginning-of-line 1)
  11193. (setq ltoggle (funcall outline-level))
  11194. ;; Three situations are to consider:
  11195. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11196. ;; to the top-level ancestor on the headline;
  11197. ;; 2. If parent has "recursive" property, repeat up to the
  11198. ;; headline setting that property, taking inheritance into
  11199. ;; account;
  11200. ;; 3. Else, move up to direct parent and proceed only once.
  11201. (while (and (setq level (org-up-heading-safe))
  11202. (or recursive first)
  11203. (>= (point) lim))
  11204. (setq first nil cookie-present nil)
  11205. (unless (and level
  11206. (not (string-match
  11207. "\\<checkbox\\>"
  11208. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11209. "")))))
  11210. (throw 'exit nil))
  11211. (while (re-search-forward box-re (point-at-eol) t)
  11212. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11213. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11214. (save-match-data
  11215. (unless (outline-next-heading) (throw 'exit nil))
  11216. (while (and (looking-at org-complex-heading-regexp)
  11217. (> (setq l1 (length (match-string 1))) level))
  11218. (setq kwd (and (or recursive (= l1 ltoggle))
  11219. (match-string 2)))
  11220. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11221. (and (eq org-provide-todo-statistics t)
  11222. (or (member kwd org-done-keywords)))
  11223. (and (listp org-provide-todo-statistics)
  11224. (stringp (car org-provide-todo-statistics))
  11225. (or (member kwd org-provide-todo-statistics)
  11226. (member kwd org-done-keywords)))
  11227. (and (listp org-provide-todo-statistics)
  11228. (listp (car org-provide-todo-statistics))
  11229. (or (member kwd (car org-provide-todo-statistics))
  11230. (and (member kwd org-done-keywords)
  11231. (member kwd (cadr org-provide-todo-statistics))))))
  11232. (setq cnt-all (1+ cnt-all))
  11233. (and (eq org-provide-todo-statistics t)
  11234. kwd
  11235. (setq cnt-all (1+ cnt-all))))
  11236. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11237. (member kwd org-done-keywords))
  11238. (and (listp org-provide-todo-statistics)
  11239. (listp (car org-provide-todo-statistics))
  11240. (member kwd org-done-keywords)
  11241. (member kwd (cadr org-provide-todo-statistics)))
  11242. (and (listp org-provide-todo-statistics)
  11243. (stringp (car org-provide-todo-statistics))
  11244. (member kwd org-done-keywords)))
  11245. (setq cnt-done (1+ cnt-done)))
  11246. (outline-next-heading)))
  11247. (setq new
  11248. (if is-percent
  11249. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11250. (max 1 cnt-all)))
  11251. (format "[%d/%d]" cnt-done cnt-all))
  11252. ndel (- (match-end 0) checkbox-beg))
  11253. (goto-char checkbox-beg)
  11254. (insert new)
  11255. (delete-region (point) (+ (point) ndel))
  11256. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11257. (when cookie-present
  11258. (run-hook-with-args 'org-after-todo-statistics-hook
  11259. cnt-done (- cnt-all cnt-done))))))
  11260. (run-hooks 'org-todo-statistics-hook)))
  11261. (defvar org-after-todo-statistics-hook nil
  11262. "Hook that is called after a TODO statistics cookie has been updated.
  11263. Each function is called with two arguments: the number of not-done entries
  11264. and the number of done entries.
  11265. For example, the following function, when added to this hook, will switch
  11266. an entry to DONE when all children are done, and back to TODO when new
  11267. entries are set to a TODO status. Note that this hook is only called
  11268. when there is a statistics cookie in the headline!
  11269. (defun org-summary-todo (n-done n-not-done)
  11270. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11271. (let (org-log-done org-log-states) ; turn off logging
  11272. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11273. ")
  11274. (defvar org-todo-statistics-hook nil
  11275. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11276. This hook runs even if there is no statistics cookie present, in which case
  11277. `org-after-todo-statistics-hook' would not run.")
  11278. (defun org-todo-trigger-tag-changes (state)
  11279. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11280. (let ((l org-todo-state-tags-triggers)
  11281. changes)
  11282. (when (or (not state) (equal state ""))
  11283. (setq changes (append changes (cdr (assoc "" l)))))
  11284. (when (and (stringp state) (> (length state) 0))
  11285. (setq changes (append changes (cdr (assoc state l)))))
  11286. (when (member state org-not-done-keywords)
  11287. (setq changes (append changes (cdr (assq 'todo l)))))
  11288. (when (member state org-done-keywords)
  11289. (setq changes (append changes (cdr (assq 'done l)))))
  11290. (dolist (c changes)
  11291. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11292. (defun org-local-logging (value)
  11293. "Get logging settings from a property VALUE."
  11294. ;; Directly set the variables, they are already local.
  11295. (setq org-log-done nil
  11296. org-log-repeat nil
  11297. org-todo-log-states nil)
  11298. (dolist (w (split-string value))
  11299. (let (a)
  11300. (cond
  11301. ((setq a (assoc w org-startup-options))
  11302. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11303. (set (nth 1 a) (nth 2 a))))
  11304. ((setq a (org-extract-log-state-settings w))
  11305. (and (member (car a) org-todo-keywords-1)
  11306. (push a org-todo-log-states)))))))
  11307. (defun org-get-todo-sequence-head (kwd)
  11308. "Return the head of the TODO sequence to which KWD belongs.
  11309. If KWD is not set, check if there is a text property remembering the
  11310. right sequence."
  11311. (let (p)
  11312. (cond
  11313. ((not kwd)
  11314. (or (get-text-property (point-at-bol) 'org-todo-head)
  11315. (progn
  11316. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11317. nil (point-at-eol)))
  11318. (get-text-property p 'org-todo-head))))
  11319. ((not (member kwd org-todo-keywords-1))
  11320. (car org-todo-keywords-1))
  11321. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11322. (defun org-fast-todo-selection ()
  11323. "Fast TODO keyword selection with single keys.
  11324. Returns the new TODO keyword, or nil if no state change should occur."
  11325. (let* ((fulltable org-todo-key-alist)
  11326. (done-keywords org-done-keywords) ;; needed for the faces.
  11327. (maxlen (apply 'max (mapcar
  11328. (lambda (x)
  11329. (if (stringp (car x)) (string-width (car x)) 0))
  11330. fulltable)))
  11331. (expert nil)
  11332. (fwidth (+ maxlen 3 1 3))
  11333. (ncol (/ (- (window-width) 4) fwidth))
  11334. tg cnt e c tbl
  11335. groups ingroup)
  11336. (save-excursion
  11337. (save-window-excursion
  11338. (if expert
  11339. (set-buffer (get-buffer-create " *Org todo*"))
  11340. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11341. (erase-buffer)
  11342. (setq-local org-done-keywords done-keywords)
  11343. (setq tbl fulltable cnt 0)
  11344. (while (setq e (pop tbl))
  11345. (cond
  11346. ((equal e '(:startgroup))
  11347. (push '() groups) (setq ingroup t)
  11348. (unless (= cnt 0)
  11349. (setq cnt 0)
  11350. (insert "\n"))
  11351. (insert "{ "))
  11352. ((equal e '(:endgroup))
  11353. (setq ingroup nil cnt 0)
  11354. (insert "}\n"))
  11355. ((equal e '(:newline))
  11356. (unless (= cnt 0)
  11357. (setq cnt 0)
  11358. (insert "\n")
  11359. (setq e (car tbl))
  11360. (while (equal (car tbl) '(:newline))
  11361. (insert "\n")
  11362. (setq tbl (cdr tbl)))))
  11363. (t
  11364. (setq tg (car e) c (cdr e))
  11365. (when ingroup (push tg (car groups)))
  11366. (setq tg (org-add-props tg nil 'face
  11367. (org-get-todo-face tg)))
  11368. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11369. (insert "[" c "] " tg (make-string
  11370. (- fwidth 4 (length tg)) ?\ ))
  11371. (when (= (setq cnt (1+ cnt)) ncol)
  11372. (insert "\n")
  11373. (when ingroup (insert " "))
  11374. (setq cnt 0)))))
  11375. (insert "\n")
  11376. (goto-char (point-min))
  11377. (unless expert (org-fit-window-to-buffer))
  11378. (message "[a-z..]:Set [SPC]:clear")
  11379. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11380. (cond
  11381. ((or (= c ?\C-g)
  11382. (and (= c ?q) (not (rassoc c fulltable))))
  11383. (setq quit-flag t))
  11384. ((= c ?\ ) nil)
  11385. ((setq e (rassoc c fulltable) tg (car e))
  11386. tg)
  11387. (t (setq quit-flag t)))))))
  11388. (defun org-entry-is-todo-p ()
  11389. (member (org-get-todo-state) org-not-done-keywords))
  11390. (defun org-entry-is-done-p ()
  11391. (member (org-get-todo-state) org-done-keywords))
  11392. (defun org-get-todo-state ()
  11393. "Return the TODO keyword of the current subtree."
  11394. (save-excursion
  11395. (org-back-to-heading t)
  11396. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11397. (match-end 2)
  11398. (match-string 2))))
  11399. (defun org-at-date-range-p (&optional inactive-ok)
  11400. "Non-nil if point is inside a date range.
  11401. When optional argument INACTIVE-OK is non-nil, also consider
  11402. inactive time ranges.
  11403. When this function returns a non-nil value, match data is set
  11404. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11405. on INACTIVE-OK."
  11406. (interactive)
  11407. (save-excursion
  11408. (catch 'exit
  11409. (let ((pos (point)))
  11410. (skip-chars-backward "^[<\r\n")
  11411. (skip-chars-backward "<[")
  11412. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11413. (>= (match-end 0) pos)
  11414. (throw 'exit t))
  11415. (skip-chars-backward "^<[\r\n")
  11416. (skip-chars-backward "<[")
  11417. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11418. (>= (match-end 0) pos)
  11419. (throw 'exit t)))
  11420. nil)))
  11421. (defun org-get-repeat (&optional timestamp)
  11422. "Check if there is a time-stamp with repeater in this entry.
  11423. Return the repeater, as a string, or nil. Also return nil when
  11424. this function is called before first heading.
  11425. When optional argument TIMESTAMP is a string, extract the
  11426. repeater from there instead."
  11427. (save-match-data
  11428. (cond (timestamp
  11429. (and (string-match org-repeat-re timestamp)
  11430. (match-string-no-properties 1 timestamp)))
  11431. ((org-before-first-heading-p) nil)
  11432. (t
  11433. (save-excursion
  11434. (org-back-to-heading t)
  11435. (let ((end (org-entry-end-position)))
  11436. (catch :repeat
  11437. (while (re-search-forward org-repeat-re end t)
  11438. (when (save-match-data (org-at-timestamp-p 'agenda))
  11439. (throw :repeat (match-string-no-properties 1)))))))))))
  11440. (defvar org-last-changed-timestamp)
  11441. (defvar org-last-inserted-timestamp)
  11442. (defvar org-log-post-message)
  11443. (defvar org-log-note-purpose)
  11444. (defvar org-log-note-how nil)
  11445. (defvar org-log-note-extra)
  11446. (defun org-auto-repeat-maybe (done-word)
  11447. "Check if the current headline contains a repeated time-stamp.
  11448. If yes, set TODO state back to what it was and change the base date
  11449. of repeating deadline/scheduled time stamps to new date.
  11450. This function is run automatically after each state change to a DONE state."
  11451. (let* ((repeat (org-get-repeat))
  11452. (aa (assoc org-last-state org-todo-kwd-alist))
  11453. (interpret (nth 1 aa))
  11454. (head (nth 2 aa))
  11455. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11456. (msg "Entry repeats: ")
  11457. (org-log-done nil)
  11458. (org-todo-log-states nil)
  11459. (end (copy-marker (org-entry-end-position))))
  11460. (unwind-protect
  11461. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11462. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11463. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11464. (and (stringp org-todo-repeat-to-state)
  11465. org-todo-repeat-to-state)
  11466. (and org-todo-repeat-to-state org-last-state))))
  11467. (org-todo (cond
  11468. ((and to-state (member to-state org-todo-keywords-1))
  11469. to-state)
  11470. ((eq interpret 'type) org-last-state)
  11471. (head)
  11472. (t 'none))))
  11473. (org-back-to-heading t)
  11474. (org-add-planning-info nil nil 'closed)
  11475. ;; When `org-log-repeat' is non-nil or entry contains
  11476. ;; a clock, set LAST_REPEAT property.
  11477. (when (or org-log-repeat
  11478. (catch :clock
  11479. (save-excursion
  11480. (while (re-search-forward org-clock-line-re end t)
  11481. (when (org-at-clock-log-p) (throw :clock t))))))
  11482. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11483. (org-time-stamp-format t t)
  11484. (current-time))))
  11485. (when org-log-repeat
  11486. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11487. (memq 'org-add-log-note post-command-hook))
  11488. ;; We are already setup for some record.
  11489. (when (eq org-log-repeat 'note)
  11490. ;; Make sure we take a note, not only a time stamp.
  11491. (setq org-log-note-how 'note))
  11492. ;; Set up for taking a record.
  11493. (org-add-log-setup 'state
  11494. (or done-word (car org-done-keywords))
  11495. org-last-state
  11496. org-log-repeat)))
  11497. (let ((planning-re (regexp-opt
  11498. (list org-scheduled-string org-deadline-string))))
  11499. (while (re-search-forward org-ts-regexp end t)
  11500. (let* ((ts (match-string 0))
  11501. (planning? (org-at-planning-p))
  11502. (type (if (not planning?) "Plain:"
  11503. (save-excursion
  11504. (re-search-backward
  11505. planning-re (line-beginning-position) t)
  11506. (match-string 0)))))
  11507. (cond
  11508. ;; Ignore fake time-stamps (e.g., within comments).
  11509. ((not (org-at-timestamp-p 'agenda)))
  11510. ;; Time-stamps without a repeater are usually
  11511. ;; skipped. However, a SCHEDULED time-stamp without
  11512. ;; one is removed, as they are no longer relevant.
  11513. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11514. ts))
  11515. (when (equal type org-scheduled-string)
  11516. (org-remove-timestamp-with-keyword type)))
  11517. (t
  11518. (let ((n (string-to-number (match-string 2 ts)))
  11519. (what (match-string 3 ts)))
  11520. (when (equal what "w") (setq n (* n 7) what "d"))
  11521. (when (and (equal what "h")
  11522. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11523. ts)))
  11524. (user-error
  11525. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11526. has been set"
  11527. n))
  11528. ;; Preparation, see if we need to modify the start
  11529. ;; date for the change.
  11530. (when (match-end 1)
  11531. (let ((time (save-match-data
  11532. (org-time-string-to-time ts))))
  11533. (cond
  11534. ((equal (match-string 1 ts) ".")
  11535. ;; Shift starting date to today
  11536. (org-timestamp-change
  11537. (- (org-today) (time-to-days time))
  11538. 'day))
  11539. ((equal (match-string 1 ts) "+")
  11540. (let ((nshiftmax 10)
  11541. (nshift 0))
  11542. (while (or (= nshift 0)
  11543. (not (time-less-p (current-time) time)))
  11544. (when (= (cl-incf nshift) nshiftmax)
  11545. (or (y-or-n-p
  11546. (format "%d repeater intervals were not \
  11547. enough to shift date past today. Continue? "
  11548. nshift))
  11549. (user-error "Abort")))
  11550. (org-timestamp-change n (cdr (assoc what whata)))
  11551. (org-in-regexp org-ts-regexp3)
  11552. (setq ts (match-string 1))
  11553. (setq time
  11554. (save-match-data
  11555. (org-time-string-to-time ts)))))
  11556. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11557. ;; Rematch, so that we have everything in place
  11558. ;; for the real shift.
  11559. (org-in-regexp org-ts-regexp3)
  11560. (setq ts (match-string 1))
  11561. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11562. ts)))))
  11563. (save-excursion
  11564. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11565. (setq msg
  11566. (concat
  11567. msg type " " org-last-changed-timestamp " "))))))))
  11568. (setq org-log-post-message msg)
  11569. (message "%s" msg))
  11570. (set-marker end nil))))
  11571. (defun org-show-todo-tree (arg)
  11572. "Make a compact tree which shows all headlines marked with TODO.
  11573. The tree will show the lines where the regexp matches, and all higher
  11574. headlines above the match.
  11575. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11576. With a numeric prefix N, construct a sparse tree for the Nth element
  11577. of `org-todo-keywords-1'."
  11578. (interactive "P")
  11579. (let ((case-fold-search nil)
  11580. (kwd-re
  11581. (cond ((null arg) org-not-done-regexp)
  11582. ((equal arg '(4))
  11583. (let ((kwd
  11584. (completing-read "Keyword (or KWD1|KWD2|...): "
  11585. (mapcar #'list org-todo-keywords-1))))
  11586. (concat "\\("
  11587. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11588. "\\)\\>")))
  11589. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11590. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11591. org-todo-keywords-1)))
  11592. (t (user-error "Invalid prefix argument: %s" arg)))))
  11593. (message "%d TODO entries found"
  11594. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11595. (defun org--deadline-or-schedule (arg type time)
  11596. "Insert DEADLINE or SCHEDULE information in current entry.
  11597. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11598. `org-schedule' for information about ARG and TIME arguments."
  11599. (let* ((deadline? (eq type 'deadline))
  11600. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11601. (log (if deadline? org-log-redeadline org-log-reschedule))
  11602. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11603. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11604. ;; Save repeater cookie from either TIME or current scheduled
  11605. ;; time stamp. We are going to insert it back at the end of
  11606. ;; the process.
  11607. (repeater (or (and (org-string-nw-p time)
  11608. ;; We use `org-repeat-re' because we need
  11609. ;; to tell the difference between a real
  11610. ;; repeater and a time delta, e.g. "+2d".
  11611. (string-match org-repeat-re time)
  11612. (match-string 1 time))
  11613. (and (org-string-nw-p old-date)
  11614. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11615. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11616. old-date)
  11617. (match-string 1 old-date)))))
  11618. (pcase arg
  11619. (`(4)
  11620. (if (not old-date)
  11621. (message (if deadline? "Entry had no deadline to remove"
  11622. "Entry was not scheduled"))
  11623. (when (and old-date log)
  11624. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11625. nil old-date log))
  11626. (org-remove-timestamp-with-keyword keyword)
  11627. (message (if deadline? "Entry no longer has a deadline."
  11628. "Entry is no longer scheduled."))))
  11629. (`(16)
  11630. (save-excursion
  11631. (org-back-to-heading t)
  11632. (let ((regexp (if deadline? org-deadline-time-regexp
  11633. org-scheduled-time-regexp)))
  11634. (if (not (re-search-forward regexp (line-end-position 2) t))
  11635. (user-error (if deadline? "No deadline information to update"
  11636. "No scheduled information to update"))
  11637. (let* ((rpl0 (match-string 1))
  11638. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11639. (msg (if deadline? "Warn starting from" "Delay until")))
  11640. (replace-match
  11641. (concat keyword
  11642. " <" rpl
  11643. (format " -%dd"
  11644. (abs (- (time-to-days
  11645. (save-match-data
  11646. (org-read-date
  11647. nil t nil msg old-date-time)))
  11648. (time-to-days old-date-time))))
  11649. ">") t t))))))
  11650. (_
  11651. (org-add-planning-info type time 'closed)
  11652. (when (and old-date
  11653. log
  11654. (not (equal old-date org-last-inserted-timestamp)))
  11655. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11656. org-last-inserted-timestamp
  11657. old-date
  11658. log))
  11659. (when repeater
  11660. (save-excursion
  11661. (org-back-to-heading t)
  11662. (when (re-search-forward
  11663. (concat keyword " " org-last-inserted-timestamp)
  11664. (line-end-position 2)
  11665. t)
  11666. (goto-char (1- (match-end 0)))
  11667. (insert " " repeater)
  11668. (setq org-last-inserted-timestamp
  11669. (concat (substring org-last-inserted-timestamp 0 -1)
  11670. " " repeater
  11671. (substring org-last-inserted-timestamp -1))))))
  11672. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11673. org-last-inserted-timestamp)))))
  11674. (defun org-deadline (arg &optional time)
  11675. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11676. With one universal prefix argument, remove any deadline from the item.
  11677. With two universal prefix arguments, prompt for a warning delay.
  11678. With argument TIME, set the deadline at the corresponding date. TIME
  11679. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11680. (interactive "P")
  11681. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11682. (org-map-entries
  11683. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11684. nil
  11685. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11686. 'region-start-level
  11687. 'region)
  11688. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11689. (org--deadline-or-schedule arg 'deadline time)))
  11690. (defun org-schedule (arg &optional time)
  11691. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11692. With one universal prefix argument, remove any scheduling date from the item.
  11693. With two universal prefix arguments, prompt for a delay cookie.
  11694. With argument TIME, scheduled at the corresponding date. TIME can
  11695. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11696. (interactive "P")
  11697. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11698. (org-map-entries
  11699. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11700. nil
  11701. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11702. 'region-start-level
  11703. 'region)
  11704. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11705. (org--deadline-or-schedule arg 'scheduled time)))
  11706. (defun org-get-scheduled-time (pom &optional inherit)
  11707. "Get the scheduled time as a time tuple, of a format suitable
  11708. for calling org-schedule with, or if there is no scheduling,
  11709. returns nil."
  11710. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11711. (when time
  11712. (apply 'encode-time (org-parse-time-string time)))))
  11713. (defun org-get-deadline-time (pom &optional inherit)
  11714. "Get the deadline as a time tuple, of a format suitable for
  11715. calling org-deadline with, or if there is no scheduling, returns
  11716. nil."
  11717. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11718. (when time
  11719. (apply 'encode-time (org-parse-time-string time)))))
  11720. (defun org-remove-timestamp-with-keyword (keyword)
  11721. "Remove all time stamps with KEYWORD in the current entry."
  11722. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11723. beg)
  11724. (save-excursion
  11725. (org-back-to-heading t)
  11726. (setq beg (point))
  11727. (outline-next-heading)
  11728. (while (re-search-backward re beg t)
  11729. (replace-match "")
  11730. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11731. (equal (char-before) ?\ ))
  11732. (backward-delete-char 1)
  11733. (when (string-match "^[ \t]*$" (buffer-substring
  11734. (point-at-bol) (point-at-eol)))
  11735. (delete-region (point-at-bol)
  11736. (min (point-max) (1+ (point-at-eol))))))))))
  11737. (defvar org-time-was-given) ; dynamically scoped parameter
  11738. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11739. (defun org-at-planning-p ()
  11740. "Non-nil when point is on a planning info line."
  11741. ;; This is as accurate and faster than `org-element-at-point' since
  11742. ;; planning info location is fixed in the section.
  11743. (org-with-wide-buffer
  11744. (beginning-of-line)
  11745. (and (looking-at-p org-planning-line-re)
  11746. (eq (point)
  11747. (ignore-errors
  11748. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11749. (org-back-to-heading t)
  11750. (org-with-limited-levels (org-back-to-heading t)))
  11751. (line-beginning-position 2))))))
  11752. (defun org-add-planning-info (what &optional time &rest remove)
  11753. "Insert new timestamp with keyword in the planning line.
  11754. WHAT indicates what kind of time stamp to add. It is a symbol
  11755. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11756. the time to use. If none is given, the user is prompted for
  11757. a date. REMOVE indicates what kind of entries to remove. An old
  11758. WHAT entry will also be removed."
  11759. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11760. (catch 'exit
  11761. (when (and (memq what '(scheduled deadline))
  11762. (or (not time)
  11763. (and (stringp time)
  11764. (string-match "^[-+]+[0-9]" time))))
  11765. ;; Try to get a default date/time from existing timestamp
  11766. (save-excursion
  11767. (org-back-to-heading t)
  11768. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11769. (when (re-search-forward (if (eq what 'scheduled)
  11770. org-scheduled-time-regexp
  11771. org-deadline-time-regexp)
  11772. end t)
  11773. (setq ts (match-string 1)
  11774. default-time (apply 'encode-time (org-parse-time-string ts))
  11775. default-input (and ts (org-get-compact-tod ts)))))))
  11776. (when what
  11777. (setq time
  11778. (if (stringp time)
  11779. ;; This is a string (relative or absolute), set
  11780. ;; proper date.
  11781. (apply #'encode-time
  11782. (org-read-date-analyze
  11783. time default-time (decode-time default-time)))
  11784. ;; If necessary, get the time from the user
  11785. (or time (org-read-date nil 'to-time nil nil
  11786. default-time default-input)))))
  11787. (org-with-wide-buffer
  11788. (org-back-to-heading t)
  11789. (forward-line)
  11790. (unless (bolp) (insert "\n"))
  11791. (cond ((looking-at-p org-planning-line-re)
  11792. ;; Move to current indentation.
  11793. (skip-chars-forward " \t")
  11794. ;; Check if we have to remove something.
  11795. (dolist (type (if what (cons what remove) remove))
  11796. (save-excursion
  11797. (when (re-search-forward
  11798. (cl-case type
  11799. (closed org-closed-time-regexp)
  11800. (deadline org-deadline-time-regexp)
  11801. (scheduled org-scheduled-time-regexp)
  11802. (otherwise
  11803. (error "Invalid planning type: %s" type)))
  11804. (line-end-position) t)
  11805. ;; Delete until next keyword or end of line.
  11806. (delete-region
  11807. (match-beginning 0)
  11808. (if (re-search-forward org-keyword-time-not-clock-regexp
  11809. (line-end-position)
  11810. t)
  11811. (match-beginning 0)
  11812. (line-end-position))))))
  11813. ;; If there is nothing more to add and no more keyword
  11814. ;; is left, remove the line completely.
  11815. (if (and (looking-at-p "[ \t]*$") (not what))
  11816. (delete-region (line-beginning-position)
  11817. (line-beginning-position 2))
  11818. ;; If we removed last keyword, do not leave trailing
  11819. ;; white space at the end of line.
  11820. (let ((p (point)))
  11821. (save-excursion
  11822. (end-of-line)
  11823. (unless (= (skip-chars-backward " \t" p) 0)
  11824. (delete-region (point) (line-end-position)))))))
  11825. ((not what) (throw 'exit nil)) ; Nothing to do.
  11826. (t (insert-before-markers "\n")
  11827. (backward-char 1)
  11828. (when org-adapt-indentation
  11829. (indent-to-column (1+ (org-outline-level))))))
  11830. (when what
  11831. ;; Insert planning keyword.
  11832. (insert (cl-case what
  11833. (closed org-closed-string)
  11834. (deadline org-deadline-string)
  11835. (scheduled org-scheduled-string)
  11836. (otherwise (error "Invalid planning type: %s" what)))
  11837. " ")
  11838. ;; Insert associated timestamp.
  11839. (let ((ts (org-insert-time-stamp
  11840. time
  11841. (or org-time-was-given
  11842. (and (eq what 'closed) org-log-done-with-time))
  11843. (eq what 'closed)
  11844. nil nil (list org-end-time-was-given))))
  11845. (unless (eolp) (insert " "))
  11846. ts))))))
  11847. (defvar org-log-note-marker (make-marker)
  11848. "Marker pointing at the entry where the note is to be inserted.")
  11849. (defvar org-log-note-purpose nil)
  11850. (defvar org-log-note-state nil)
  11851. (defvar org-log-note-previous-state nil)
  11852. (defvar org-log-note-extra nil)
  11853. (defvar org-log-note-window-configuration nil)
  11854. (defvar org-log-note-return-to (make-marker))
  11855. (defvar org-log-note-effective-time nil
  11856. "Remembered current time so that dynamically scoped
  11857. `org-extend-today-until' affects timestamps in state change log")
  11858. (defvar org-log-post-message nil
  11859. "Message to be displayed after a log note has been stored.
  11860. The auto-repeater uses this.")
  11861. (defun org-add-note ()
  11862. "Add a note to the current entry.
  11863. This is done in the same way as adding a state change note."
  11864. (interactive)
  11865. (org-add-log-setup 'note))
  11866. (defun org-log-beginning (&optional create)
  11867. "Return expected start of log notes in current entry.
  11868. When optional argument CREATE is non-nil, the function creates
  11869. a drawer to store notes, if necessary. Returned position ignores
  11870. narrowing."
  11871. (org-with-wide-buffer
  11872. (let ((drawer (org-log-into-drawer)))
  11873. (cond
  11874. (drawer
  11875. (org-end-of-meta-data)
  11876. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11877. (end (if (org-at-heading-p) (point)
  11878. (save-excursion (outline-next-heading) (point))))
  11879. (case-fold-search t))
  11880. (catch 'exit
  11881. ;; Try to find existing drawer.
  11882. (while (re-search-forward regexp end t)
  11883. (let ((element (org-element-at-point)))
  11884. (when (eq (org-element-type element) 'drawer)
  11885. (let ((cend (org-element-property :contents-end element)))
  11886. (when (and (not org-log-states-order-reversed) cend)
  11887. (goto-char cend)))
  11888. (throw 'exit nil))))
  11889. ;; No drawer found. Create one, if permitted.
  11890. (when create
  11891. (unless (bolp) (insert "\n"))
  11892. (let ((beg (point)))
  11893. (insert ":" drawer ":\n:END:\n")
  11894. (org-indent-region beg (point))
  11895. (org-flag-region
  11896. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11897. (end-of-line -1)))))
  11898. (t
  11899. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11900. (skip-chars-forward " \t\n")
  11901. (beginning-of-line)
  11902. (unless org-log-states-order-reversed
  11903. (org-skip-over-state-notes)
  11904. (skip-chars-backward " \t\n")
  11905. (forward-line)))))
  11906. (if (bolp) (point) (line-beginning-position 2))))
  11907. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11908. "Set up the post command hook to take a note.
  11909. If this is about to TODO state change, the new state is expected in STATE.
  11910. HOW is an indicator what kind of note should be created.
  11911. EXTRA is additional text that will be inserted into the notes buffer."
  11912. (move-marker org-log-note-marker (point))
  11913. (setq org-log-note-purpose purpose
  11914. org-log-note-state state
  11915. org-log-note-previous-state prev-state
  11916. org-log-note-how how
  11917. org-log-note-extra extra
  11918. org-log-note-effective-time (org-current-effective-time))
  11919. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11920. (defun org-skip-over-state-notes ()
  11921. "Skip past the list of State notes in an entry."
  11922. (when (ignore-errors (goto-char (org-in-item-p)))
  11923. (let* ((struct (org-list-struct))
  11924. (prevs (org-list-prevs-alist struct))
  11925. (regexp
  11926. (concat "[ \t]*- +"
  11927. (replace-regexp-in-string
  11928. " +" " +"
  11929. (org-replace-escapes
  11930. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11931. `(("%d" . ,org-ts-regexp-inactive)
  11932. ("%D" . ,org-ts-regexp)
  11933. ("%s" . "\\(?:\"\\S-+\"\\)?")
  11934. ("%S" . "\\(?:\"\\S-+\"\\)?")
  11935. ("%t" . ,org-ts-regexp-inactive)
  11936. ("%T" . ,org-ts-regexp)
  11937. ("%u" . ".*?")
  11938. ("%U" . ".*?")))))))
  11939. (while (looking-at-p regexp)
  11940. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11941. (org-list-get-item-end (point) struct)))))))
  11942. (defun org-add-log-note (&optional _purpose)
  11943. "Pop up a window for taking a note, and add this note later."
  11944. (remove-hook 'post-command-hook 'org-add-log-note)
  11945. (setq org-log-note-window-configuration (current-window-configuration))
  11946. (delete-other-windows)
  11947. (move-marker org-log-note-return-to (point))
  11948. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11949. (goto-char org-log-note-marker)
  11950. (org-switch-to-buffer-other-window "*Org Note*")
  11951. (erase-buffer)
  11952. (if (memq org-log-note-how '(time state))
  11953. (org-store-log-note)
  11954. (let ((org-inhibit-startup t)) (org-mode))
  11955. (insert (format "# Insert note for %s.
  11956. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11957. (cl-case org-log-note-purpose
  11958. (clock-out "stopped clock")
  11959. (done "closed todo item")
  11960. (reschedule "rescheduling")
  11961. (delschedule "no longer scheduled")
  11962. (redeadline "changing deadline")
  11963. (deldeadline "removing deadline")
  11964. (refile "refiling")
  11965. (note "this entry")
  11966. (state
  11967. (format "state change from \"%s\" to \"%s\""
  11968. (or org-log-note-previous-state "")
  11969. (or org-log-note-state "")))
  11970. (t (error "This should not happen")))))
  11971. (when org-log-note-extra (insert org-log-note-extra))
  11972. (setq-local org-finish-function 'org-store-log-note)
  11973. (run-hooks 'org-log-buffer-setup-hook)))
  11974. (defvar org-note-abort nil) ; dynamically scoped
  11975. (defun org-store-log-note ()
  11976. "Finish taking a log note, and insert it to where it belongs."
  11977. (let ((txt (prog1 (buffer-string)
  11978. (kill-buffer)))
  11979. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11980. lines)
  11981. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11982. (setq txt (replace-match "" t t txt)))
  11983. (when (string-match "\\s-+\\'" txt)
  11984. (setq txt (replace-match "" t t txt)))
  11985. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11986. (when (org-string-nw-p note)
  11987. (setq note
  11988. (org-replace-escapes
  11989. note
  11990. (list (cons "%u" (user-login-name))
  11991. (cons "%U" user-full-name)
  11992. (cons "%t" (format-time-string
  11993. (org-time-stamp-format 'long 'inactive)
  11994. org-log-note-effective-time))
  11995. (cons "%T" (format-time-string
  11996. (org-time-stamp-format 'long nil)
  11997. org-log-note-effective-time))
  11998. (cons "%d" (format-time-string
  11999. (org-time-stamp-format nil 'inactive)
  12000. org-log-note-effective-time))
  12001. (cons "%D" (format-time-string
  12002. (org-time-stamp-format nil nil)
  12003. org-log-note-effective-time))
  12004. (cons "%s" (cond
  12005. ((not org-log-note-state) "")
  12006. ((string-match-p org-ts-regexp
  12007. org-log-note-state)
  12008. (format "\"[%s]\""
  12009. (substring org-log-note-state 1 -1)))
  12010. (t (format "\"%s\"" org-log-note-state))))
  12011. (cons "%S"
  12012. (cond
  12013. ((not org-log-note-previous-state) "")
  12014. ((string-match-p org-ts-regexp
  12015. org-log-note-previous-state)
  12016. (format "\"[%s]\""
  12017. (substring
  12018. org-log-note-previous-state 1 -1)))
  12019. (t (format "\"%s\""
  12020. org-log-note-previous-state)))))))
  12021. (when lines (setq note (concat note " \\\\")))
  12022. (push note lines))
  12023. (when (and lines (not org-note-abort))
  12024. (with-current-buffer (marker-buffer org-log-note-marker)
  12025. (org-with-wide-buffer
  12026. ;; Find location for the new note.
  12027. (goto-char org-log-note-marker)
  12028. (set-marker org-log-note-marker nil)
  12029. ;; Note associated to a clock is to be located right after
  12030. ;; the clock. Do not move point.
  12031. (unless (eq org-log-note-purpose 'clock-out)
  12032. (goto-char (org-log-beginning t)))
  12033. ;; Make sure point is at the beginning of an empty line.
  12034. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12035. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12036. ;; In an existing list, add a new item at the top level.
  12037. ;; Otherwise, indent line like a regular one.
  12038. (let ((itemp (org-in-item-p)))
  12039. (if itemp
  12040. (indent-line-to
  12041. (let ((struct (save-excursion
  12042. (goto-char itemp) (org-list-struct))))
  12043. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12044. (org-indent-line)))
  12045. (insert (org-list-bullet-string "-") (pop lines))
  12046. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12047. (dolist (line lines)
  12048. (insert "\n")
  12049. (indent-line-to ind)
  12050. (insert line)))
  12051. (message "Note stored")
  12052. (org-back-to-heading t))
  12053. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12054. ;; from within `org-add-log-note' because `buffer-undo-list'
  12055. ;; is then modified outside of `org-with-remote-undo'.
  12056. (when (eq this-command 'org-agenda-todo)
  12057. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12058. ;; Don't add undo information when called from `org-agenda-todo'.
  12059. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12060. (set-window-configuration org-log-note-window-configuration)
  12061. (with-current-buffer (marker-buffer org-log-note-return-to)
  12062. (goto-char org-log-note-return-to))
  12063. (move-marker org-log-note-return-to nil)
  12064. (when org-log-post-message (message "%s" org-log-post-message))))
  12065. (defun org-remove-empty-drawer-at (pos)
  12066. "Remove an empty drawer at position POS.
  12067. POS may also be a marker."
  12068. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12069. (org-with-wide-buffer
  12070. (goto-char pos)
  12071. (let ((drawer (org-element-at-point)))
  12072. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12073. (not (org-element-property :contents-begin drawer)))
  12074. (delete-region (org-element-property :begin drawer)
  12075. (progn (goto-char (org-element-property :end drawer))
  12076. (skip-chars-backward " \r\t\n")
  12077. (forward-line)
  12078. (point))))))))
  12079. (defvar org-ts-type nil)
  12080. (defun org-sparse-tree (&optional arg type)
  12081. "Create a sparse tree, prompt for the details.
  12082. This command can create sparse trees. You first need to select the type
  12083. of match used to create the tree:
  12084. t Show all TODO entries.
  12085. T Show entries with a specific TODO keyword.
  12086. m Show entries selected by a tags/property match.
  12087. p Enter a property name and its value (both with completion on existing
  12088. names/values) and show entries with that property.
  12089. r Show entries matching a regular expression (`/' can be used as well).
  12090. b Show deadlines and scheduled items before a date.
  12091. a Show deadlines and scheduled items after a date.
  12092. d Show deadlines due within `org-deadline-warning-days'.
  12093. D Show deadlines and scheduled items between a date range."
  12094. (interactive "P")
  12095. (setq type (or type org-sparse-tree-default-date-type))
  12096. (setq org-ts-type type)
  12097. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12098. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12099. \[c]ycle through date types: %s"
  12100. (cl-case type
  12101. (all "all timestamps")
  12102. (scheduled "only scheduled")
  12103. (deadline "only deadline")
  12104. (active "only active timestamps")
  12105. (inactive "only inactive timestamps")
  12106. (closed "with a closed time-stamp")
  12107. (otherwise "scheduled/deadline")))
  12108. (let ((answer (read-char-exclusive)))
  12109. (cl-case answer
  12110. (?c
  12111. (org-sparse-tree
  12112. arg
  12113. (cadr
  12114. (memq type '(nil all scheduled deadline active inactive closed)))))
  12115. (?d (call-interactively 'org-check-deadlines))
  12116. (?b (call-interactively 'org-check-before-date))
  12117. (?a (call-interactively 'org-check-after-date))
  12118. (?D (call-interactively 'org-check-dates-range))
  12119. (?t (call-interactively 'org-show-todo-tree))
  12120. (?T (org-show-todo-tree '(4)))
  12121. (?m (call-interactively 'org-match-sparse-tree))
  12122. ((?p ?P)
  12123. (let* ((kwd (completing-read
  12124. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12125. (value (completing-read
  12126. "Value: " (mapcar #'list (org-property-values kwd)))))
  12127. (unless (string-match "\\`{.*}\\'" value)
  12128. (setq value (concat "\"" value "\"")))
  12129. (org-match-sparse-tree arg (concat kwd "=" value))))
  12130. ((?r ?R ?/) (call-interactively 'org-occur))
  12131. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12132. (defvar-local org-occur-highlights nil
  12133. "List of overlays used for occur matches.")
  12134. (defvar-local org-occur-parameters nil
  12135. "Parameters of the active org-occur calls.
  12136. This is a list, each call to org-occur pushes as cons cell,
  12137. containing the regular expression and the callback, onto the list.
  12138. The list can contain several entries if `org-occur' has been called
  12139. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12140. will only contain one set of parameters. When the highlights are
  12141. removed (for example with `C-c C-c', or with the next edit (depending
  12142. on `org-remove-highlights-with-change'), this variable is emptied
  12143. as well.")
  12144. (defun org-occur (regexp &optional keep-previous callback)
  12145. "Make a compact tree which shows all matches of REGEXP.
  12146. The tree will show the lines where the regexp matches, and any other context
  12147. defined in `org-show-context-detail', which see.
  12148. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12149. done by a previous call to `org-occur' will be kept, to allow stacking of
  12150. calls to this command.
  12151. Optional argument CALLBACK can be a function of no argument. In this case,
  12152. it is called with point at the end of the match, match data being set
  12153. accordingly. Current match is shown only if the return value is non-nil.
  12154. The function must neither move point nor alter narrowing."
  12155. (interactive "sRegexp: \nP")
  12156. (when (equal regexp "")
  12157. (user-error "Regexp cannot be empty"))
  12158. (unless keep-previous
  12159. (org-remove-occur-highlights nil nil t))
  12160. (push (cons regexp callback) org-occur-parameters)
  12161. (let ((cnt 0))
  12162. (save-excursion
  12163. (goto-char (point-min))
  12164. (when (or (not keep-previous) ; do not want to keep
  12165. (not org-occur-highlights)) ; no previous matches
  12166. ;; hide everything
  12167. (org-overview))
  12168. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12169. (isearch-no-upper-case-p regexp t)
  12170. org-occur-case-fold-search)))
  12171. (while (re-search-forward regexp nil t)
  12172. (when (or (not callback)
  12173. (save-match-data (funcall callback)))
  12174. (setq cnt (1+ cnt))
  12175. (when org-highlight-sparse-tree-matches
  12176. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12177. (org-show-context 'occur-tree)))))
  12178. (when org-remove-highlights-with-change
  12179. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12180. nil 'local))
  12181. (unless org-sparse-tree-open-archived-trees
  12182. (org-hide-archived-subtrees (point-min) (point-max)))
  12183. (run-hooks 'org-occur-hook)
  12184. (when (called-interactively-p 'interactive)
  12185. (message "%d match(es) for regexp %s" cnt regexp))
  12186. cnt))
  12187. (defun org-occur-next-match (&optional n _reset)
  12188. "Function for `next-error-function' to find sparse tree matches.
  12189. N is the number of matches to move, when negative move backwards.
  12190. This function always goes back to the starting point when no
  12191. match is found."
  12192. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12193. (search-func (if (< n 0)
  12194. 'previous-single-char-property-change
  12195. 'next-single-char-property-change))
  12196. (n (abs n))
  12197. (pos (point))
  12198. p1)
  12199. (catch 'exit
  12200. (while (setq p1 (funcall search-func (point) 'org-type))
  12201. (when (equal p1 limit)
  12202. (goto-char pos)
  12203. (user-error "No more matches"))
  12204. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12205. (setq n (1- n))
  12206. (when (= n 0)
  12207. (goto-char p1)
  12208. (throw 'exit (point))))
  12209. (goto-char p1))
  12210. (goto-char p1)
  12211. (user-error "No more matches"))))
  12212. (defun org-highlight-new-match (beg end)
  12213. "Highlight from BEG to END and mark the highlight is an occur headline."
  12214. (let ((ov (make-overlay beg end)))
  12215. (overlay-put ov 'face 'secondary-selection)
  12216. (overlay-put ov 'org-type 'org-occur)
  12217. (push ov org-occur-highlights)))
  12218. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12219. "Remove the occur highlights from the buffer.
  12220. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12221. from the `before-change-functions' in the current buffer."
  12222. (interactive)
  12223. (unless org-inhibit-highlight-removal
  12224. (mapc #'delete-overlay org-occur-highlights)
  12225. (setq org-occur-highlights nil)
  12226. (setq org-occur-parameters nil)
  12227. (unless noremove
  12228. (remove-hook 'before-change-functions
  12229. 'org-remove-occur-highlights 'local))))
  12230. ;;;; Priorities
  12231. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12232. "Regular expression matching the priority indicator.")
  12233. (defvar org-remove-priority-next-time nil)
  12234. (defun org-priority-up ()
  12235. "Increase the priority of the current item."
  12236. (interactive)
  12237. (org-priority 'up))
  12238. (defun org-priority-down ()
  12239. "Decrease the priority of the current item."
  12240. (interactive)
  12241. (org-priority 'down))
  12242. (defun org-priority (&optional action show)
  12243. "Change the priority of an item.
  12244. When called interactively with a `\\[universal-argument]' prefix,
  12245. show the priority in the minibuffer instead of changing it.
  12246. When called programatically, ACTION can be `set', `up', `down',
  12247. or a character."
  12248. (interactive "P")
  12249. (when show
  12250. ;; Deprecation warning inserted for Org 9.2; once enough time has
  12251. ;; passed the SHOW argument should be removed.
  12252. (warn "`org-priority' called with deprecated SHOW argument"))
  12253. (if (equal action '(4))
  12254. (org-show-priority)
  12255. (unless org-enable-priority-commands
  12256. (user-error "Priority commands are disabled"))
  12257. (setq action (or action 'set))
  12258. (let (current new news have remove)
  12259. (save-excursion
  12260. (org-back-to-heading t)
  12261. (when (looking-at org-priority-regexp)
  12262. (setq current (string-to-char (match-string 2))
  12263. have t))
  12264. (cond
  12265. ((eq action 'remove)
  12266. (setq remove t new ?\ ))
  12267. ((or (eq action 'set)
  12268. (integerp action))
  12269. (if (not (eq action 'set))
  12270. (setq new action)
  12271. (message "Priority %c-%c, SPC to remove: "
  12272. org-highest-priority org-lowest-priority)
  12273. (save-match-data
  12274. (setq new (read-char-exclusive))))
  12275. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12276. (= (upcase org-lowest-priority) org-lowest-priority))
  12277. (setq new (upcase new)))
  12278. (cond ((equal new ?\s) (setq remove t))
  12279. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12280. (user-error "Priority must be between `%c' and `%c'"
  12281. org-highest-priority org-lowest-priority))))
  12282. ((eq action 'up)
  12283. (setq new (if have
  12284. (1- current) ; normal cycling
  12285. ;; last priority was empty
  12286. (if (eq last-command this-command)
  12287. org-lowest-priority ; wrap around empty to lowest
  12288. ;; default
  12289. (if org-priority-start-cycle-with-default
  12290. org-default-priority
  12291. (1- org-default-priority))))))
  12292. ((eq action 'down)
  12293. (setq new (if have
  12294. (1+ current) ; normal cycling
  12295. ;; last priority was empty
  12296. (if (eq last-command this-command)
  12297. org-highest-priority ; wrap around empty to highest
  12298. ;; default
  12299. (if org-priority-start-cycle-with-default
  12300. org-default-priority
  12301. (1+ org-default-priority))))))
  12302. (t (user-error "Invalid action")))
  12303. (when (or (< (upcase new) org-highest-priority)
  12304. (> (upcase new) org-lowest-priority))
  12305. (if (and (memq action '(up down))
  12306. (not have) (not (eq last-command this-command)))
  12307. ;; `new' is from default priority
  12308. (error
  12309. "The default can not be set, see `org-default-priority' why")
  12310. ;; normal cycling: `new' is beyond highest/lowest priority
  12311. ;; and is wrapped around to the empty priority
  12312. (setq remove t)))
  12313. (setq news (format "%c" new))
  12314. (if have
  12315. (if remove
  12316. (replace-match "" t t nil 1)
  12317. (replace-match news t t nil 2))
  12318. (if remove
  12319. (user-error "No priority cookie found in line")
  12320. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12321. (if (match-end 2)
  12322. (progn
  12323. (goto-char (match-end 2))
  12324. (insert " [#" news "]"))
  12325. (goto-char (match-beginning 3))
  12326. (insert "[#" news "] "))))
  12327. (org-align-tags))
  12328. (if remove
  12329. (message "Priority removed")
  12330. (message "Priority of current item set to %s" news)))))
  12331. (defun org-show-priority ()
  12332. "Show the priority of the current item.
  12333. This priority is composed of the main priority given with the [#A] cookies,
  12334. and by additional input from the age of a schedules or deadline entry."
  12335. (interactive)
  12336. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12337. (org-get-at-bol 'priority)
  12338. (save-excursion
  12339. (save-match-data
  12340. (beginning-of-line)
  12341. (and (looking-at org-heading-regexp)
  12342. (org-get-priority (match-string 0))))))))
  12343. (message "Priority is %d" (if pri pri -1000))))
  12344. (defun org-get-priority (s)
  12345. "Find priority cookie and return priority."
  12346. (save-match-data
  12347. (if (functionp org-get-priority-function)
  12348. (funcall org-get-priority-function)
  12349. (if (not (string-match org-priority-regexp s))
  12350. (* 1000 (- org-lowest-priority org-default-priority))
  12351. (* 1000 (- org-lowest-priority
  12352. (string-to-char (match-string 2 s))))))))
  12353. ;;;; Tags
  12354. (defvar org-agenda-archives-mode)
  12355. (defvar org-map-continue-from nil
  12356. "Position from where mapping should continue.
  12357. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12358. (defvar org-scanner-tags nil
  12359. "The current tag list while the tags scanner is running.")
  12360. (defvar org-trust-scanner-tags nil
  12361. "Should `org-get-tags' use the tags for the scanner.
  12362. This is for internal dynamical scoping only.
  12363. When this is non-nil, the function `org-get-tags' will return the value
  12364. of `org-scanner-tags' instead of building the list by itself. This
  12365. can lead to large speed-ups when the tags scanner is used in a file with
  12366. many entries, and when the list of tags is retrieved, for example to
  12367. obtain a list of properties. Building the tags list for each entry in such
  12368. a file becomes an N^2 operation - but with this variable set, it scales
  12369. as N.")
  12370. (defvar org--matcher-tags-todo-only nil)
  12371. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12372. "Scan headline tags with inheritance and produce output ACTION.
  12373. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12374. or `agenda' to produce an entry list for an agenda view. It can also be
  12375. a Lisp form or a function that should be called at each matched headline, in
  12376. this case the return value is a list of all return values from these calls.
  12377. MATCHER is a function accepting three arguments, returning
  12378. a non-nil value whenever a given set of tags qualifies a headline
  12379. for inclusion. See `org-make-tags-matcher' for more information.
  12380. As a special case, it can also be set to t (respectively nil) in
  12381. order to match all (respectively none) headline.
  12382. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12383. included in the output.
  12384. START-LEVEL can be a string with asterisks, reducing the scope to
  12385. headlines matching this string."
  12386. (require 'org-agenda)
  12387. (let* ((re (concat "^"
  12388. (if start-level
  12389. ;; Get the correct level to match
  12390. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12391. org-outline-regexp)
  12392. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12393. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12394. (props (list 'face 'default
  12395. 'done-face 'org-agenda-done
  12396. 'undone-face 'default
  12397. 'mouse-face 'highlight
  12398. 'org-not-done-regexp org-not-done-regexp
  12399. 'org-todo-regexp org-todo-regexp
  12400. 'org-complex-heading-regexp org-complex-heading-regexp
  12401. 'help-echo
  12402. (format "mouse-2 or RET jump to Org file %S"
  12403. (abbreviate-file-name
  12404. (or (buffer-file-name (buffer-base-buffer))
  12405. (buffer-name (buffer-base-buffer)))))))
  12406. (org-map-continue-from nil)
  12407. lspos tags tags-list
  12408. (tags-alist (list (cons 0 org-file-tags)))
  12409. (llast 0) rtn rtn1 level category i txt
  12410. todo marker entry priority
  12411. ts-date ts-date-type ts-date-pair)
  12412. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12413. (setq action (list 'lambda nil action)))
  12414. (save-excursion
  12415. (goto-char (point-min))
  12416. (when (eq action 'sparse-tree)
  12417. (org-overview)
  12418. (org-remove-occur-highlights))
  12419. (while (let (case-fold-search)
  12420. (re-search-forward re nil t))
  12421. (setq org-map-continue-from nil)
  12422. (catch :skip
  12423. ;; Ignore closing parts of inline tasks.
  12424. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12425. (throw :skip t))
  12426. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  12427. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  12428. (goto-char (setq lspos (match-beginning 0)))
  12429. (setq level (org-reduced-level (org-outline-level))
  12430. category (org-get-category))
  12431. (when (eq action 'agenda)
  12432. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12433. ts-date (car ts-date-pair)
  12434. ts-date-type (cdr ts-date-pair)))
  12435. (setq i llast llast level)
  12436. ;; remove tag lists from same and sublevels
  12437. (while (>= i level)
  12438. (when (setq entry (assoc i tags-alist))
  12439. (setq tags-alist (delete entry tags-alist)))
  12440. (setq i (1- i)))
  12441. ;; add the next tags
  12442. (when tags
  12443. (setq tags (org-split-string tags ":")
  12444. tags-alist
  12445. (cons (cons level tags) tags-alist)))
  12446. ;; compile tags for current headline
  12447. (setq tags-list
  12448. (if org-use-tag-inheritance
  12449. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12450. tags)
  12451. org-scanner-tags tags-list)
  12452. (when org-use-tag-inheritance
  12453. (setcdr (car tags-alist)
  12454. (mapcar (lambda (x)
  12455. (setq x (copy-sequence x))
  12456. (org-add-prop-inherited x))
  12457. (cdar tags-alist))))
  12458. (when (and tags org-use-tag-inheritance
  12459. (or (not (eq t org-use-tag-inheritance))
  12460. org-tags-exclude-from-inheritance))
  12461. ;; Selective inheritance, remove uninherited ones.
  12462. (setcdr (car tags-alist)
  12463. (org-remove-uninherited-tags (cdar tags-alist))))
  12464. (when (and
  12465. ;; eval matcher only when the todo condition is OK
  12466. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12467. (if (functionp matcher)
  12468. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12469. (funcall matcher todo tags-list level))
  12470. matcher))
  12471. ;; Call the skipper, but return t if it does not
  12472. ;; skip, so that the `and' form continues evaluating.
  12473. (progn
  12474. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12475. t)
  12476. ;; Check if timestamps are deselecting this entry
  12477. (or (not todo-only)
  12478. (and (member todo org-todo-keywords-1)
  12479. (or (not org-agenda-tags-todo-honor-ignore-options)
  12480. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12481. ;; select this headline
  12482. (cond
  12483. ((eq action 'sparse-tree)
  12484. (and org-highlight-sparse-tree-matches
  12485. (org-get-heading) (match-end 0)
  12486. (org-highlight-new-match
  12487. (match-beginning 1) (match-end 1)))
  12488. (org-show-context 'tags-tree))
  12489. ((eq action 'agenda)
  12490. (setq txt (org-agenda-format-item
  12491. ""
  12492. (concat
  12493. (if (eq org-tags-match-list-sublevels 'indented)
  12494. (make-string (1- level) ?.) "")
  12495. (org-get-heading))
  12496. (make-string level ?\s)
  12497. category
  12498. tags-list)
  12499. priority (org-get-priority txt))
  12500. (goto-char lspos)
  12501. (setq marker (org-agenda-new-marker))
  12502. (org-add-props txt props
  12503. 'org-marker marker 'org-hd-marker marker 'org-category category
  12504. 'todo-state todo
  12505. 'ts-date ts-date
  12506. 'priority priority
  12507. 'type (concat "tagsmatch" ts-date-type))
  12508. (push txt rtn))
  12509. ((functionp action)
  12510. (setq org-map-continue-from nil)
  12511. (save-excursion
  12512. (setq rtn1 (funcall action))
  12513. (push rtn1 rtn)))
  12514. (t (user-error "Invalid action")))
  12515. ;; if we are to skip sublevels, jump to end of subtree
  12516. (unless org-tags-match-list-sublevels
  12517. (org-end-of-subtree t)
  12518. (backward-char 1))))
  12519. ;; Get the correct position from where to continue
  12520. (if org-map-continue-from
  12521. (goto-char org-map-continue-from)
  12522. (and (= (point) lspos) (end-of-line 1)))))
  12523. (when (and (eq action 'sparse-tree)
  12524. (not org-sparse-tree-open-archived-trees))
  12525. (org-hide-archived-subtrees (point-min) (point-max)))
  12526. (nreverse rtn)))
  12527. (defun org-remove-uninherited-tags (tags)
  12528. "Remove all tags that are not inherited from the list TAGS."
  12529. (cond
  12530. ((eq org-use-tag-inheritance t)
  12531. (if org-tags-exclude-from-inheritance
  12532. (org-delete-all org-tags-exclude-from-inheritance tags)
  12533. tags))
  12534. ((not org-use-tag-inheritance) nil)
  12535. ((stringp org-use-tag-inheritance)
  12536. (delq nil (mapcar
  12537. (lambda (x)
  12538. (if (and (string-match org-use-tag-inheritance x)
  12539. (not (member x org-tags-exclude-from-inheritance)))
  12540. x nil))
  12541. tags)))
  12542. ((listp org-use-tag-inheritance)
  12543. (delq nil (mapcar
  12544. (lambda (x)
  12545. (if (member x org-use-tag-inheritance) x nil))
  12546. tags)))))
  12547. (defun org-match-sparse-tree (&optional todo-only match)
  12548. "Create a sparse tree according to tags string MATCH.
  12549. MATCH is a string with match syntax. It can contain a selection
  12550. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12551. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12552. those. See the manual for details.
  12553. If optional argument TODO-ONLY is non-nil, only select lines that
  12554. are also TODO tasks."
  12555. (interactive "P")
  12556. (org-agenda-prepare-buffers (list (current-buffer)))
  12557. (let ((org--matcher-tags-todo-only todo-only))
  12558. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12559. org--matcher-tags-todo-only)))
  12560. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12561. (defvar org-cached-props nil)
  12562. (defun org-cached-entry-get (pom property)
  12563. (if (or (eq t org-use-property-inheritance)
  12564. (and (stringp org-use-property-inheritance)
  12565. (let ((case-fold-search t))
  12566. (string-match-p org-use-property-inheritance property)))
  12567. (and (listp org-use-property-inheritance)
  12568. (member-ignore-case property org-use-property-inheritance)))
  12569. ;; Caching is not possible, check it directly.
  12570. (org-entry-get pom property 'inherit)
  12571. ;; Get all properties, so we can do complicated checks easily.
  12572. (cdr (assoc-string property
  12573. (or org-cached-props
  12574. (setq org-cached-props (org-entry-properties pom)))
  12575. t))))
  12576. (defun org-global-tags-completion-table (&optional files)
  12577. "Return the list of all tags in all agenda buffer/files.
  12578. Optional FILES argument is a list of files which can be used
  12579. instead of the agenda files."
  12580. (save-excursion
  12581. (org-uniquify
  12582. (delq nil
  12583. (apply #'append
  12584. (mapcar
  12585. (lambda (file)
  12586. (set-buffer (find-file-noselect file))
  12587. (org--tag-add-to-alist
  12588. (org-get-buffer-tags)
  12589. (mapcar (lambda (x)
  12590. (and (stringp (car-safe x))
  12591. (list (car-safe x))))
  12592. org-current-tag-alist)))
  12593. (if (car-safe files) files
  12594. (org-agenda-files))))))))
  12595. (defun org-make-tags-matcher (match)
  12596. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12597. Returns a cons of the selection string MATCH and a function
  12598. implementing the matcher.
  12599. The matcher is to be called at an Org entry, with point on the
  12600. headline, and returns non-nil if the entry matches the selection
  12601. string MATCH. It must be called with three arguments: the TODO
  12602. keyword at the entry (or nil if none), the list of all tags at
  12603. the entry including inherited ones and the reduced level of the
  12604. headline. Additionally, the category of the entry, if any, must
  12605. be specified as the text property `org-category' on the headline.
  12606. This function sets the variable `org--matcher-tags-todo-only' to
  12607. a non-nil value if the matcher restricts matching to TODO
  12608. entries, otherwise it is not touched.
  12609. See also `org-scan-tags'."
  12610. (unless match
  12611. ;; Get a new match request, with completion against the global
  12612. ;; tags table and the local tags in current buffer.
  12613. (let ((org-last-tags-completion-table
  12614. (org--tag-add-to-alist
  12615. (org-get-buffer-tags)
  12616. (org-global-tags-completion-table))))
  12617. (setq match
  12618. (completing-read
  12619. "Match: "
  12620. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12621. (let ((match0 match)
  12622. (re (concat
  12623. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12624. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12625. "\\([<>=]\\{1,2\\}\\)"
  12626. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12627. "\\|" org-tag-re "\\)"))
  12628. (start 0)
  12629. tagsmatch todomatch tagsmatcher todomatcher)
  12630. ;; Expand group tags.
  12631. (setq match (org-tags-expand match))
  12632. ;; Check if there is a TODO part of this match, which would be the
  12633. ;; part after a "/". To make sure that this slash is not part of
  12634. ;; a property value to be matched against, we also check that
  12635. ;; there is no / after that slash. First, find the last slash.
  12636. (let ((s 0))
  12637. (while (string-match "/+" match s)
  12638. (setq start (match-beginning 0))
  12639. (setq s (match-end 0))))
  12640. (if (and (string-match "/+" match start)
  12641. (not (string-match-p "\"" match start)))
  12642. ;; Match contains also a TODO-matching request.
  12643. (progn
  12644. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12645. (setq todomatch (substring match (match-end 0)))
  12646. (when (string-prefix-p "!" todomatch)
  12647. (setq org--matcher-tags-todo-only t)
  12648. (setq todomatch (substring todomatch 1)))
  12649. (when (string-match "\\`\\s-*\\'" todomatch)
  12650. (setq todomatch nil)))
  12651. ;; Only matching tags.
  12652. (setq tagsmatch match)
  12653. (setq todomatch nil))
  12654. ;; Make the tags matcher.
  12655. (when (org-string-nw-p tagsmatch)
  12656. (let ((orlist nil)
  12657. (orterms (org-split-string tagsmatch "|"))
  12658. term)
  12659. (while (setq term (pop orterms))
  12660. (while (and (equal (substring term -1) "\\") orterms)
  12661. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12662. (while (string-match re term)
  12663. (let* ((rest (substring term (match-end 0)))
  12664. (minus (and (match-end 1)
  12665. (equal (match-string 1 term) "-")))
  12666. (tag (save-match-data
  12667. (replace-regexp-in-string
  12668. "\\\\-" "-" (match-string 2 term))))
  12669. (regexp (eq (string-to-char tag) ?{))
  12670. (levelp (match-end 4))
  12671. (propp (match-end 5))
  12672. (mm
  12673. (cond
  12674. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12675. (levelp
  12676. `(,(org-op-to-function (match-string 3 term))
  12677. level
  12678. ,(string-to-number (match-string 4 term))))
  12679. (propp
  12680. (let* ((gv (pcase (upcase (match-string 5 term))
  12681. ("CATEGORY"
  12682. '(get-text-property (point) 'org-category))
  12683. ("TODO" 'todo)
  12684. (p `(org-cached-entry-get nil ,p))))
  12685. (pv (match-string 7 term))
  12686. (regexp (eq (string-to-char pv) ?{))
  12687. (strp (eq (string-to-char pv) ?\"))
  12688. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12689. (po (org-op-to-function (match-string 6 term)
  12690. (if timep 'time strp))))
  12691. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12692. (when timep (setq pv (org-matcher-time pv)))
  12693. (cond ((and regexp (eq po '/=))
  12694. `(not (string-match ,pv (or ,gv ""))))
  12695. (regexp `(string-match ,pv (or ,gv "")))
  12696. (strp `(,po (or ,gv "") ,pv))
  12697. (t
  12698. `(,po
  12699. (string-to-number (or ,gv ""))
  12700. ,(string-to-number pv))))))
  12701. (t `(member ,tag tags-list)))))
  12702. (push (if minus `(not ,mm) mm) tagsmatcher)
  12703. (setq term rest)))
  12704. (push `(and ,@tagsmatcher) orlist)
  12705. (setq tagsmatcher nil))
  12706. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12707. ;; Make the TODO matcher.
  12708. (when (org-string-nw-p todomatch)
  12709. (let ((orlist nil))
  12710. (dolist (term (org-split-string todomatch "|"))
  12711. (while (string-match re term)
  12712. (let* ((minus (and (match-end 1)
  12713. (equal (match-string 1 term) "-")))
  12714. (kwd (match-string 2 term))
  12715. (regexp (eq (string-to-char kwd) ?{))
  12716. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12717. `(equal todo ,kwd))))
  12718. (push (if minus `(not ,mm) mm) todomatcher))
  12719. (setq term (substring term (match-end 0))))
  12720. (push (if (> (length todomatcher) 1)
  12721. (cons 'and todomatcher)
  12722. (car todomatcher))
  12723. orlist)
  12724. (setq todomatcher nil))
  12725. (setq todomatcher (cons 'or orlist))))
  12726. ;; Return the string and function of the matcher. If no
  12727. ;; tags-specific or todo-specific matcher exists, match
  12728. ;; everything.
  12729. (let ((matcher (if (and tagsmatcher todomatcher)
  12730. `(and ,tagsmatcher ,todomatcher)
  12731. (or tagsmatcher todomatcher t))))
  12732. (when org--matcher-tags-todo-only
  12733. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12734. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12735. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12736. "Expand group tags in MATCH.
  12737. This replaces every group tag in MATCH with a regexp tag search.
  12738. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12739. will be replaced like this:
  12740. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12741. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12742. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12743. Replacing by a regexp preserves the structure of the match.
  12744. E.g., this expansion
  12745. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12746. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12747. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12748. A group tag in MATCH can contain regular expressions of its own.
  12749. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12750. will be replaced like this:
  12751. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12752. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12753. assumed to be a single group tag, and the function will return
  12754. the list of tags in this group.
  12755. When DOWNCASE is non-nil, expand downcased TAGS."
  12756. (if org-group-tags
  12757. (let* ((case-fold-search t)
  12758. (stable org-mode-syntax-table)
  12759. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12760. (taggroups (if downcased
  12761. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12762. taggroups)
  12763. taggroups))
  12764. (taggroups-keys (mapcar #'car taggroups))
  12765. (return-match (if downcased (downcase match) match))
  12766. (count 0)
  12767. (work-already-expanded tags-already-expanded)
  12768. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12769. ;; @ and _ are allowed as word-components in tags.
  12770. (modify-syntax-entry ?@ "w" stable)
  12771. (modify-syntax-entry ?_ "w" stable)
  12772. ;; Temporarily replace regexp-expressions in the match-expression.
  12773. (while (string-match "{.+?}" return-match)
  12774. (cl-incf count)
  12775. (push (match-string 0 return-match) regexps-in-match)
  12776. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12777. (while (and taggroups-keys
  12778. (with-syntax-table stable
  12779. (string-match
  12780. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12781. (regexp-opt taggroups-keys) "\\>\\)")
  12782. return-match)))
  12783. (let* ((dir (match-string 1 return-match))
  12784. (tag (match-string 2 return-match))
  12785. (tag (if downcased (downcase tag) tag)))
  12786. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12787. (member tag tags-already-expanded))
  12788. (setq tags-in-group (assoc tag taggroups))
  12789. (push tag work-already-expanded)
  12790. ;; Recursively expand each tag in the group, if the tag hasn't
  12791. ;; already been expanded. Restore the match-data after all recursive calls.
  12792. (save-match-data
  12793. (let (tags-expanded)
  12794. (dolist (x (cdr tags-in-group))
  12795. (if (and (member x taggroups-keys)
  12796. (not (member x work-already-expanded)))
  12797. (setq tags-expanded
  12798. (delete-dups
  12799. (append
  12800. (org-tags-expand x t downcased
  12801. work-already-expanded)
  12802. tags-expanded)))
  12803. (setq tags-expanded
  12804. (append (list x) tags-expanded)))
  12805. (setq work-already-expanded
  12806. (delete-dups
  12807. (append tags-expanded
  12808. work-already-expanded))))
  12809. (setq tags-in-group
  12810. (delete-dups (cons (car tags-in-group)
  12811. tags-expanded)))))
  12812. ;; Filter tag-regexps from tags.
  12813. (setq regexp-in-group-escaped
  12814. (delq nil (mapcar (lambda (x)
  12815. (if (stringp x)
  12816. (and (equal "{" (substring x 0 1))
  12817. (equal "}" (substring x -1))
  12818. x)
  12819. x))
  12820. tags-in-group))
  12821. regexp-in-group
  12822. (mapcar (lambda (x)
  12823. (substring x 1 -1))
  12824. regexp-in-group-escaped)
  12825. tags-in-group
  12826. (delq nil (mapcar (lambda (x)
  12827. (if (stringp x)
  12828. (and (not (equal "{" (substring x 0 1)))
  12829. (not (equal "}" (substring x -1)))
  12830. x)
  12831. x))
  12832. tags-in-group)))
  12833. ;; If single-as-list, do no more in the while-loop.
  12834. (if (not single-as-list)
  12835. (progn
  12836. (when regexp-in-group
  12837. (setq regexp-in-group
  12838. (concat "\\|"
  12839. (mapconcat 'identity regexp-in-group
  12840. "\\|"))))
  12841. (setq tags-in-group
  12842. (concat dir
  12843. "{\\<"
  12844. (regexp-opt tags-in-group)
  12845. "\\>"
  12846. regexp-in-group
  12847. "}"))
  12848. (when (stringp tags-in-group)
  12849. (org-add-props tags-in-group '(grouptag t)))
  12850. (setq return-match
  12851. (replace-match tags-in-group t t return-match)))
  12852. (setq tags-in-group
  12853. (append regexp-in-group-escaped tags-in-group))))
  12854. (setq taggroups-keys (delete tag taggroups-keys))))
  12855. ;; Add the regular expressions back into the match-expression again.
  12856. (while regexps-in-match
  12857. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12858. (pop regexps-in-match)
  12859. return-match t t))
  12860. (cl-decf count))
  12861. (if single-as-list
  12862. (if tags-in-group tags-in-group (list return-match))
  12863. return-match))
  12864. (if single-as-list
  12865. (list (if downcased (downcase match) match))
  12866. match)))
  12867. (defun org-op-to-function (op &optional stringp)
  12868. "Turn an operator into the appropriate function."
  12869. (setq op
  12870. (cond
  12871. ((equal op "<" ) '(< org-string< org-time<))
  12872. ((equal op ">" ) '(> org-string> org-time>))
  12873. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12874. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12875. ((member op '("=" "==")) '(= string= org-time=))
  12876. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12877. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12878. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12879. (defvar org-tags-overlay (make-overlay 1 1))
  12880. (delete-overlay org-tags-overlay)
  12881. (defun org-add-prop-inherited (s)
  12882. (add-text-properties 0 (length s) '(inherited t) s)
  12883. s)
  12884. (defun org-toggle-tag (tag &optional onoff)
  12885. "Toggle the tag TAG for the current line.
  12886. If ONOFF is `on' or `off', don't toggle but set to this state."
  12887. (save-excursion
  12888. (org-back-to-heading t)
  12889. (let ((current
  12890. ;; Reverse the tags list so any new tag is appended to the
  12891. ;; current list of tags.
  12892. (nreverse (org-get-tags nil t)))
  12893. res)
  12894. (pcase onoff
  12895. (`off (setq current (delete tag current)))
  12896. ((or `on (guard (not (member tag current))))
  12897. (setq res t)
  12898. (cl-pushnew tag current :test #'equal))
  12899. (_ (setq current (delete tag current))))
  12900. (org-set-tags (nreverse current))
  12901. res)))
  12902. (defun org--align-tags-here (to-col)
  12903. "Align tags on the current headline to TO-COL.
  12904. Assume point is on a headline. Preserve point when aligning
  12905. tags."
  12906. (when (org-match-line org-tag-line-re)
  12907. (let* ((tags-start (match-beginning 1))
  12908. (blank-start (save-excursion
  12909. (goto-char tags-start)
  12910. (skip-chars-backward " \t")
  12911. (point)))
  12912. (new (max (if (>= to-col 0) to-col
  12913. (- (abs to-col) (string-width (match-string 1))))
  12914. ;; Introduce at least one space after the heading
  12915. ;; or the stars.
  12916. (save-excursion
  12917. (goto-char blank-start)
  12918. (1+ (current-column)))))
  12919. (current
  12920. (save-excursion (goto-char tags-start) (current-column)))
  12921. (origin (point-marker))
  12922. (column (current-column))
  12923. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  12924. (when (/= new current)
  12925. (delete-region blank-start tags-start)
  12926. (goto-char blank-start)
  12927. (let ((indent-tabs-mode nil)) (indent-to new))
  12928. ;; Try to move back to original position. If point was in the
  12929. ;; blanks before the tags, ORIGIN marker is of no use because
  12930. ;; it now points to BLANK-START. Use COLUMN instead.
  12931. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  12932. (defun org-set-tags-command (&optional arg)
  12933. "Set the tags for the current visible entry.
  12934. When called with `\\[universal-argument]' prefix argument ARG, \
  12935. realign all tags
  12936. in the current buffer. If a region is active, set tags for
  12937. all headlines in the region.
  12938. This function is for interactive use only;
  12939. in Lisp code use `org-set-tags' instead."
  12940. (interactive "P")
  12941. (cond
  12942. (arg (org-align-tags t))
  12943. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12944. ;; Disable `org-loop-over-headlines-in-active-region' for
  12945. ;; successive calls.
  12946. (let (org-loop-over-headlines-in-active-region)
  12947. (org-map-entries
  12948. #'org-set-tags-command
  12949. nil
  12950. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12951. 'region-start-level
  12952. 'region)
  12953. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  12954. (t
  12955. (save-excursion
  12956. (org-back-to-heading)
  12957. (let* ((all-tags (org-get-tags))
  12958. (table (setq org-last-tags-completion-table
  12959. (org--tag-add-to-alist
  12960. (and org-complete-tags-always-offer-all-agenda-tags
  12961. (org-global-tags-completion-table
  12962. (org-agenda-files)))
  12963. (or org-current-tag-alist (org-get-buffer-tags)))))
  12964. (current-tags
  12965. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  12966. all-tags))
  12967. (inherited-tags
  12968. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  12969. all-tags))
  12970. (tags
  12971. (replace-regexp-in-string
  12972. ;; Ignore all forbidden characters in tags.
  12973. "[^[:alnum:]_@#%]+" ":"
  12974. (if (or (eq t org-use-fast-tag-selection)
  12975. (and org-use-fast-tag-selection
  12976. (delq nil (mapcar #'cdr table))))
  12977. (org-fast-tag-selection
  12978. current-tags
  12979. inherited-tags
  12980. table
  12981. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  12982. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  12983. (org-trim (completing-read
  12984. "Tags: "
  12985. #'org-tags-completion-function
  12986. nil nil (org-make-tag-string current-tags)
  12987. 'org-tags-history)))))))
  12988. (org-set-tags tags))))))
  12989. (defun org-align-tags (&optional all)
  12990. "Align tags in current entry.
  12991. When optional argument ALL is non-nil, align all tags in the
  12992. visible part of the buffer."
  12993. (let ((get-indent-column
  12994. (lambda ()
  12995. (let ((offset (if (bound-and-true-p org-indent-mode)
  12996. (* (1- org-indent-indentation-per-level)
  12997. (1- (org-current-level)))
  12998. 0)))
  12999. (+ org-tags-column
  13000. (if (> org-tags-column 0) (- offset) offset))))))
  13001. (if (and (not all) (org-at-heading-p))
  13002. (org--align-tags-here (funcall get-indent-column))
  13003. (save-excursion
  13004. (if all
  13005. (while (re-search-forward org-tag-line-re nil t)
  13006. (org--align-tags-here (funcall get-indent-column)))
  13007. (org-back-to-heading t)
  13008. (org--align-tags-here (funcall get-indent-column)))))))
  13009. (defun org-set-tags (tags)
  13010. "Set the tags of the current entry to TAGS, replacing current tags.
  13011. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  13012. If TAGS is nil or the empty string, all tags are removed.
  13013. This function assumes point is on a headline."
  13014. (org-with-wide-buffer
  13015. (let ((tags (pcase tags
  13016. ((pred listp) tags)
  13017. ((pred stringp) (split-string (org-trim tags) ":" t))
  13018. (_ (error "Invalid tag specification: %S" tags))))
  13019. (old-tags (org-get-tags nil t))
  13020. (tags-change? nil))
  13021. (when (functionp org-tags-sort-function)
  13022. (setq tags (sort tags org-tags-sort-function)))
  13023. (setq tags-change? (not (equal tags old-tags)))
  13024. (when tags-change?
  13025. ;; Delete previous tags and any trailing white space.
  13026. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  13027. (line-end-position)))
  13028. (skip-chars-backward " \t")
  13029. (delete-region (point) (line-end-position))
  13030. ;; Deleting white spaces may break an otherwise empty headline.
  13031. ;; Re-introduce one space in this case.
  13032. (unless (org-at-heading-p) (insert " "))
  13033. (when tags
  13034. (save-excursion (insert " " (org-make-tag-string tags)))
  13035. ;; When text is being inserted on an invisible region
  13036. ;; boundary, it can be inadvertently sucked into
  13037. ;; invisibility.
  13038. (unless (org-invisible-p (line-beginning-position))
  13039. (org-flag-region (point) (line-end-position) nil 'outline))))
  13040. ;; Align tags, if any.
  13041. (when tags (org-align-tags))
  13042. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  13043. (defun org-change-tag-in-region (beg end tag off)
  13044. "Add or remove TAG for each entry in the region.
  13045. This works in the agenda, and also in an Org buffer."
  13046. (interactive
  13047. (list (region-beginning) (region-end)
  13048. (let ((org-last-tags-completion-table
  13049. (if (derived-mode-p 'org-mode)
  13050. (org--tag-add-to-alist
  13051. (org-get-buffer-tags)
  13052. (org-global-tags-completion-table))
  13053. (org-global-tags-completion-table))))
  13054. (completing-read
  13055. "Tag: " 'org-tags-completion-function nil nil nil
  13056. 'org-tags-history))
  13057. (progn
  13058. (message "[s]et or [r]emove? ")
  13059. (equal (read-char-exclusive) ?r))))
  13060. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13061. (let ((agendap (equal major-mode 'org-agenda-mode))
  13062. l1 l2 m buf pos newhead (cnt 0))
  13063. (goto-char end)
  13064. (setq l2 (1- (org-current-line)))
  13065. (goto-char beg)
  13066. (setq l1 (org-current-line))
  13067. (cl-loop for l from l1 to l2 do
  13068. (org-goto-line l)
  13069. (setq m (get-text-property (point) 'org-hd-marker))
  13070. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13071. (and agendap m))
  13072. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13073. pos (if agendap m (point)))
  13074. (with-current-buffer buf
  13075. (save-excursion
  13076. (save-restriction
  13077. (goto-char pos)
  13078. (setq cnt (1+ cnt))
  13079. (org-toggle-tag tag (if off 'off 'on))
  13080. (setq newhead (org-get-heading)))))
  13081. (and agendap (org-agenda-change-all-lines newhead m))))
  13082. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13083. (defun org-tags-completion-function (string _predicate &optional flag)
  13084. "Complete tag STRING.
  13085. FLAG specifies the type of completion operation to perform. This
  13086. function is passed as a collection function to `completing-read',
  13087. which see."
  13088. (let ((completion-ignore-case nil) ;tags are case-sensitive
  13089. (confirm (lambda (x) (stringp (car x))))
  13090. (prefix ""))
  13091. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13092. (setq prefix (match-string 1 string))
  13093. (setq string (match-string 2 string)))
  13094. (pcase flag
  13095. (`t (all-completions string org-last-tags-completion-table confirm))
  13096. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  13097. (`nil
  13098. (pcase (try-completion string org-last-tags-completion-table confirm)
  13099. ((and completion (pred stringp))
  13100. (concat prefix
  13101. completion
  13102. (if (and org-add-colon-after-tag-completion
  13103. (assoc completion org-last-tags-completion-table))
  13104. ":"
  13105. "")))
  13106. (completion completion)))
  13107. (_ nil))))
  13108. (defun org-fast-tag-insert (kwd tags face &optional end)
  13109. "Insert KWD, and the TAGS, the latter with face FACE.
  13110. Also insert END."
  13111. (insert (format "%-12s" (concat kwd ":"))
  13112. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13113. (or end "")))
  13114. (defun org-fast-tag-show-exit (flag)
  13115. (save-excursion
  13116. (org-goto-line 3)
  13117. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13118. (replace-match ""))
  13119. (when flag
  13120. (end-of-line 1)
  13121. (org-move-to-column (- (window-width) 19) t)
  13122. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13123. (defun org-set-current-tags-overlay (current prefix)
  13124. "Add an overlay to CURRENT tag with PREFIX."
  13125. (let ((s (org-make-tag-string current)))
  13126. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13127. (org-overlay-display org-tags-overlay (concat prefix s))))
  13128. (defvar org-last-tag-selection-key nil)
  13129. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13130. "Fast tag selection with single keys.
  13131. CURRENT is the current list of tags in the headline, INHERITED is the
  13132. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13133. possibly with grouping information. TODO-TABLE is a similar table with
  13134. TODO keywords, should these have keys assigned to them.
  13135. If the keys are nil, a-z are automatically assigned.
  13136. Returns the new tags string, or nil to not change the current settings."
  13137. (let* ((fulltable (append table todo-table))
  13138. (maxlen (if (null fulltable) 0
  13139. (apply #'max
  13140. (mapcar (lambda (x)
  13141. (if (stringp (car x)) (string-width (car x))
  13142. 0))
  13143. fulltable))))
  13144. (buf (current-buffer))
  13145. (expert (eq org-fast-tag-selection-single-key 'expert))
  13146. (buffer-tags nil)
  13147. (fwidth (+ maxlen 3 1 3))
  13148. (ncol (/ (- (window-width) 4) fwidth))
  13149. (i-face 'org-done)
  13150. (c-face 'org-todo)
  13151. tg cnt e c char c1 c2 ntable tbl rtn
  13152. ov-start ov-end ov-prefix
  13153. (exit-after-next org-fast-tag-selection-single-key)
  13154. (done-keywords org-done-keywords)
  13155. groups ingroup intaggroup)
  13156. (save-excursion
  13157. (beginning-of-line)
  13158. (if (looking-at org-tag-line-re)
  13159. (setq ov-start (match-beginning 1)
  13160. ov-end (match-end 1)
  13161. ov-prefix "")
  13162. (setq ov-start (1- (point-at-eol))
  13163. ov-end (1+ ov-start))
  13164. (skip-chars-forward "^\n\r")
  13165. (setq ov-prefix
  13166. (concat
  13167. (buffer-substring (1- (point)) (point))
  13168. (if (> (current-column) org-tags-column)
  13169. " "
  13170. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13171. (move-overlay org-tags-overlay ov-start ov-end)
  13172. (save-window-excursion
  13173. (if expert
  13174. (set-buffer (get-buffer-create " *Org tags*"))
  13175. (delete-other-windows)
  13176. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13177. (org-switch-to-buffer-other-window " *Org tags*"))
  13178. (erase-buffer)
  13179. (setq-local org-done-keywords done-keywords)
  13180. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13181. (org-fast-tag-insert "Current" current c-face "\n\n")
  13182. (org-fast-tag-show-exit exit-after-next)
  13183. (org-set-current-tags-overlay current ov-prefix)
  13184. (setq tbl fulltable char ?a cnt 0)
  13185. (while (setq e (pop tbl))
  13186. (cond
  13187. ((eq (car e) :startgroup)
  13188. (push '() groups) (setq ingroup t)
  13189. (unless (zerop cnt)
  13190. (setq cnt 0)
  13191. (insert "\n"))
  13192. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13193. ((eq (car e) :endgroup)
  13194. (setq ingroup nil cnt 0)
  13195. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13196. ((eq (car e) :startgrouptag)
  13197. (setq intaggroup t)
  13198. (unless (zerop cnt)
  13199. (setq cnt 0)
  13200. (insert "\n"))
  13201. (insert "[ "))
  13202. ((eq (car e) :endgrouptag)
  13203. (setq intaggroup nil cnt 0)
  13204. (insert "]\n"))
  13205. ((equal e '(:newline))
  13206. (unless (zerop cnt)
  13207. (setq cnt 0)
  13208. (insert "\n")
  13209. (setq e (car tbl))
  13210. (while (equal (car tbl) '(:newline))
  13211. (insert "\n")
  13212. (setq tbl (cdr tbl)))))
  13213. ((equal e '(:grouptags)) (insert " : "))
  13214. (t
  13215. (setq tg (copy-sequence (car e)) c2 nil)
  13216. (if (cdr e)
  13217. (setq c (cdr e))
  13218. ;; automatically assign a character.
  13219. (setq c1 (string-to-char
  13220. (downcase (substring
  13221. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13222. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13223. (while (or (rassoc char ntable) (rassoc char table))
  13224. (setq char (1+ char)))
  13225. (setq c2 c1))
  13226. (setq c (or c2 char)))
  13227. (when ingroup (push tg (car groups)))
  13228. (setq tg (org-add-props tg nil 'face
  13229. (cond
  13230. ((not (assoc tg table))
  13231. (org-get-todo-face tg))
  13232. ((member tg current) c-face)
  13233. ((member tg inherited) i-face))))
  13234. (when (equal (caar tbl) :grouptags)
  13235. (org-add-props tg nil 'face 'org-tag-group))
  13236. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13237. (insert "[" c "] " tg (make-string
  13238. (- fwidth 4 (length tg)) ?\ ))
  13239. (push (cons tg c) ntable)
  13240. (when (= (cl-incf cnt) ncol)
  13241. (insert "\n")
  13242. (when (or ingroup intaggroup) (insert " "))
  13243. (setq cnt 0)))))
  13244. (setq ntable (nreverse ntable))
  13245. (insert "\n")
  13246. (goto-char (point-min))
  13247. (unless expert (org-fit-window-to-buffer))
  13248. (setq rtn
  13249. (catch 'exit
  13250. (while t
  13251. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13252. (if (not groups) "no " "")
  13253. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13254. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13255. (setq org-last-tag-selection-key c)
  13256. (cond
  13257. ((= c ?\r) (throw 'exit t))
  13258. ((= c ?!)
  13259. (setq groups (not groups))
  13260. (goto-char (point-min))
  13261. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13262. ((= c ?\C-c)
  13263. (if (not expert)
  13264. (org-fast-tag-show-exit
  13265. (setq exit-after-next (not exit-after-next)))
  13266. (setq expert nil)
  13267. (delete-other-windows)
  13268. (set-window-buffer (split-window-vertically) " *Org tags*")
  13269. (org-switch-to-buffer-other-window " *Org tags*")
  13270. (org-fit-window-to-buffer)))
  13271. ((or (= c ?\C-g)
  13272. (and (= c ?q) (not (rassoc c ntable))))
  13273. (delete-overlay org-tags-overlay)
  13274. (setq quit-flag t))
  13275. ((= c ?\ )
  13276. (setq current nil)
  13277. (when exit-after-next (setq exit-after-next 'now)))
  13278. ((= c ?\t)
  13279. (condition-case nil
  13280. (setq tg (completing-read
  13281. "Tag: "
  13282. (or buffer-tags
  13283. (with-current-buffer buf
  13284. (setq buffer-tags
  13285. (org-get-buffer-tags))))))
  13286. (quit (setq tg "")))
  13287. (when (string-match "\\S-" tg)
  13288. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13289. (if (member tg current)
  13290. (setq current (delete tg current))
  13291. (push tg current)))
  13292. (when exit-after-next (setq exit-after-next 'now)))
  13293. ((setq e (rassoc c todo-table) tg (car e))
  13294. (with-current-buffer buf
  13295. (save-excursion (org-todo tg)))
  13296. (when exit-after-next (setq exit-after-next 'now)))
  13297. ((setq e (rassoc c ntable) tg (car e))
  13298. (if (member tg current)
  13299. (setq current (delete tg current))
  13300. (cl-loop for g in groups do
  13301. (when (member tg g)
  13302. (dolist (x g) (setq current (delete x current)))))
  13303. (push tg current))
  13304. (when exit-after-next (setq exit-after-next 'now))))
  13305. ;; Create a sorted list
  13306. (setq current
  13307. (sort current
  13308. (lambda (a b)
  13309. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13310. (when (eq exit-after-next 'now) (throw 'exit t))
  13311. (goto-char (point-min))
  13312. (beginning-of-line 2)
  13313. (delete-region (point) (point-at-eol))
  13314. (org-fast-tag-insert "Current" current c-face)
  13315. (org-set-current-tags-overlay current ov-prefix)
  13316. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13317. (while (re-search-forward tag-re nil t)
  13318. (let ((tag (match-string 1)))
  13319. (add-text-properties
  13320. (match-beginning 1) (match-end 1)
  13321. (list 'face
  13322. (cond
  13323. ((member tag current) c-face)
  13324. ((member tag inherited) i-face)
  13325. (t (get-text-property (match-beginning 1) '
  13326. face))))))))
  13327. (goto-char (point-min)))))
  13328. (delete-overlay org-tags-overlay)
  13329. (if rtn
  13330. (mapconcat 'identity current ":")
  13331. nil))))
  13332. (defun org-make-tag-string (tags)
  13333. "Return string associated to TAGS.
  13334. TAGS is a list of strings."
  13335. (if (null tags) ""
  13336. (format ":%s:" (mapconcat #'identity tags ":"))))
  13337. (defun org--get-local-tags ()
  13338. "Return list of tags for the current headline.
  13339. Assume point is at the beginning of the headline."
  13340. (and (looking-at org-tag-line-re)
  13341. (split-string (match-string-no-properties 2) ":" t)))
  13342. (defun org-get-tags (&optional pos local)
  13343. "Get the list of tags specified in the current headline.
  13344. When argument POS is non-nil, retrieve tags for headline at POS.
  13345. Accoring to `org-use-tags-inheritance', tags may be inherited
  13346. from parent headlines, and from the whole document, through
  13347. `org-file-tags'. However, when optional argument LOCAL is
  13348. non-nil, only return tags really specified in the considered
  13349. headline.
  13350. Inherited tags have the `inherited' text property."
  13351. (if (and org-trust-scanner-tags
  13352. (or (not pos) (eq pos (point)))
  13353. (not local))
  13354. org-scanner-tags
  13355. (org-with-point-at (or pos (point))
  13356. (unless (org-before-first-heading-p)
  13357. (org-back-to-heading t)
  13358. (let ((tags (org--get-local-tags)))
  13359. (if (or local (not org-use-tag-inheritance)) tags
  13360. (while (org-up-heading-safe)
  13361. (setq tags (append (mapcar #'org-add-prop-inherited
  13362. (org--get-local-tags))
  13363. tags)))
  13364. (org-remove-uninherited-tags
  13365. (delete-dups (append org-file-tags tags)))))))))
  13366. (defun org-get-buffer-tags ()
  13367. "Get a table of all tags used in the buffer, for completion."
  13368. (org-with-point-at 1
  13369. (let (tags)
  13370. (while (re-search-forward org-tag-line-re nil t)
  13371. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13372. tags)))
  13373. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13374. ;;;; The mapping API
  13375. (defvar org-agenda-skip-comment-trees)
  13376. (defvar org-agenda-skip-function)
  13377. (defun org-map-entries (func &optional match scope &rest skip)
  13378. "Call FUNC at each headline selected by MATCH in SCOPE.
  13379. FUNC is a function or a lisp form. The function will be called without
  13380. arguments, with the cursor positioned at the beginning of the headline.
  13381. The return values of all calls to the function will be collected and
  13382. returned as a list.
  13383. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13384. does not need to preserve point. After evaluation, the cursor will be
  13385. moved to the end of the line (presumably of the headline of the
  13386. processed entry) and search continues from there. Under some
  13387. circumstances, this may not produce the wanted results. For example,
  13388. if you have removed (e.g. archived) the current (sub)tree it could
  13389. mean that the next entry will be skipped entirely. In such cases, you
  13390. can specify the position from where search should continue by making
  13391. FUNC set the variable `org-map-continue-from' to the desired buffer
  13392. position.
  13393. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13394. Only headlines that are matched by this query will be considered during
  13395. the iteration. When MATCH is nil or t, all headlines will be
  13396. visited by the iteration.
  13397. SCOPE determines the scope of this command. It can be any of:
  13398. nil The current buffer, respecting the restriction if any
  13399. tree The subtree started with the entry at point
  13400. region The entries within the active region, if any
  13401. region-start-level
  13402. The entries within the active region, but only those at
  13403. the same level than the first one.
  13404. file The current buffer, without restriction
  13405. file-with-archives
  13406. The current buffer, and any archives associated with it
  13407. agenda All agenda files
  13408. agenda-with-archives
  13409. All agenda files with any archive files associated with them
  13410. \(file1 file2 ...)
  13411. If this is a list, all files in the list will be scanned
  13412. The remaining args are treated as settings for the skipping facilities of
  13413. the scanner. The following items can be given here:
  13414. archive skip trees with the archive tag
  13415. comment skip trees with the COMMENT keyword
  13416. function or Emacs Lisp form:
  13417. will be used as value for `org-agenda-skip-function', so
  13418. whenever the function returns a position, FUNC will not be
  13419. called for that entry and search will continue from the
  13420. position returned
  13421. If your function needs to retrieve the tags including inherited tags
  13422. at the *current* entry, you can use the value of the variable
  13423. `org-scanner-tags' which will be much faster than getting the value
  13424. with `org-get-tags'. If your function gets properties with
  13425. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13426. to t around the call to `org-entry-properties' to get the same speedup.
  13427. Note that if your function moves around to retrieve tags and properties at
  13428. a *different* entry, you cannot use these techniques."
  13429. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13430. (not (org-region-active-p)))
  13431. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13432. (org-agenda-skip-archived-trees (memq 'archive skip))
  13433. (org-agenda-skip-comment-trees (memq 'comment skip))
  13434. (org-agenda-skip-function
  13435. (car (org-delete-all '(comment archive) skip)))
  13436. (org-tags-match-list-sublevels t)
  13437. (start-level (eq scope 'region-start-level))
  13438. matcher res
  13439. org-todo-keywords-for-agenda
  13440. org-done-keywords-for-agenda
  13441. org-todo-keyword-alist-for-agenda
  13442. org-tag-alist-for-agenda
  13443. org--matcher-tags-todo-only)
  13444. (cond
  13445. ((eq match t) (setq matcher t))
  13446. ((eq match nil) (setq matcher t))
  13447. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13448. (save-excursion
  13449. (save-restriction
  13450. (cond ((eq scope 'tree)
  13451. (org-back-to-heading t)
  13452. (org-narrow-to-subtree)
  13453. (setq scope nil))
  13454. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13455. (org-region-active-p))
  13456. ;; If needed, set start-level to a string like "2"
  13457. (when start-level
  13458. (save-excursion
  13459. (goto-char (region-beginning))
  13460. (unless (org-at-heading-p) (outline-next-heading))
  13461. (setq start-level (org-current-level))))
  13462. (narrow-to-region (region-beginning)
  13463. (save-excursion
  13464. (goto-char (region-end))
  13465. (unless (and (bolp) (org-at-heading-p))
  13466. (outline-next-heading))
  13467. (point)))
  13468. (setq scope nil)))
  13469. (if (not scope)
  13470. (progn
  13471. (org-agenda-prepare-buffers
  13472. (and buffer-file-name (list buffer-file-name)))
  13473. (setq res
  13474. (org-scan-tags
  13475. func matcher org--matcher-tags-todo-only start-level)))
  13476. ;; Get the right scope
  13477. (cond
  13478. ((and scope (listp scope) (symbolp (car scope)))
  13479. (setq scope (eval scope)))
  13480. ((eq scope 'agenda)
  13481. (setq scope (org-agenda-files t)))
  13482. ((eq scope 'agenda-with-archives)
  13483. (setq scope (org-agenda-files t))
  13484. (setq scope (org-add-archive-files scope)))
  13485. ((eq scope 'file)
  13486. (setq scope (and buffer-file-name (list buffer-file-name))))
  13487. ((eq scope 'file-with-archives)
  13488. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13489. (org-agenda-prepare-buffers scope)
  13490. (dolist (file scope)
  13491. (with-current-buffer (org-find-base-buffer-visiting file)
  13492. (org-with-wide-buffer
  13493. (goto-char (point-min))
  13494. (setq res
  13495. (append
  13496. res
  13497. (org-scan-tags
  13498. func matcher org--matcher-tags-todo-only)))))))))
  13499. res)))
  13500. ;;; Properties API
  13501. (defconst org-special-properties
  13502. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13503. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13504. "The special properties valid in Org mode.
  13505. These are properties that are not defined in the property drawer,
  13506. but in some other way.")
  13507. (defconst org-default-properties
  13508. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13509. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13510. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13511. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13512. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13513. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13514. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13515. "Some properties that are used by Org mode for various purposes.
  13516. Being in this list makes sure that they are offered for completion.")
  13517. (defun org--valid-property-p (property)
  13518. "Non nil when string PROPERTY is a valid property name."
  13519. (not
  13520. (or (equal property "")
  13521. (string-match-p "\\s-" property))))
  13522. (defun org--update-property-plist (key val props)
  13523. "Associate KEY to VAL in alist PROPS.
  13524. Modifications are made by side-effect. Return new alist."
  13525. (let* ((appending (string= (substring key -1) "+"))
  13526. (key (if appending (substring key 0 -1) key))
  13527. (old (assoc-string key props t)))
  13528. (if (not old) (cons (cons key val) props)
  13529. (setcdr old (if appending (concat (cdr old) " " val) val))
  13530. props)))
  13531. (defun org-get-property-block (&optional beg force)
  13532. "Return the (beg . end) range of the body of the property drawer.
  13533. BEG is the beginning of the current subtree, or of the part
  13534. before the first headline. If it is not given, it will be found.
  13535. If the drawer does not exist, create it if FORCE is non-nil, or
  13536. return nil."
  13537. (org-with-wide-buffer
  13538. (when beg (goto-char beg))
  13539. (unless (org-before-first-heading-p)
  13540. (let ((beg (cond (beg)
  13541. ((or (not (featurep 'org-inlinetask))
  13542. (org-inlinetask-in-task-p))
  13543. (org-back-to-heading t))
  13544. (t (org-with-limited-levels (org-back-to-heading t))))))
  13545. (forward-line)
  13546. (when (looking-at-p org-planning-line-re) (forward-line))
  13547. (cond ((looking-at org-property-drawer-re)
  13548. (forward-line)
  13549. (cons (point) (progn (goto-char (match-end 0))
  13550. (line-beginning-position))))
  13551. (force
  13552. (goto-char beg)
  13553. (org-insert-property-drawer)
  13554. (let ((pos (save-excursion (search-forward ":END:")
  13555. (line-beginning-position))))
  13556. (cons pos pos))))))))
  13557. (defun org-at-property-p ()
  13558. "Non-nil when point is inside a property drawer.
  13559. See `org-property-re' for match data, if applicable."
  13560. (save-excursion
  13561. (beginning-of-line)
  13562. (and (looking-at org-property-re)
  13563. (let ((property-drawer (save-match-data (org-get-property-block))))
  13564. (and property-drawer
  13565. (>= (point) (car property-drawer))
  13566. (< (point) (cdr property-drawer)))))))
  13567. (defun org-property-action ()
  13568. "Do an action on properties."
  13569. (interactive)
  13570. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13571. (let ((c (read-char-exclusive)))
  13572. (cl-case c
  13573. (?s (call-interactively #'org-set-property))
  13574. (?d (call-interactively #'org-delete-property))
  13575. (?D (call-interactively #'org-delete-property-globally))
  13576. (?c (call-interactively #'org-compute-property-at-point))
  13577. (otherwise (user-error "No such property action %c" c)))))
  13578. (defun org-inc-effort ()
  13579. "Increment the value of the effort property in the current entry."
  13580. (interactive)
  13581. (org-set-effort t))
  13582. (defvar org-clock-effort) ; Defined in org-clock.el.
  13583. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13584. (defun org-set-effort (&optional increment value)
  13585. "Set the effort property of the current entry.
  13586. If INCREMENT is non-nil, set the property to the next allowed
  13587. value. Otherwise, if optional argument VALUE is provided, use
  13588. it. Eventually, prompt for the new value if none of the previous
  13589. variables is set."
  13590. (interactive "P")
  13591. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13592. (current (org-entry-get nil org-effort-property))
  13593. (value
  13594. (cond
  13595. (increment
  13596. (unless allowed (user-error "Allowed effort values are not set"))
  13597. (or (cl-caadr (member (list current) allowed))
  13598. (user-error "Unknown value %S among allowed values" current)))
  13599. (value
  13600. (if (stringp value) value
  13601. (error "Invalid effort value: %S" value)))
  13602. (t
  13603. (let ((must-match
  13604. (and allowed
  13605. (not (get-text-property 0 'org-unrestricted
  13606. (caar allowed))))))
  13607. (completing-read "Effort: " allowed nil must-match))))))
  13608. (unless (equal current value)
  13609. (org-entry-put nil org-effort-property value))
  13610. (org-refresh-property '((effort . identity)
  13611. (effort-minutes . org-duration-to-minutes))
  13612. value)
  13613. (when (equal (org-get-heading t t t t)
  13614. (bound-and-true-p org-clock-current-task))
  13615. (setq org-clock-effort (org-get-at-bol 'effort))
  13616. (org-clock-update-mode-line))
  13617. (message "%s is now %s" org-effort-property value)))
  13618. (defun org-entry-properties (&optional pom which)
  13619. "Get all properties of the current entry.
  13620. When POM is a buffer position, get all properties from the entry
  13621. there instead.
  13622. This includes the TODO keyword, the tags, time strings for
  13623. deadline, scheduled, and clocking, and any additional properties
  13624. defined in the entry.
  13625. If WHICH is nil or `all', get all properties. If WHICH is
  13626. `special' or `standard', only get that subclass. If WHICH is
  13627. a string, only get that property.
  13628. Return value is an alist. Keys are properties, as upcased
  13629. strings."
  13630. (org-with-point-at pom
  13631. (when (and (derived-mode-p 'org-mode)
  13632. (ignore-errors (org-back-to-heading t)))
  13633. (catch 'exit
  13634. (let* ((beg (point))
  13635. (specific (and (stringp which) (upcase which)))
  13636. (which (cond ((not specific) which)
  13637. ((member specific org-special-properties) 'special)
  13638. (t 'standard)))
  13639. props)
  13640. ;; Get the special properties, like TODO and TAGS.
  13641. (when (memq which '(nil all special))
  13642. (when (or (not specific) (string= specific "CLOCKSUM"))
  13643. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13644. (when clocksum
  13645. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13646. props)))
  13647. (when specific (throw 'exit props)))
  13648. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13649. (let ((clocksumt (get-text-property (point)
  13650. :org-clock-minutes-today)))
  13651. (when clocksumt
  13652. (push (cons "CLOCKSUM_T"
  13653. (org-duration-from-minutes clocksumt))
  13654. props)))
  13655. (when specific (throw 'exit props)))
  13656. (when (or (not specific) (string= specific "ITEM"))
  13657. (let ((case-fold-search nil))
  13658. (when (looking-at org-complex-heading-regexp)
  13659. (push (cons "ITEM"
  13660. (let ((title (match-string-no-properties 4)))
  13661. (if (org-string-nw-p title)
  13662. (org-remove-tabs title)
  13663. "")))
  13664. props)))
  13665. (when specific (throw 'exit props)))
  13666. (when (or (not specific) (string= specific "TODO"))
  13667. (let ((case-fold-search nil))
  13668. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13669. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13670. (when specific (throw 'exit props)))
  13671. (when (or (not specific) (string= specific "PRIORITY"))
  13672. (push (cons "PRIORITY"
  13673. (if (looking-at org-priority-regexp)
  13674. (match-string-no-properties 2)
  13675. (char-to-string org-default-priority)))
  13676. props)
  13677. (when specific (throw 'exit props)))
  13678. (when (or (not specific) (string= specific "FILE"))
  13679. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13680. props)
  13681. (when specific (throw 'exit props)))
  13682. (when (or (not specific) (string= specific "TAGS"))
  13683. (let ((tags (org-get-tags nil t)))
  13684. (when tags
  13685. (push (cons "TAGS" (org-make-tag-string tags))
  13686. props)))
  13687. (when specific (throw 'exit props)))
  13688. (when (or (not specific) (string= specific "ALLTAGS"))
  13689. (let ((tags (org-get-tags)))
  13690. (when tags
  13691. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13692. props)))
  13693. (when specific (throw 'exit props)))
  13694. (when (or (not specific) (string= specific "BLOCKED"))
  13695. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13696. (when specific (throw 'exit props)))
  13697. (when (or (not specific)
  13698. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13699. (forward-line)
  13700. (when (looking-at-p org-planning-line-re)
  13701. (end-of-line)
  13702. (let ((bol (line-beginning-position))
  13703. ;; Backward compatibility: time keywords used to
  13704. ;; be configurable (before 8.3). Make sure we
  13705. ;; get the correct keyword.
  13706. (key-assoc `(("CLOSED" . ,org-closed-string)
  13707. ("DEADLINE" . ,org-deadline-string)
  13708. ("SCHEDULED" . ,org-scheduled-string))))
  13709. (dolist (pair (if specific (list (assoc specific key-assoc))
  13710. key-assoc))
  13711. (save-excursion
  13712. (when (search-backward (cdr pair) bol t)
  13713. (goto-char (match-end 0))
  13714. (skip-chars-forward " \t")
  13715. (and (looking-at org-ts-regexp-both)
  13716. (push (cons (car pair)
  13717. (match-string-no-properties 0))
  13718. props)))))))
  13719. (when specific (throw 'exit props)))
  13720. (when (or (not specific)
  13721. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13722. (let ((find-ts
  13723. (lambda (end ts)
  13724. ;; Fix next time-stamp before END. TS is the
  13725. ;; list of time-stamps found so far.
  13726. (let ((ts ts)
  13727. (regexp (cond
  13728. ((string= specific "TIMESTAMP")
  13729. org-ts-regexp)
  13730. ((string= specific "TIMESTAMP_IA")
  13731. org-ts-regexp-inactive)
  13732. ((assoc "TIMESTAMP_IA" ts)
  13733. org-ts-regexp)
  13734. ((assoc "TIMESTAMP" ts)
  13735. org-ts-regexp-inactive)
  13736. (t org-ts-regexp-both))))
  13737. (catch 'next
  13738. (while (re-search-forward regexp end t)
  13739. (backward-char)
  13740. (let ((object (org-element-context)))
  13741. ;; Accept to match timestamps in node
  13742. ;; properties, too.
  13743. (when (memq (org-element-type object)
  13744. '(node-property timestamp))
  13745. (let ((type
  13746. (org-element-property :type object)))
  13747. (cond
  13748. ((and (memq type '(active active-range))
  13749. (not (equal specific "TIMESTAMP_IA")))
  13750. (unless (assoc "TIMESTAMP" ts)
  13751. (push (cons "TIMESTAMP"
  13752. (org-element-property
  13753. :raw-value object))
  13754. ts)
  13755. (when specific (throw 'exit ts))))
  13756. ((and (memq type '(inactive inactive-range))
  13757. (not (string= specific "TIMESTAMP")))
  13758. (unless (assoc "TIMESTAMP_IA" ts)
  13759. (push (cons "TIMESTAMP_IA"
  13760. (org-element-property
  13761. :raw-value object))
  13762. ts)
  13763. (when specific (throw 'exit ts))))))
  13764. ;; Both timestamp types are found,
  13765. ;; move to next part.
  13766. (when (= (length ts) 2) (throw 'next ts)))))
  13767. ts)))))
  13768. (goto-char beg)
  13769. ;; First look for timestamps within headline.
  13770. (let ((ts (funcall find-ts (line-end-position) nil)))
  13771. (if (= (length ts) 2) (setq props (nconc ts props))
  13772. ;; Then find timestamps in the section, skipping
  13773. ;; planning line.
  13774. (let ((end (save-excursion (outline-next-heading))))
  13775. (forward-line)
  13776. (when (looking-at-p org-planning-line-re) (forward-line))
  13777. (setq props (nconc (funcall find-ts end ts) props))))))))
  13778. ;; Get the standard properties, like :PROP:.
  13779. (when (memq which '(nil all standard))
  13780. ;; If we are looking after a specific property, delegate
  13781. ;; to `org-entry-get', which is faster. However, make an
  13782. ;; exception for "CATEGORY", since it can be also set
  13783. ;; through keywords (i.e. #+CATEGORY).
  13784. (if (and specific (not (equal specific "CATEGORY")))
  13785. (let ((value (org-entry-get beg specific nil t)))
  13786. (throw 'exit (and value (list (cons specific value)))))
  13787. (let ((range (org-get-property-block beg)))
  13788. (when range
  13789. (let ((end (cdr range)) seen-base)
  13790. (goto-char (car range))
  13791. ;; Unlike to `org--update-property-plist', we
  13792. ;; handle the case where base values is found
  13793. ;; after its extension. We also forbid standard
  13794. ;; properties to be named as special properties.
  13795. (while (re-search-forward org-property-re end t)
  13796. (let* ((key (upcase (match-string-no-properties 2)))
  13797. (extendp (string-match-p "\\+\\'" key))
  13798. (key-base (if extendp (substring key 0 -1) key))
  13799. (value (match-string-no-properties 3)))
  13800. (cond
  13801. ((member-ignore-case key-base org-special-properties))
  13802. (extendp
  13803. (setq props
  13804. (org--update-property-plist key value props)))
  13805. ((member key seen-base))
  13806. (t (push key seen-base)
  13807. (let ((p (assoc-string key props t)))
  13808. (if p (setcdr p (concat value " " (cdr p)))
  13809. (push (cons key value) props))))))))))))
  13810. (unless (assoc "CATEGORY" props)
  13811. (push (cons "CATEGORY" (org-get-category beg)) props)
  13812. (when (string= specific "CATEGORY") (throw 'exit props)))
  13813. ;; Return value.
  13814. props)))))
  13815. (defun org--property-local-values (property literal-nil)
  13816. "Return value for PROPERTY in current entry.
  13817. Value is a list whose car is the base value for PROPERTY and cdr
  13818. a list of accumulated values. Return nil if neither is found in
  13819. the entry. Also return nil when PROPERTY is set to \"nil\",
  13820. unless LITERAL-NIL is non-nil."
  13821. (let ((range (org-get-property-block)))
  13822. (when range
  13823. (goto-char (car range))
  13824. (let* ((case-fold-search t)
  13825. (end (cdr range))
  13826. (value
  13827. ;; Base value.
  13828. (save-excursion
  13829. (let ((v (and (re-search-forward
  13830. (org-re-property property nil t) end t)
  13831. (match-string-no-properties 3))))
  13832. (list (if literal-nil v (org-not-nil v)))))))
  13833. ;; Find additional values.
  13834. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13835. (while (re-search-forward property+ end t)
  13836. (push (match-string-no-properties 3) value)))
  13837. ;; Return final values.
  13838. (and (not (equal value '(nil))) (nreverse value))))))
  13839. (defun org--property-global-value (property literal-nil)
  13840. "Return value for PROPERTY in current buffer.
  13841. Return value is a string. Return nil if property is not set
  13842. globally. Also return nil when PROPERTY is set to \"nil\",
  13843. unless LITERAL-NIL is non-nil."
  13844. (let ((global
  13845. (cdr (or (assoc-string property org-file-properties t)
  13846. (assoc-string property org-global-properties t)
  13847. (assoc-string property org-global-properties-fixed t)))))
  13848. (if literal-nil global (org-not-nil global))))
  13849. (defun org-entry-get (pom property &optional inherit literal-nil)
  13850. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13851. If INHERIT is non-nil and the entry does not have the property,
  13852. then also check higher levels of the hierarchy. If INHERIT is
  13853. the symbol `selective', use inheritance only if the setting in
  13854. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13855. If the property is present but empty, the return value is the
  13856. empty string. If the property is not present at all, nil is
  13857. returned. In any other case, return the value as a string.
  13858. Search is case-insensitive.
  13859. If LITERAL-NIL is set, return the string value \"nil\" as
  13860. a string, do not interpret it as the list atom nil. This is used
  13861. for inheritance when a \"nil\" value can supersede a non-nil
  13862. value higher up the hierarchy."
  13863. (org-with-point-at pom
  13864. (cond
  13865. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13866. ;; We need a special property. Use `org-entry-properties' to
  13867. ;; retrieve it, but specify the wanted property.
  13868. (cdr (assoc-string property (org-entry-properties nil property))))
  13869. ((and inherit
  13870. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13871. (org-entry-get-with-inheritance property literal-nil))
  13872. (t
  13873. (let* ((local (org--property-local-values property literal-nil))
  13874. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13875. (if literal-nil value (org-not-nil value)))))))
  13876. (defun org-property-or-variable-value (var &optional inherit)
  13877. "Check if there is a property fixing the value of VAR.
  13878. If yes, return this value. If not, return the current value of the variable."
  13879. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13880. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13881. (read prop)
  13882. (symbol-value var))))
  13883. (defun org-entry-delete (pom property)
  13884. "Delete PROPERTY from entry at point-or-marker POM.
  13885. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13886. non-nil when a property was removed."
  13887. (org-with-point-at pom
  13888. (pcase (org-get-property-block)
  13889. (`(,begin . ,origin)
  13890. (let* ((end (copy-marker origin))
  13891. (re (org-re-property
  13892. (concat (regexp-quote property) "\\+?") t t)))
  13893. (goto-char begin)
  13894. (while (re-search-forward re end t)
  13895. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13896. ;; If drawer is empty, remove it altogether.
  13897. (when (= begin end)
  13898. (delete-region (line-beginning-position 0)
  13899. (line-beginning-position 2)))
  13900. ;; Return non-nil if some property was removed.
  13901. (prog1 (/= end origin) (set-marker end nil))))
  13902. (_ nil))))
  13903. ;; Multi-values properties are properties that contain multiple values
  13904. ;; These values are assumed to be single words, separated by whitespace.
  13905. (defun org-entry-add-to-multivalued-property (pom property value)
  13906. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13907. (let* ((old (org-entry-get pom property))
  13908. (values (and old (split-string old))))
  13909. (setq value (org-entry-protect-space value))
  13910. (unless (member value values)
  13911. (setq values (append values (list value)))
  13912. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13913. (defun org-entry-remove-from-multivalued-property (pom property value)
  13914. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13915. (let* ((old (org-entry-get pom property))
  13916. (values (and old (split-string old))))
  13917. (setq value (org-entry-protect-space value))
  13918. (when (member value values)
  13919. (setq values (delete value values))
  13920. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13921. (defun org-entry-member-in-multivalued-property (pom property value)
  13922. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13923. (let* ((old (org-entry-get pom property))
  13924. (values (and old (split-string old))))
  13925. (setq value (org-entry-protect-space value))
  13926. (member value values)))
  13927. (defun org-entry-get-multivalued-property (pom property)
  13928. "Return a list of values in a multivalued property."
  13929. (let* ((value (org-entry-get pom property))
  13930. (values (and value (split-string value))))
  13931. (mapcar #'org-entry-restore-space values)))
  13932. (defun org-entry-put-multivalued-property (pom property &rest values)
  13933. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13934. VALUES should be a list of strings. Spaces will be protected."
  13935. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13936. (let* ((value (org-entry-get pom property))
  13937. (values (and value (split-string value))))
  13938. (mapcar #'org-entry-restore-space values)))
  13939. (defun org-entry-protect-space (s)
  13940. "Protect spaces and newline in string S."
  13941. (while (string-match " " s)
  13942. (setq s (replace-match "%20" t t s)))
  13943. (while (string-match "\n" s)
  13944. (setq s (replace-match "%0A" t t s)))
  13945. s)
  13946. (defun org-entry-restore-space (s)
  13947. "Restore spaces and newline in string S."
  13948. (while (string-match "%20" s)
  13949. (setq s (replace-match " " t t s)))
  13950. (while (string-match "%0A" s)
  13951. (setq s (replace-match "\n" t t s)))
  13952. s)
  13953. (defvar org-entry-property-inherited-from (make-marker)
  13954. "Marker pointing to the entry from where a property was inherited.
  13955. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13956. location of the entry where the inheritance search matched. If there was
  13957. no match, the marker will point nowhere.
  13958. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13959. is set.")
  13960. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13961. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13962. The search will stop at the first ancestor which has the property defined.
  13963. If the value found is \"nil\", return nil to show that the property
  13964. should be considered as undefined (this is the meaning of nil here).
  13965. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13966. (move-marker org-entry-property-inherited-from nil)
  13967. (org-with-wide-buffer
  13968. (let (value)
  13969. (catch 'exit
  13970. (while t
  13971. (let ((v (org--property-local-values property literal-nil)))
  13972. (when v
  13973. (setq value
  13974. (concat (mapconcat #'identity (delq nil v) " ")
  13975. (and value " ")
  13976. value)))
  13977. (cond
  13978. ((car v)
  13979. (org-back-to-heading t)
  13980. (move-marker org-entry-property-inherited-from (point))
  13981. (throw 'exit nil))
  13982. ((org-up-heading-safe))
  13983. (t
  13984. (let ((global (org--property-global-value property literal-nil)))
  13985. (cond ((not global))
  13986. (value (setq value (concat global " " value)))
  13987. (t (setq value global))))
  13988. (throw 'exit nil))))))
  13989. (if literal-nil value (org-not-nil value)))))
  13990. (defvar org-property-changed-functions nil
  13991. "Hook called when the value of a property has changed.
  13992. Each hook function should accept two arguments, the name of the property
  13993. and the new value.")
  13994. (defun org-entry-put (pom property value)
  13995. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13996. If the value is nil, it is converted to the empty string. If it
  13997. is not a string, an error is raised. Also raise an error on
  13998. invalid property names.
  13999. PROPERTY can be any regular property (see
  14000. `org-special-properties'). It can also be \"TODO\",
  14001. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14002. For the last two properties, VALUE may have any of the special
  14003. values \"earlier\" and \"later\". The function then increases or
  14004. decreases scheduled or deadline date by one day."
  14005. (cond ((null value) (setq value ""))
  14006. ((not (stringp value)) (error "Properties values should be strings"))
  14007. ((not (org--valid-property-p property))
  14008. (user-error "Invalid property name: \"%s\"" property)))
  14009. (org-with-point-at pom
  14010. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14011. (org-back-to-heading t)
  14012. (org-with-limited-levels (org-back-to-heading t)))
  14013. (let ((beg (point)))
  14014. (cond
  14015. ((equal property "TODO")
  14016. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14017. ((not (member value org-todo-keywords-1))
  14018. (user-error "\"%s\" is not a valid TODO state" value)))
  14019. (org-todo value)
  14020. (org-align-tags))
  14021. ((equal property "PRIORITY")
  14022. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14023. (org-align-tags))
  14024. ((equal property "SCHEDULED")
  14025. (forward-line)
  14026. (if (and (looking-at-p org-planning-line-re)
  14027. (re-search-forward
  14028. org-scheduled-time-regexp (line-end-position) t))
  14029. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14030. ((string= value "later") (org-timestamp-change 1 'day))
  14031. ((string= value "") (org-schedule '(4)))
  14032. (t (org-schedule nil value)))
  14033. (if (member value '("earlier" "later" ""))
  14034. (call-interactively #'org-schedule)
  14035. (org-schedule nil value))))
  14036. ((equal property "DEADLINE")
  14037. (forward-line)
  14038. (if (and (looking-at-p org-planning-line-re)
  14039. (re-search-forward
  14040. org-deadline-time-regexp (line-end-position) t))
  14041. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14042. ((string= value "later") (org-timestamp-change 1 'day))
  14043. ((string= value "") (org-deadline '(4)))
  14044. (t (org-deadline nil value)))
  14045. (if (member value '("earlier" "later" ""))
  14046. (call-interactively #'org-deadline)
  14047. (org-deadline nil value))))
  14048. ((member property org-special-properties)
  14049. (error "The %s property cannot be set with `org-entry-put'" property))
  14050. (t
  14051. (let* ((range (org-get-property-block beg 'force))
  14052. (end (cdr range))
  14053. (case-fold-search t))
  14054. (goto-char (car range))
  14055. (if (re-search-forward (org-re-property property nil t) end t)
  14056. (progn (delete-region (match-beginning 0) (match-end 0))
  14057. (goto-char (match-beginning 0)))
  14058. (goto-char end)
  14059. (insert "\n")
  14060. (backward-char))
  14061. (insert ":" property ":")
  14062. (when value (insert " " value))
  14063. (org-indent-line)))))
  14064. (run-hook-with-args 'org-property-changed-functions property value)))
  14065. (defun org-buffer-property-keys (&optional specials defaults columns)
  14066. "Get all property keys in the current buffer.
  14067. When SPECIALS is non-nil, also list the special properties that
  14068. reflect things like tags and TODO state.
  14069. When DEFAULTS is non-nil, also include properties that has
  14070. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14071. DESCRIPTION, LOCATION, and LOGGING and others.
  14072. When COLUMNS in non-nil, also include property names given in
  14073. COLUMN formats in the current buffer."
  14074. (let ((case-fold-search t)
  14075. (props (append
  14076. (and specials org-special-properties)
  14077. (and defaults (cons org-effort-property org-default-properties))
  14078. nil)))
  14079. (org-with-wide-buffer
  14080. (goto-char (point-min))
  14081. (while (re-search-forward org-property-start-re nil t)
  14082. (catch :skip
  14083. (let ((range (org-get-property-block)))
  14084. (unless range (throw :skip nil))
  14085. (goto-char (car range))
  14086. (let ((begin (car range))
  14087. (end (cdr range)))
  14088. ;; Make sure that found property block is not located
  14089. ;; before current point, as it would generate an infloop.
  14090. ;; It can happen, for example, in the following
  14091. ;; situation:
  14092. ;;
  14093. ;; * Headline
  14094. ;; :PROPERTIES:
  14095. ;; ...
  14096. ;; :END:
  14097. ;; *************** Inlinetask
  14098. ;; #+BEGIN_EXAMPLE
  14099. ;; :PROPERTIES:
  14100. ;; #+END_EXAMPLE
  14101. ;;
  14102. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14103. (while (< (point) end)
  14104. (let ((p (progn (looking-at org-property-re)
  14105. (match-string-no-properties 2))))
  14106. ;; Only add true property name, not extension symbol.
  14107. (push (if (not (string-match-p "\\+\\'" p)) p
  14108. (substring p 0 -1))
  14109. props))
  14110. (forward-line))))
  14111. (outline-next-heading)))
  14112. (when columns
  14113. (goto-char (point-min))
  14114. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14115. (let ((element (org-element-at-point)))
  14116. (when (memq (org-element-type element) '(keyword node-property))
  14117. (let ((value (org-element-property :value element))
  14118. (start 0))
  14119. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14120. \\(?:{[^}]+}\\)?"
  14121. value start)
  14122. (setq start (match-end 0))
  14123. (let ((p (match-string-no-properties 1 value)))
  14124. (unless (member-ignore-case p org-special-properties)
  14125. (push p props))))))))))
  14126. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14127. (defun org-property-values (key)
  14128. "List all non-nil values of property KEY in current buffer."
  14129. (org-with-wide-buffer
  14130. (goto-char (point-min))
  14131. (let ((case-fold-search t)
  14132. (re (org-re-property key))
  14133. values)
  14134. (while (re-search-forward re nil t)
  14135. (push (org-entry-get (point) key) values))
  14136. (delete-dups values))))
  14137. (defun org-insert-property-drawer ()
  14138. "Insert a property drawer into the current entry."
  14139. (org-with-wide-buffer
  14140. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14141. (org-back-to-heading t)
  14142. (org-with-limited-levels (org-back-to-heading t)))
  14143. (forward-line)
  14144. (when (looking-at-p org-planning-line-re) (forward-line))
  14145. (unless (looking-at-p org-property-drawer-re)
  14146. ;; Make sure we start editing a line from current entry, not from
  14147. ;; next one. It prevents extending text properties or overlays
  14148. ;; belonging to the latter.
  14149. (when (bolp) (backward-char))
  14150. (let ((begin (1+ (point)))
  14151. (inhibit-read-only t))
  14152. (insert "\n:PROPERTIES:\n:END:")
  14153. (when (eobp) (insert "\n"))
  14154. (org-indent-region begin (point))))))
  14155. (defun org-insert-drawer (&optional arg drawer)
  14156. "Insert a drawer at point.
  14157. When optional argument ARG is non-nil, insert a property drawer.
  14158. Optional argument DRAWER, when non-nil, is a string representing
  14159. drawer's name. Otherwise, the user is prompted for a name.
  14160. If a region is active, insert the drawer around that region
  14161. instead.
  14162. Point is left between drawer's boundaries."
  14163. (interactive "P")
  14164. (let* ((drawer (if arg "PROPERTIES"
  14165. (or drawer (read-from-minibuffer "Drawer: ")))))
  14166. (cond
  14167. ;; With C-u, fall back on `org-insert-property-drawer'
  14168. (arg (org-insert-property-drawer))
  14169. ;; Check validity of suggested drawer's name.
  14170. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14171. (user-error "Invalid drawer name"))
  14172. ;; With an active region, insert a drawer at point.
  14173. ((not (org-region-active-p))
  14174. (progn
  14175. (unless (bolp) (insert "\n"))
  14176. (insert (format ":%s:\n\n:END:\n" drawer))
  14177. (forward-line -2)))
  14178. ;; Otherwise, insert the drawer at point
  14179. (t
  14180. (let ((rbeg (region-beginning))
  14181. (rend (copy-marker (region-end))))
  14182. (unwind-protect
  14183. (progn
  14184. (goto-char rbeg)
  14185. (beginning-of-line)
  14186. (when (save-excursion
  14187. (re-search-forward org-outline-regexp-bol rend t))
  14188. (user-error "Drawers cannot contain headlines"))
  14189. ;; Position point at the beginning of the first
  14190. ;; non-blank line in region. Insert drawer's opening
  14191. ;; there, then indent it.
  14192. (org-skip-whitespace)
  14193. (beginning-of-line)
  14194. (insert ":" drawer ":\n")
  14195. (forward-line -1)
  14196. (indent-for-tab-command)
  14197. ;; Move point to the beginning of the first blank line
  14198. ;; after the last non-blank line in region. Insert
  14199. ;; drawer's closing, then indent it.
  14200. (goto-char rend)
  14201. (skip-chars-backward " \r\t\n")
  14202. (insert "\n:END:")
  14203. (deactivate-mark t)
  14204. (indent-for-tab-command)
  14205. (unless (eolp) (insert "\n")))
  14206. ;; Clear marker, whatever the outcome of insertion is.
  14207. (set-marker rend nil)))))))
  14208. (defvar org-property-set-functions-alist nil
  14209. "Property set function alist.
  14210. Each entry should have the following format:
  14211. (PROPERTY . READ-FUNCTION)
  14212. The read function will be called with the same argument as
  14213. `org-completing-read'.")
  14214. (defun org-set-property-function (property)
  14215. "Get the function that should be used to set PROPERTY.
  14216. This is computed according to `org-property-set-functions-alist'."
  14217. (or (cdr (assoc property org-property-set-functions-alist))
  14218. 'org-completing-read))
  14219. (defun org-read-property-value (property &optional pom)
  14220. "Read value for PROPERTY, as a string.
  14221. When optional argument POM is non-nil, completion uses additional
  14222. information, i.e., allowed or existing values at point or marker
  14223. POM."
  14224. (let* ((completion-ignore-case t)
  14225. (allowed
  14226. (or (org-property-get-allowed-values nil property 'table)
  14227. (and pom (org-property-get-allowed-values pom property 'table))))
  14228. (current (org-entry-get nil property))
  14229. (prompt (format "%s value%s: "
  14230. property
  14231. (if (org-string-nw-p current)
  14232. (format " [%s]" current)
  14233. "")))
  14234. (set-function (org-set-property-function property)))
  14235. (org-trim
  14236. (if allowed
  14237. (funcall set-function
  14238. prompt allowed nil
  14239. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  14240. (let ((all (mapcar #'list
  14241. (append (org-property-values property)
  14242. (and pom
  14243. (org-with-point-at pom
  14244. (org-property-values property)))))))
  14245. (funcall set-function prompt all nil nil "" nil current))))))
  14246. (defvar org-last-set-property nil)
  14247. (defvar org-last-set-property-value nil)
  14248. (defun org-read-property-name ()
  14249. "Read a property name."
  14250. (let ((completion-ignore-case t)
  14251. (default-prop (or (and (org-at-property-p)
  14252. (match-string-no-properties 2))
  14253. org-last-set-property)))
  14254. (org-completing-read
  14255. (concat "Property"
  14256. (if default-prop (concat " [" default-prop "]") "")
  14257. ": ")
  14258. (mapcar #'list (org-buffer-property-keys nil t t))
  14259. nil nil nil nil default-prop)))
  14260. (defun org-set-property-and-value (use-last)
  14261. "Allow to set [PROPERTY]: [value] direction from prompt.
  14262. When use-default, don't even ask, just use the last
  14263. \"[PROPERTY]: [value]\" string from the history."
  14264. (interactive "P")
  14265. (let* ((completion-ignore-case t)
  14266. (pv (or (and use-last org-last-set-property-value)
  14267. (org-completing-read
  14268. "Enter a \"[Property]: [value]\" pair: "
  14269. nil nil nil nil nil
  14270. org-last-set-property-value)))
  14271. prop val)
  14272. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14273. (setq prop (match-string 1 pv)
  14274. val (match-string 2 pv))
  14275. (org-set-property prop val))))
  14276. (defun org-set-property (property value)
  14277. "In the current entry, set PROPERTY to VALUE.
  14278. When called interactively, this will prompt for a property name, offering
  14279. completion on existing and default properties. And then it will prompt
  14280. for a value, offering completion either on allowed values (via an inherited
  14281. xxx_ALL property) or on existing values in other instances of this property
  14282. in the current file.
  14283. Throw an error when trying to set a property with an invalid name."
  14284. (interactive (list nil nil))
  14285. (let ((property (or property (org-read-property-name))))
  14286. ;; `org-entry-put' also makes the following check, but this one
  14287. ;; avoids polluting `org-last-set-property' and
  14288. ;; `org-last-set-property-value' needlessly.
  14289. (unless (org--valid-property-p property)
  14290. (user-error "Invalid property name: \"%s\"" property))
  14291. (let ((value (or value (org-read-property-value property)))
  14292. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14293. (setq org-last-set-property property)
  14294. (setq org-last-set-property-value (concat property ": " value))
  14295. ;; Possibly postprocess the inserted value:
  14296. (when fn (setq value (funcall fn value)))
  14297. (unless (equal (org-entry-get nil property) value)
  14298. (org-entry-put nil property value)))))
  14299. (defun org-find-property (property &optional value)
  14300. "Find first entry in buffer that sets PROPERTY.
  14301. When optional argument VALUE is non-nil, only consider an entry
  14302. if it contains PROPERTY set to this value. If PROPERTY should be
  14303. explicitly set to nil, use string \"nil\" for VALUE.
  14304. Return position where the entry begins, or nil if there is no
  14305. such entry. If narrowing is in effect, only search the visible
  14306. part of the buffer."
  14307. (save-excursion
  14308. (goto-char (point-min))
  14309. (let ((case-fold-search t)
  14310. (re (org-re-property property nil (not value) value)))
  14311. (catch 'exit
  14312. (while (re-search-forward re nil t)
  14313. (when (if value (org-at-property-p)
  14314. (org-entry-get (point) property nil t))
  14315. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14316. (defun org-delete-property (property)
  14317. "In the current entry, delete PROPERTY."
  14318. (interactive
  14319. (let* ((completion-ignore-case t)
  14320. (cat (org-entry-get (point) "CATEGORY"))
  14321. (props0 (org-entry-properties nil 'standard))
  14322. (props (if cat props0
  14323. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14324. (prop (if (< 1 (length props))
  14325. (completing-read "Property: " props nil t)
  14326. (caar props))))
  14327. (list prop)))
  14328. (if (not property)
  14329. (message "No property to delete in this entry")
  14330. (org-entry-delete nil property)
  14331. (message "Property \"%s\" deleted" property)))
  14332. (defun org-delete-property-globally (property)
  14333. "Remove PROPERTY globally, from all entries.
  14334. This function ignores narrowing, if any."
  14335. (interactive
  14336. (let* ((completion-ignore-case t)
  14337. (prop (completing-read
  14338. "Globally remove property: "
  14339. (mapcar #'list (org-buffer-property-keys)))))
  14340. (list prop)))
  14341. (org-with-wide-buffer
  14342. (goto-char (point-min))
  14343. (let ((count 0)
  14344. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14345. (while (re-search-forward re nil t)
  14346. (when (org-entry-delete (point) property) (cl-incf count)))
  14347. (message "Property \"%s\" removed from %d entries" property count))))
  14348. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14349. (defun org-compute-property-at-point ()
  14350. "Compute the property at point.
  14351. This looks for an enclosing column format, extracts the operator and
  14352. then applies it to the property in the column format's scope."
  14353. (interactive)
  14354. (unless (org-at-property-p)
  14355. (user-error "Not at a property"))
  14356. (let ((prop (match-string-no-properties 2)))
  14357. (org-columns-get-format-and-top-level)
  14358. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14359. (user-error "No operator defined for property %s" prop))
  14360. (org-columns-compute prop)))
  14361. (defvar org-property-allowed-value-functions nil
  14362. "Hook for functions supplying allowed values for a specific property.
  14363. The functions must take a single argument, the name of the property, and
  14364. return a flat list of allowed values. If \":ETC\" is one of
  14365. the values, this means that these values are intended as defaults for
  14366. completion, but that other values should be allowed too.
  14367. The functions must return nil if they are not responsible for this
  14368. property.")
  14369. (defun org-property-get-allowed-values (pom property &optional table)
  14370. "Get allowed values for the property PROPERTY.
  14371. When TABLE is non-nil, return an alist that can directly be used for
  14372. completion."
  14373. (let (vals)
  14374. (cond
  14375. ((equal property "TODO")
  14376. (setq vals (org-with-point-at pom
  14377. (append org-todo-keywords-1 '("")))))
  14378. ((equal property "PRIORITY")
  14379. (let ((n org-lowest-priority))
  14380. (while (>= n org-highest-priority)
  14381. (push (char-to-string n) vals)
  14382. (setq n (1- n)))))
  14383. ((equal property "CATEGORY"))
  14384. ((member property org-special-properties))
  14385. ((setq vals (run-hook-with-args-until-success
  14386. 'org-property-allowed-value-functions property)))
  14387. (t
  14388. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14389. (when (and vals (string-match "\\S-" vals))
  14390. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14391. (setq vals (mapcar (lambda (x)
  14392. (cond ((stringp x) x)
  14393. ((numberp x) (number-to-string x))
  14394. ((symbolp x) (symbol-name x))
  14395. (t "???")))
  14396. vals)))))
  14397. (when (member ":ETC" vals)
  14398. (setq vals (remove ":ETC" vals))
  14399. (org-add-props (car vals) '(org-unrestricted t)))
  14400. (if table (mapcar 'list vals) vals)))
  14401. (defun org-property-previous-allowed-value (&optional _previous)
  14402. "Switch to the next allowed value for this property."
  14403. (interactive)
  14404. (org-property-next-allowed-value t))
  14405. (defun org-property-next-allowed-value (&optional previous)
  14406. "Switch to the next allowed value for this property."
  14407. (interactive)
  14408. (unless (org-at-property-p)
  14409. (user-error "Not at a property"))
  14410. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14411. (key (match-string 2))
  14412. (value (match-string 3))
  14413. (allowed (or (org-property-get-allowed-values (point) key)
  14414. (and (member value '("[ ]" "[-]" "[X]"))
  14415. '("[ ]" "[X]"))))
  14416. (heading (save-match-data (nth 4 (org-heading-components))))
  14417. nval)
  14418. (unless allowed
  14419. (user-error "Allowed values for this property have not been defined"))
  14420. (when previous (setq allowed (reverse allowed)))
  14421. (when (member value allowed)
  14422. (setq nval (car (cdr (member value allowed)))))
  14423. (setq nval (or nval (car allowed)))
  14424. (when (equal nval value)
  14425. (user-error "Only one allowed value for this property"))
  14426. (org-at-property-p)
  14427. (replace-match (concat " :" key ": " nval) t t)
  14428. (org-indent-line)
  14429. (beginning-of-line 1)
  14430. (skip-chars-forward " \t")
  14431. (when (equal prop org-effort-property)
  14432. (org-refresh-property
  14433. '((effort . identity)
  14434. (effort-minutes . org-duration-to-minutes))
  14435. nval)
  14436. (when (string= org-clock-current-task heading)
  14437. (setq org-clock-effort nval)
  14438. (org-clock-update-mode-line)))
  14439. (run-hook-with-args 'org-property-changed-functions key nval)))
  14440. (defun org-find-olp (path &optional this-buffer)
  14441. "Return a marker pointing to the entry at outline path OLP.
  14442. If anything goes wrong, throw an error.
  14443. You can wrap this call to catch the error like this:
  14444. (condition-case msg
  14445. (org-mobile-locate-entry (match-string 4))
  14446. (error (nth 1 msg)))
  14447. The return value will then be either a string with the error message,
  14448. or a marker if everything is OK.
  14449. If THIS-BUFFER is set, the outline path does not contain a file,
  14450. only headings."
  14451. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14452. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14453. (level 1)
  14454. (lmin 1)
  14455. (lmax 1)
  14456. end found flevel)
  14457. (unless buffer (error "File not found :%s" file))
  14458. (with-current-buffer buffer
  14459. (unless (derived-mode-p 'org-mode)
  14460. (error "Buffer %s needs to be in Org mode" buffer))
  14461. (org-with-wide-buffer
  14462. (goto-char (point-min))
  14463. (dolist (heading path)
  14464. (let ((re (format org-complex-heading-regexp-format
  14465. (regexp-quote heading)))
  14466. (cnt 0))
  14467. (while (re-search-forward re end t)
  14468. (setq level (- (match-end 1) (match-beginning 1)))
  14469. (when (and (>= level lmin) (<= level lmax))
  14470. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14471. (when (= cnt 0)
  14472. (error "Heading not found on level %d: %s" lmax heading))
  14473. (when (> cnt 1)
  14474. (error "Heading not unique on level %d: %s" lmax heading))
  14475. (goto-char found)
  14476. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14477. (setq end (save-excursion (org-end-of-subtree t t)))))
  14478. (when (org-at-heading-p)
  14479. (point-marker))))))
  14480. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14481. "Find node HEADING in BUFFER.
  14482. Return a marker to the heading if it was found, or nil if not.
  14483. If POS-ONLY is set, return just the position instead of a marker.
  14484. The heading text must match exact, but it may have a TODO keyword,
  14485. a priority cookie and tags in the standard locations."
  14486. (with-current-buffer (or buffer (current-buffer))
  14487. (org-with-wide-buffer
  14488. (goto-char (point-min))
  14489. (let (case-fold-search)
  14490. (when (re-search-forward
  14491. (format org-complex-heading-regexp-format
  14492. (regexp-quote heading)) nil t)
  14493. (if pos-only
  14494. (match-beginning 0)
  14495. (move-marker (make-marker) (match-beginning 0))))))))
  14496. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14497. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14498. When the target headline is found, return a marker to this location."
  14499. (let ((files (directory-files (or dir default-directory)
  14500. t "\\`[^.#].*\\.org\\'"))
  14501. visiting m buffer)
  14502. (catch 'found
  14503. (dolist (file files)
  14504. (message "trying %s" file)
  14505. (setq visiting (org-find-base-buffer-visiting file))
  14506. (setq buffer (or visiting (find-file-noselect file)))
  14507. (setq m (org-find-exact-headline-in-buffer
  14508. heading buffer))
  14509. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14510. (and m (throw 'found m))))))
  14511. (defun org-find-entry-with-id (ident)
  14512. "Locate the entry that contains the ID property with exact value IDENT.
  14513. IDENT can be a string, a symbol or a number, this function will search for
  14514. the string representation of it.
  14515. Return the position where this entry starts, or nil if there is no such entry."
  14516. (interactive "sID: ")
  14517. (let ((id (cond
  14518. ((stringp ident) ident)
  14519. ((symbolp ident) (symbol-name ident))
  14520. ((numberp ident) (number-to-string ident))
  14521. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14522. (org-with-wide-buffer (org-find-property "ID" id))))
  14523. ;;;; Timestamps
  14524. (defvar org-last-changed-timestamp nil)
  14525. (defvar org-last-inserted-timestamp nil
  14526. "The last time stamp inserted with `org-insert-time-stamp'.")
  14527. (defun org-time-stamp (arg &optional inactive)
  14528. "Prompt for a date/time and insert a time stamp.
  14529. If the user specifies a time like HH:MM or if this command is
  14530. called with at least one prefix argument, the time stamp contains
  14531. the date and the time. Otherwise, only the date is included.
  14532. All parts of a date not specified by the user are filled in from
  14533. the timestamp at point, if any, or the current date/time
  14534. otherwise.
  14535. If there is already a timestamp at the cursor, it is replaced.
  14536. With two universal prefix arguments, insert an active timestamp
  14537. with the current time without prompting the user.
  14538. When called from lisp, the timestamp is inactive if INACTIVE is
  14539. non-nil."
  14540. (interactive "P")
  14541. (let* ((ts (cond
  14542. ((org-at-date-range-p t)
  14543. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14544. ((org-at-timestamp-p 'lax) (match-string 0))))
  14545. ;; Default time is either the timestamp at point or today.
  14546. ;; When entering a range, only the range start is considered.
  14547. (default-time (if (not ts) (current-time)
  14548. (apply #'encode-time (org-parse-time-string ts))))
  14549. (default-input (and ts (org-get-compact-tod ts)))
  14550. (repeater (and ts
  14551. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14552. (match-string 0 ts)))
  14553. org-time-was-given
  14554. org-end-time-was-given
  14555. (time
  14556. (and (if (equal arg '(16)) (current-time)
  14557. ;; Preserve `this-command' and `last-command'.
  14558. (let ((this-command this-command)
  14559. (last-command last-command))
  14560. (org-read-date
  14561. arg 'totime nil nil default-time default-input
  14562. inactive))))))
  14563. (cond
  14564. ((and ts
  14565. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14566. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14567. (insert "--")
  14568. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14569. (ts
  14570. ;; Make sure we're on a timestamp. When in the middle of a date
  14571. ;; range, move arbitrarily to range end.
  14572. (unless (org-at-timestamp-p 'lax)
  14573. (skip-chars-forward "-")
  14574. (org-at-timestamp-p 'lax))
  14575. (replace-match "")
  14576. (setq org-last-changed-timestamp
  14577. (org-insert-time-stamp
  14578. time (or org-time-was-given arg)
  14579. inactive nil nil (list org-end-time-was-given)))
  14580. (when repeater
  14581. (backward-char)
  14582. (insert " " repeater)
  14583. (setq org-last-changed-timestamp
  14584. (concat (substring org-last-inserted-timestamp 0 -1)
  14585. " " repeater ">")))
  14586. (message "Timestamp updated"))
  14587. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14588. (t (org-insert-time-stamp
  14589. time (or org-time-was-given arg) inactive nil nil
  14590. (list org-end-time-was-given))))))
  14591. ;; FIXME: can we use this for something else, like computing time differences?
  14592. (defun org-get-compact-tod (s)
  14593. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14594. (let* ((t1 (match-string 1 s))
  14595. (h1 (string-to-number (match-string 2 s)))
  14596. (m1 (string-to-number (match-string 3 s)))
  14597. (t2 (and (match-end 4) (match-string 5 s)))
  14598. (h2 (and t2 (string-to-number (match-string 6 s))))
  14599. (m2 (and t2 (string-to-number (match-string 7 s))))
  14600. dh dm)
  14601. (if (not t2)
  14602. t1
  14603. (setq dh (- h2 h1) dm (- m2 m1))
  14604. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14605. (concat t1 "+" (number-to-string dh)
  14606. (and (/= 0 dm) (format ":%02d" dm)))))))
  14607. (defun org-time-stamp-inactive (&optional arg)
  14608. "Insert an inactive time stamp.
  14609. An inactive time stamp is enclosed in square brackets instead of angle
  14610. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14611. does not link to the calendar and cannot be changed with the S-cursor keys.
  14612. So these are more for recording a certain time/date.
  14613. If the user specifies a time like HH:MM or if this command is called with
  14614. at least one prefix argument, the time stamp contains the date and the time.
  14615. Otherwise, only the date is included.
  14616. When called with two universal prefix arguments, insert an active time stamp
  14617. with the current time without prompting the user."
  14618. (interactive "P")
  14619. (org-time-stamp arg 'inactive))
  14620. (defvar org-date-ovl (make-overlay 1 1))
  14621. (overlay-put org-date-ovl 'face 'org-date-selected)
  14622. (delete-overlay org-date-ovl)
  14623. (defvar org-ans1) ; dynamically scoped parameter
  14624. (defvar org-ans2) ; dynamically scoped parameter
  14625. (defvar org-plain-time-of-day-regexp) ; defined below
  14626. (defvar org-overriding-default-time nil) ; dynamically scoped
  14627. (defvar org-read-date-overlay nil)
  14628. (defvar org-dcst nil) ; dynamically scoped
  14629. (defvar org-read-date-history nil)
  14630. (defvar org-read-date-final-answer nil)
  14631. (defvar org-read-date-analyze-futurep nil)
  14632. (defvar org-read-date-analyze-forced-year nil)
  14633. (defvar org-read-date-inactive)
  14634. (defvar org-read-date-minibuffer-local-map
  14635. (let* ((map (make-sparse-keymap)))
  14636. (set-keymap-parent map minibuffer-local-map)
  14637. (org-defkey map (kbd ".")
  14638. (lambda () (interactive)
  14639. ;; Are we at the beginning of the prompt?
  14640. (if (looking-back "^[^:]+: "
  14641. (let ((inhibit-field-text-motion t))
  14642. (line-beginning-position)))
  14643. (org-eval-in-calendar '(calendar-goto-today))
  14644. (insert "."))))
  14645. (org-defkey map (kbd "C-.")
  14646. (lambda () (interactive)
  14647. (org-eval-in-calendar '(calendar-goto-today))))
  14648. (org-defkey map (kbd "M-S-<left>")
  14649. (lambda () (interactive)
  14650. (org-eval-in-calendar '(calendar-backward-month 1))))
  14651. (org-defkey map (kbd "ESC S-<left>")
  14652. (lambda () (interactive)
  14653. (org-eval-in-calendar '(calendar-backward-month 1))))
  14654. (org-defkey map (kbd "M-S-<right>")
  14655. (lambda () (interactive)
  14656. (org-eval-in-calendar '(calendar-forward-month 1))))
  14657. (org-defkey map (kbd "ESC S-<right>")
  14658. (lambda () (interactive)
  14659. (org-eval-in-calendar '(calendar-forward-month 1))))
  14660. (org-defkey map (kbd "M-S-<up>")
  14661. (lambda () (interactive)
  14662. (org-eval-in-calendar '(calendar-backward-year 1))))
  14663. (org-defkey map (kbd "ESC S-<up>")
  14664. (lambda () (interactive)
  14665. (org-eval-in-calendar '(calendar-backward-year 1))))
  14666. (org-defkey map (kbd "M-S-<down>")
  14667. (lambda () (interactive)
  14668. (org-eval-in-calendar '(calendar-forward-year 1))))
  14669. (org-defkey map (kbd "ESC S-<down>")
  14670. (lambda () (interactive)
  14671. (org-eval-in-calendar '(calendar-forward-year 1))))
  14672. (org-defkey map (kbd "S-<up>")
  14673. (lambda () (interactive)
  14674. (org-eval-in-calendar '(calendar-backward-week 1))))
  14675. (org-defkey map (kbd "S-<down>")
  14676. (lambda () (interactive)
  14677. (org-eval-in-calendar '(calendar-forward-week 1))))
  14678. (org-defkey map (kbd "S-<left>")
  14679. (lambda () (interactive)
  14680. (org-eval-in-calendar '(calendar-backward-day 1))))
  14681. (org-defkey map (kbd "S-<right>")
  14682. (lambda () (interactive)
  14683. (org-eval-in-calendar '(calendar-forward-day 1))))
  14684. (org-defkey map (kbd "!")
  14685. (lambda () (interactive)
  14686. (org-eval-in-calendar '(diary-view-entries))
  14687. (message "")))
  14688. (org-defkey map (kbd ">")
  14689. (lambda () (interactive)
  14690. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14691. (org-defkey map (kbd "<")
  14692. (lambda () (interactive)
  14693. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14694. (org-defkey map (kbd "C-v")
  14695. (lambda () (interactive)
  14696. (org-eval-in-calendar
  14697. '(calendar-scroll-left-three-months 1))))
  14698. (org-defkey map (kbd "M-v")
  14699. (lambda () (interactive)
  14700. (org-eval-in-calendar
  14701. '(calendar-scroll-right-three-months 1))))
  14702. map)
  14703. "Keymap for minibuffer commands when using `org-read-date'.")
  14704. (defvar org-def)
  14705. (defvar org-defdecode)
  14706. (defvar org-with-time)
  14707. (defvar calendar-setup) ; Dynamically scoped.
  14708. (defun org-read-date (&optional with-time to-time from-string prompt
  14709. default-time default-input inactive)
  14710. "Read a date, possibly a time, and make things smooth for the user.
  14711. The prompt will suggest to enter an ISO date, but you can also enter anything
  14712. which will at least partially be understood by `parse-time-string'.
  14713. Unrecognized parts of the date will default to the current day, month, year,
  14714. hour and minute. If this command is called to replace a timestamp at point,
  14715. or to enter the second timestamp of a range, the default time is taken
  14716. from the existing stamp. Furthermore, the command prefers the future,
  14717. so if you are giving a date where the year is not given, and the day-month
  14718. combination is already past in the current year, it will assume you
  14719. mean next year. For details, see the manual. A few examples:
  14720. 3-2-5 --> 2003-02-05
  14721. feb 15 --> currentyear-02-15
  14722. 2/15 --> currentyear-02-15
  14723. sep 12 9 --> 2009-09-12
  14724. 12:45 --> today 12:45
  14725. 22 sept 0:34 --> currentyear-09-22 0:34
  14726. 12 --> currentyear-currentmonth-12
  14727. Fri --> nearest Friday after today
  14728. -Tue --> last Tuesday
  14729. etc.
  14730. Furthermore you can specify a relative date by giving, as the *first* thing
  14731. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14732. change in days weeks, months, years.
  14733. With a single plus or minus, the date is relative to today. With a double
  14734. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14735. +4d --> four days from today
  14736. +4 --> same as above
  14737. +2w --> two weeks from today
  14738. ++5 --> five days from default date
  14739. The function understands only English month and weekday abbreviations.
  14740. While prompting, a calendar is popped up - you can also select the
  14741. date with the mouse (button 1). The calendar shows a period of three
  14742. months. To scroll it to other months, use the keys `>' and `<'.
  14743. If you don't like the calendar, turn it off with
  14744. (setq org-read-date-popup-calendar nil)
  14745. With optional argument TO-TIME, the date will immediately be converted
  14746. to an internal time.
  14747. With an optional argument WITH-TIME, the prompt will suggest to
  14748. also insert a time. Note that when WITH-TIME is not set, you can
  14749. still enter a time, and this function will inform the calling routine
  14750. about this change. The calling routine may then choose to change the
  14751. format used to insert the time stamp into the buffer to include the time.
  14752. With optional argument FROM-STRING, read from this string instead from
  14753. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14754. the time/date that is used for everything that is not specified by the
  14755. user."
  14756. (require 'parse-time)
  14757. (let* ((org-with-time with-time)
  14758. (org-time-stamp-rounding-minutes
  14759. (if (equal org-with-time '(16))
  14760. '(0 0)
  14761. org-time-stamp-rounding-minutes))
  14762. (org-dcst org-display-custom-times)
  14763. (ct (org-current-time))
  14764. (org-def (or org-overriding-default-time default-time ct))
  14765. (org-defdecode (decode-time org-def))
  14766. (cur-frame (selected-frame))
  14767. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14768. (calendar-setup
  14769. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14770. (calendar-move-hook nil)
  14771. (calendar-view-diary-initially-flag nil)
  14772. (calendar-view-holidays-initially-flag nil)
  14773. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14774. ;; Rationalize `org-def' and `org-defdecode', if required.
  14775. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14776. (setf (nth 2 org-defdecode) -1)
  14777. (setf (nth 1 org-defdecode) 59)
  14778. (setq org-def (apply #'encode-time org-defdecode))
  14779. (setq org-defdecode (decode-time org-def)))
  14780. (let* ((timestr (format-time-string
  14781. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14782. org-def))
  14783. (prompt (concat (if prompt (concat prompt " ") "")
  14784. (format "Date+time [%s]: " timestr))))
  14785. (cond
  14786. (from-string (setq ans from-string))
  14787. (org-read-date-popup-calendar
  14788. (save-excursion
  14789. (save-window-excursion
  14790. (calendar)
  14791. (when (eq calendar-setup 'calendar-only)
  14792. (setq cal-frame
  14793. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14794. (select-frame cal-frame))
  14795. (org-eval-in-calendar '(setq cursor-type nil) t)
  14796. (unwind-protect
  14797. (progn
  14798. (calendar-forward-day (- (time-to-days org-def)
  14799. (calendar-absolute-from-gregorian
  14800. (calendar-current-date))))
  14801. (org-eval-in-calendar nil t)
  14802. (let* ((old-map (current-local-map))
  14803. (map (copy-keymap calendar-mode-map))
  14804. (minibuffer-local-map
  14805. (copy-keymap org-read-date-minibuffer-local-map)))
  14806. (org-defkey map (kbd "RET") 'org-calendar-select)
  14807. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14808. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14809. (unwind-protect
  14810. (progn
  14811. (use-local-map map)
  14812. (setq org-read-date-inactive inactive)
  14813. (add-hook 'post-command-hook 'org-read-date-display)
  14814. (setq org-ans0
  14815. (read-string prompt
  14816. default-input
  14817. 'org-read-date-history
  14818. nil))
  14819. ;; org-ans0: from prompt
  14820. ;; org-ans1: from mouse click
  14821. ;; org-ans2: from calendar motion
  14822. (setq ans
  14823. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14824. (remove-hook 'post-command-hook 'org-read-date-display)
  14825. (use-local-map old-map)
  14826. (when org-read-date-overlay
  14827. (delete-overlay org-read-date-overlay)
  14828. (setq org-read-date-overlay nil)))))
  14829. (bury-buffer "*Calendar*")
  14830. (when cal-frame
  14831. (delete-frame cal-frame)
  14832. (select-frame-set-input-focus cur-frame))))))
  14833. (t ; Naked prompt only
  14834. (unwind-protect
  14835. (setq ans (read-string prompt default-input
  14836. 'org-read-date-history timestr))
  14837. (when org-read-date-overlay
  14838. (delete-overlay org-read-date-overlay)
  14839. (setq org-read-date-overlay nil))))))
  14840. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14841. (when org-read-date-analyze-forced-year
  14842. (message "Year was forced into %s"
  14843. (if org-read-date-force-compatible-dates
  14844. "compatible range (1970-2037)"
  14845. "range representable on this machine"))
  14846. (ding))
  14847. ;; One round trip to get rid of 34th of August and stuff like that....
  14848. (setq final (decode-time (apply 'encode-time final)))
  14849. (setq org-read-date-final-answer ans)
  14850. (if to-time
  14851. (apply 'encode-time final)
  14852. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14853. (format "%04d-%02d-%02d %02d:%02d"
  14854. (nth 5 final) (nth 4 final) (nth 3 final)
  14855. (nth 2 final) (nth 1 final))
  14856. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14857. (defun org-read-date-display ()
  14858. "Display the current date prompt interpretation in the minibuffer."
  14859. (when org-read-date-display-live
  14860. (when org-read-date-overlay
  14861. (delete-overlay org-read-date-overlay))
  14862. (when (minibufferp (current-buffer))
  14863. (save-excursion
  14864. (end-of-line 1)
  14865. (while (not (equal (buffer-substring
  14866. (max (point-min) (- (point) 4)) (point))
  14867. " "))
  14868. (insert " ")))
  14869. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14870. " " (or org-ans1 org-ans2)))
  14871. (org-end-time-was-given nil)
  14872. (f (org-read-date-analyze ans org-def org-defdecode))
  14873. (fmts (if org-dcst
  14874. org-time-stamp-custom-formats
  14875. org-time-stamp-formats))
  14876. (fmt (if (or org-with-time
  14877. (and (boundp 'org-time-was-given) org-time-was-given))
  14878. (cdr fmts)
  14879. (car fmts)))
  14880. (txt (format-time-string fmt (apply 'encode-time f)))
  14881. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14882. (txt (concat "=> " txt)))
  14883. (when (and org-end-time-was-given
  14884. (string-match org-plain-time-of-day-regexp txt))
  14885. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14886. org-end-time-was-given
  14887. (substring txt (match-end 0)))))
  14888. (when org-read-date-analyze-futurep
  14889. (setq txt (concat txt " (=>F)")))
  14890. (setq org-read-date-overlay
  14891. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14892. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14893. (defun org-read-date-analyze (ans def defdecode)
  14894. "Analyze the combined answer of the date prompt."
  14895. ;; FIXME: cleanup and comment
  14896. ;; Pass `current-time' result to `decode-time' (instead of calling
  14897. ;; without arguments) so that only `current-time' has to be
  14898. ;; overridden in tests.
  14899. (let ((org-def def)
  14900. (org-defdecode defdecode)
  14901. (nowdecode (decode-time (current-time)))
  14902. delta deltan deltaw deltadef year month day
  14903. hour minute second wday pm h2 m2 tl wday1
  14904. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14905. (setq org-read-date-analyze-futurep nil
  14906. org-read-date-analyze-forced-year nil)
  14907. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14908. (setq ans "+0"))
  14909. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14910. (setq ans (replace-match "" t t ans)
  14911. deltan (car delta)
  14912. deltaw (nth 1 delta)
  14913. deltadef (nth 2 delta)))
  14914. ;; Check if there is an iso week date in there. If yes, store the
  14915. ;; info and postpone interpreting it until the rest of the parsing
  14916. ;; is done.
  14917. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14918. (setq iso-year (when (match-end 1)
  14919. (org-small-year-to-year
  14920. (string-to-number (match-string 1 ans))))
  14921. iso-weekday (when (match-end 3)
  14922. (string-to-number (match-string 3 ans)))
  14923. iso-week (string-to-number (match-string 2 ans)))
  14924. (setq ans (replace-match "" t t ans)))
  14925. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14926. (when (string-match
  14927. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14928. (setq year (if (match-end 2)
  14929. (string-to-number (match-string 2 ans))
  14930. (progn (setq kill-year t)
  14931. (string-to-number (format-time-string "%Y"))))
  14932. month (string-to-number (match-string 3 ans))
  14933. day (string-to-number (match-string 4 ans)))
  14934. (setq year (org-small-year-to-year year))
  14935. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14936. t nil ans)))
  14937. ;; Help matching dotted european dates
  14938. (when (string-match
  14939. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14940. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14941. (setq kill-year t)
  14942. (string-to-number (format-time-string "%Y")))
  14943. day (string-to-number (match-string 1 ans))
  14944. month (string-to-number (match-string 2 ans))
  14945. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14946. t nil ans)))
  14947. ;; Help matching american dates, like 5/30 or 5/30/7
  14948. (when (string-match
  14949. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14950. (setq year (if (match-end 4)
  14951. (string-to-number (match-string 4 ans))
  14952. (progn (setq kill-year t)
  14953. (string-to-number (format-time-string "%Y"))))
  14954. month (string-to-number (match-string 1 ans))
  14955. day (string-to-number (match-string 2 ans)))
  14956. (setq year (org-small-year-to-year year))
  14957. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14958. t nil ans)))
  14959. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14960. ;; If there is a time with am/pm, and *no* time without it, we convert
  14961. ;; so that matching will be successful.
  14962. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14963. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14964. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14965. (setq hour (string-to-number (match-string 1 ans))
  14966. minute (if (match-end 3)
  14967. (string-to-number (match-string 3 ans))
  14968. 0)
  14969. pm (equal ?p
  14970. (string-to-char (downcase (match-string 4 ans)))))
  14971. (if (and (= hour 12) (not pm))
  14972. (setq hour 0)
  14973. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14974. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14975. t t ans))))
  14976. ;; Check if a time range is given as a duration
  14977. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14978. (setq hour (string-to-number (match-string 1 ans))
  14979. h2 (+ hour (string-to-number (match-string 3 ans)))
  14980. minute (string-to-number (match-string 2 ans))
  14981. m2 (+ minute (if (match-end 5) (string-to-number
  14982. (match-string 5 ans))0)))
  14983. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14984. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14985. t t ans)))
  14986. ;; Check if there is a time range
  14987. (when (boundp 'org-end-time-was-given)
  14988. (setq org-time-was-given nil)
  14989. (when (and (string-match org-plain-time-of-day-regexp ans)
  14990. (match-end 8))
  14991. (setq org-end-time-was-given (match-string 8 ans))
  14992. (setq ans (concat (substring ans 0 (match-beginning 7))
  14993. (substring ans (match-end 7))))))
  14994. (setq tl (parse-time-string ans)
  14995. day (or (nth 3 tl) (nth 3 org-defdecode))
  14996. month
  14997. (cond ((nth 4 tl))
  14998. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14999. ;; Day was specified. Make sure DAY+MONTH
  15000. ;; combination happens in the future.
  15001. ((nth 3 tl)
  15002. (setq futurep t)
  15003. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15004. (nth 4 nowdecode)))
  15005. (t (nth 4 org-defdecode)))
  15006. year
  15007. (cond ((and (not kill-year) (nth 5 tl)))
  15008. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15009. ;; Month was guessed in the future and is at least
  15010. ;; equal to NOWDECODE's. Fix year accordingly.
  15011. (futurep
  15012. (if (or (> month (nth 4 nowdecode))
  15013. (>= day (nth 3 nowdecode)))
  15014. (nth 5 nowdecode)
  15015. (1+ (nth 5 nowdecode))))
  15016. ;; Month was specified. Make sure MONTH+YEAR
  15017. ;; combination happens in the future.
  15018. ((nth 4 tl)
  15019. (setq futurep t)
  15020. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15021. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15022. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15023. (t (nth 5 nowdecode))))
  15024. (t (nth 5 org-defdecode)))
  15025. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15026. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15027. second (or (nth 0 tl) 0)
  15028. wday (nth 6 tl))
  15029. (when (and (eq org-read-date-prefer-future 'time)
  15030. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15031. (equal day (nth 3 nowdecode))
  15032. (equal month (nth 4 nowdecode))
  15033. (equal year (nth 5 nowdecode))
  15034. (nth 2 tl)
  15035. (or (< (nth 2 tl) (nth 2 nowdecode))
  15036. (and (= (nth 2 tl) (nth 2 nowdecode))
  15037. (nth 1 tl)
  15038. (< (nth 1 tl) (nth 1 nowdecode)))))
  15039. (setq day (1+ day)
  15040. futurep t))
  15041. ;; Special date definitions below
  15042. (cond
  15043. (iso-week
  15044. ;; There was an iso week
  15045. (require 'cal-iso)
  15046. (setq futurep nil)
  15047. (setq year (or iso-year year)
  15048. day (or iso-weekday wday 1)
  15049. wday nil ; to make sure that the trigger below does not match
  15050. iso-date (calendar-gregorian-from-absolute
  15051. (calendar-iso-to-absolute
  15052. (list iso-week day year))))
  15053. ; FIXME: Should we also push ISO weeks into the future?
  15054. ; (when (and org-read-date-prefer-future
  15055. ; (not iso-year)
  15056. ; (< (calendar-absolute-from-gregorian iso-date)
  15057. ; (time-to-days (current-time))))
  15058. ; (setq year (1+ year)
  15059. ; iso-date (calendar-gregorian-from-absolute
  15060. ; (calendar-iso-to-absolute
  15061. ; (list iso-week day year)))))
  15062. (setq month (car iso-date)
  15063. year (nth 2 iso-date)
  15064. day (nth 1 iso-date)))
  15065. (deltan
  15066. (setq futurep nil)
  15067. (unless deltadef
  15068. ;; Pass `current-time' result to `decode-time' (instead of
  15069. ;; calling without arguments) so that only `current-time' has
  15070. ;; to be overridden in tests.
  15071. (let ((now (decode-time (current-time))))
  15072. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15073. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15074. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15075. ((equal deltaw "m") (setq month (+ month deltan)))
  15076. ((equal deltaw "y") (setq year (+ year deltan)))))
  15077. ((and wday (not (nth 3 tl)))
  15078. ;; Weekday was given, but no day, so pick that day in the week
  15079. ;; on or after the derived date.
  15080. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15081. (unless (equal wday wday1)
  15082. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15083. (when (and (boundp 'org-time-was-given)
  15084. (nth 2 tl))
  15085. (setq org-time-was-given t))
  15086. (when (< year 100) (setq year (+ 2000 year)))
  15087. ;; Check of the date is representable
  15088. (if org-read-date-force-compatible-dates
  15089. (progn
  15090. (when (< year 1970)
  15091. (setq year 1970 org-read-date-analyze-forced-year t))
  15092. (when (> year 2037)
  15093. (setq year 2037 org-read-date-analyze-forced-year t)))
  15094. (condition-case nil
  15095. (ignore (encode-time second minute hour day month year))
  15096. (error
  15097. (setq year (nth 5 org-defdecode))
  15098. (setq org-read-date-analyze-forced-year t))))
  15099. (setq org-read-date-analyze-futurep futurep)
  15100. (list second minute hour day month year)))
  15101. (defvar parse-time-weekdays)
  15102. (defun org-read-date-get-relative (s today default)
  15103. "Check string S for special relative date string.
  15104. TODAY and DEFAULT are internal times, for today and for a default.
  15105. Return shift list (N what def-flag)
  15106. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15107. N is the number of WHATs to shift.
  15108. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15109. the DEFAULT date rather than TODAY."
  15110. (require 'parse-time)
  15111. (when (and
  15112. (string-match
  15113. (concat
  15114. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15115. "\\([0-9]+\\)?"
  15116. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15117. "\\([ \t]\\|$\\)") s)
  15118. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15119. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15120. (string-to-char (substring (match-string 1 s) -1))
  15121. ?+))
  15122. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15123. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15124. (what (if (match-end 3) (match-string 3 s) "d"))
  15125. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15126. (date (if rel default today))
  15127. (wday (nth 6 (decode-time date)))
  15128. delta)
  15129. (if wday1
  15130. (progn
  15131. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15132. (when (= delta 0) (setq delta 7))
  15133. (when (= dir ?-)
  15134. (setq delta (- delta 7))
  15135. (when (= delta 0) (setq delta -7)))
  15136. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15137. (list delta "d" rel))
  15138. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15139. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15140. "Turn a user-specified date into the internal representation.
  15141. The internal representation needed by the calendar is (month day year).
  15142. This is a wrapper to handle the brain-dead convention in calendar that
  15143. user function argument order change dependent on argument order."
  15144. (pcase calendar-date-style
  15145. (`american (list arg1 arg2 arg3))
  15146. (`european (list arg2 arg1 arg3))
  15147. (`iso (list arg2 arg3 arg1))))
  15148. (defun org-eval-in-calendar (form &optional keepdate)
  15149. "Eval FORM in the calendar window and return to current window.
  15150. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15151. (let ((sf (selected-frame))
  15152. (sw (selected-window)))
  15153. (select-window (get-buffer-window "*Calendar*" t))
  15154. (eval form)
  15155. (when (and (not keepdate) (calendar-cursor-to-date))
  15156. (let* ((date (calendar-cursor-to-date))
  15157. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15158. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15159. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15160. (select-window sw)
  15161. (select-frame-set-input-focus sf)))
  15162. (defun org-calendar-select ()
  15163. "Return to `org-read-date' with the date currently selected.
  15164. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15165. (interactive)
  15166. (when (calendar-cursor-to-date)
  15167. (let* ((date (calendar-cursor-to-date))
  15168. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15169. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15170. (when (active-minibuffer-window) (exit-minibuffer))))
  15171. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15172. "Insert a date stamp for the date given by the internal TIME.
  15173. See `format-time-string' for the format of TIME.
  15174. WITH-HM means use the stamp format that includes the time of the day.
  15175. INACTIVE means use square brackets instead of angular ones, so that the
  15176. stamp will not contribute to the agenda.
  15177. PRE and POST are optional strings to be inserted before and after the
  15178. stamp.
  15179. The command returns the inserted time stamp."
  15180. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15181. stamp)
  15182. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15183. (insert-before-markers (or pre ""))
  15184. (when (listp extra)
  15185. (setq extra (car extra))
  15186. (if (and (stringp extra)
  15187. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15188. (setq extra (format "-%02d:%02d"
  15189. (string-to-number (match-string 1 extra))
  15190. (string-to-number (match-string 2 extra))))
  15191. (setq extra nil)))
  15192. (when extra
  15193. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15194. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15195. (insert-before-markers (or post ""))
  15196. (setq org-last-inserted-timestamp stamp)))
  15197. (defun org-toggle-time-stamp-overlays ()
  15198. "Toggle the use of custom time stamp formats."
  15199. (interactive)
  15200. (setq org-display-custom-times (not org-display-custom-times))
  15201. (unless org-display-custom-times
  15202. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15203. (while (setq p (next-single-property-change p 'display))
  15204. (when (and (get-text-property p 'display)
  15205. (eq (get-text-property p 'face) 'org-date))
  15206. (remove-text-properties
  15207. p (setq p (next-single-property-change p 'display))
  15208. '(display t))))
  15209. (set-buffer-modified-p bmp)))
  15210. (org-restart-font-lock)
  15211. (setq org-table-may-need-update t)
  15212. (if org-display-custom-times
  15213. (message "Time stamps are overlaid with custom format")
  15214. (message "Time stamp overlays removed")))
  15215. (defun org-display-custom-time (beg end)
  15216. "Overlay modified time stamp format over timestamp between BEG and END."
  15217. (let* ((ts (buffer-substring beg end))
  15218. t1 with-hm tf time str (off 0))
  15219. (save-match-data
  15220. (setq t1 (org-parse-time-string ts t))
  15221. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15222. (setq off (- (match-end 0) (match-beginning 0)))))
  15223. (setq end (- end off))
  15224. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15225. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15226. time (org-fix-decoded-time t1)
  15227. str (org-add-props
  15228. (format-time-string
  15229. (substring tf 1 -1) (apply 'encode-time time))
  15230. nil 'mouse-face 'highlight))
  15231. (put-text-property beg end 'display str)))
  15232. (defun org-fix-decoded-time (time)
  15233. "Set 0 instead of nil for the first 6 elements of time.
  15234. Don't touch the rest."
  15235. (let ((n 0))
  15236. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15237. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15238. "Difference between TIMESTAMP-STRING and now in days.
  15239. If SECONDS is non-nil, return the difference in seconds."
  15240. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15241. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15242. (funcall fdiff (current-time)))))
  15243. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15244. "Is the time in TIMESTAMP-STRING close to the current date?"
  15245. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15246. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15247. (not (org-entry-is-done-p))))
  15248. (defun org-get-wdays (ts &optional delay zero-delay)
  15249. "Get the deadline lead time appropriate for timestring TS.
  15250. When DELAY is non-nil, get the delay time for scheduled items
  15251. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15252. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15253. don't try to find the delay cookie in the scheduled timestamp."
  15254. (let ((tv (if delay org-scheduled-delay-days
  15255. org-deadline-warning-days)))
  15256. (cond
  15257. ((or (and delay (< tv 0))
  15258. (and delay zero-delay (<= tv 0))
  15259. (and (not delay) (<= tv 0)))
  15260. ;; Enforce this value no matter what
  15261. (- tv))
  15262. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15263. ;; lead time is specified.
  15264. (floor (* (string-to-number (match-string 1 ts))
  15265. (cdr (assoc (match-string 2 ts)
  15266. '(("d" . 1) ("w" . 7)
  15267. ("m" . 30.4) ("y" . 365.25)
  15268. ("h" . 0.041667)))))))
  15269. ;; go for the default.
  15270. (t tv))))
  15271. (defun org-calendar-select-mouse (ev)
  15272. "Return to `org-read-date' with the date currently selected.
  15273. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15274. (interactive "e")
  15275. (mouse-set-point ev)
  15276. (when (calendar-cursor-to-date)
  15277. (let* ((date (calendar-cursor-to-date))
  15278. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15279. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15280. (when (active-minibuffer-window) (exit-minibuffer))))
  15281. (defun org-check-deadlines (ndays)
  15282. "Check if there are any deadlines due or past due.
  15283. A deadline is considered due if it happens within `org-deadline-warning-days'
  15284. days from today's date. If the deadline appears in an entry marked DONE,
  15285. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15286. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15287. are shown."
  15288. (interactive "P")
  15289. (let* ((org-warn-days
  15290. (cond
  15291. ((equal ndays '(4)) 100000)
  15292. (ndays (prefix-numeric-value ndays))
  15293. (t (abs org-deadline-warning-days))))
  15294. (case-fold-search nil)
  15295. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15296. (callback
  15297. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15298. (message "%d deadlines past-due or due within %d days"
  15299. (org-occur regexp nil callback)
  15300. org-warn-days)))
  15301. (defsubst org-re-timestamp (type)
  15302. "Return a regexp for timestamp TYPE.
  15303. Allowed values for TYPE are:
  15304. all: all timestamps
  15305. active: only active timestamps (<...>)
  15306. inactive: only inactive timestamps ([...])
  15307. scheduled: only scheduled timestamps
  15308. deadline: only deadline timestamps
  15309. closed: only closed time-stamps
  15310. When TYPE is nil, fall back on returning a regexp that matches
  15311. both scheduled and deadline timestamps."
  15312. (cl-case type
  15313. (all org-ts-regexp-both)
  15314. (active org-ts-regexp)
  15315. (inactive org-ts-regexp-inactive)
  15316. (scheduled org-scheduled-time-regexp)
  15317. (deadline org-deadline-time-regexp)
  15318. (closed org-closed-time-regexp)
  15319. (otherwise
  15320. (concat "\\<"
  15321. (regexp-opt (list org-deadline-string org-scheduled-string))
  15322. " *<\\([^>]+\\)>"))))
  15323. (defun org-check-before-date (d)
  15324. "Check if there are deadlines or scheduled entries before 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. (time-less-p
  15339. (org-time-string-to-time match)
  15340. (org-time-string-to-time d)))))))
  15341. (message "%d entries before %s"
  15342. (org-occur regexp nil callback)
  15343. d)))
  15344. (defun org-check-after-date (d)
  15345. "Check if there are deadlines or scheduled entries after date D."
  15346. (interactive (list (org-read-date)))
  15347. (let* ((case-fold-search nil)
  15348. (regexp (org-re-timestamp org-ts-type))
  15349. (ts-type org-ts-type)
  15350. (callback
  15351. (lambda ()
  15352. (let ((match (match-string 1)))
  15353. (and (if (memq ts-type '(active inactive all))
  15354. (eq (org-element-type (save-excursion
  15355. (backward-char)
  15356. (org-element-context)))
  15357. 'timestamp)
  15358. (org-at-planning-p))
  15359. (not (time-less-p
  15360. (org-time-string-to-time match)
  15361. (org-time-string-to-time d))))))))
  15362. (message "%d entries after %s"
  15363. (org-occur regexp nil callback)
  15364. d)))
  15365. (defun org-check-dates-range (start-date end-date)
  15366. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15367. (interactive (list (org-read-date nil nil nil "Range starts")
  15368. (org-read-date nil nil nil "Range end")))
  15369. (let ((case-fold-search nil)
  15370. (regexp (org-re-timestamp org-ts-type))
  15371. (callback
  15372. (let ((type org-ts-type))
  15373. (lambda ()
  15374. (let ((match (match-string 1)))
  15375. (and
  15376. (if (memq type '(active inactive all))
  15377. (eq (org-element-type (save-excursion
  15378. (backward-char)
  15379. (org-element-context)))
  15380. 'timestamp)
  15381. (org-at-planning-p))
  15382. (not (time-less-p
  15383. (org-time-string-to-time match)
  15384. (org-time-string-to-time start-date)))
  15385. (time-less-p
  15386. (org-time-string-to-time match)
  15387. (org-time-string-to-time end-date))))))))
  15388. (message "%d entries between %s and %s"
  15389. (org-occur regexp nil callback) start-date end-date)))
  15390. (defun org-evaluate-time-range (&optional to-buffer)
  15391. "Evaluate a time range by computing the difference between start and end.
  15392. Normally the result is just printed in the echo area, but with prefix arg
  15393. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15394. If the time range is actually in a table, the result is inserted into the
  15395. next column.
  15396. For time difference computation, a year is assumed to be exactly 365
  15397. days in order to avoid rounding problems."
  15398. (interactive "P")
  15399. (or
  15400. (org-clock-update-time-maybe)
  15401. (save-excursion
  15402. (unless (org-at-date-range-p t)
  15403. (goto-char (point-at-bol))
  15404. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15405. (unless (org-at-date-range-p t)
  15406. (user-error "Not at a time-stamp range, and none found in current line")))
  15407. (let* ((ts1 (match-string 1))
  15408. (ts2 (match-string 2))
  15409. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15410. (match-end (match-end 0))
  15411. (time1 (org-time-string-to-time ts1))
  15412. (time2 (org-time-string-to-time ts2))
  15413. (t1 (float-time time1))
  15414. (t2 (float-time time2))
  15415. (diff (abs (- t2 t1)))
  15416. (negative (< (- t2 t1) 0))
  15417. ;; (ys (floor (* 365 24 60 60)))
  15418. (ds (* 24 60 60))
  15419. (hs (* 60 60))
  15420. (fy "%dy %dd %02d:%02d")
  15421. (fy1 "%dy %dd")
  15422. (fd "%dd %02d:%02d")
  15423. (fd1 "%dd")
  15424. (fh "%02d:%02d")
  15425. y d h m align)
  15426. (if havetime
  15427. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15428. y 0
  15429. d (floor (/ diff ds)) diff (mod diff ds)
  15430. h (floor (/ diff hs)) diff (mod diff hs)
  15431. m (floor (/ diff 60)))
  15432. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15433. y 0
  15434. d (floor (+ (/ diff ds) 0.5))
  15435. h 0 m 0))
  15436. (if (not to-buffer)
  15437. (message "%s" (org-make-tdiff-string y d h m))
  15438. (if (org-at-table-p)
  15439. (progn
  15440. (goto-char match-end)
  15441. (setq align t)
  15442. (and (looking-at " *|") (goto-char (match-end 0))))
  15443. (goto-char match-end))
  15444. (when (looking-at
  15445. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15446. (replace-match ""))
  15447. (when negative (insert " -"))
  15448. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15449. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15450. (insert " " (format fh h m))))
  15451. (when align (org-table-align))
  15452. (message "Time difference inserted")))))
  15453. (defun org-make-tdiff-string (y d h m)
  15454. (let ((fmt "")
  15455. (l nil))
  15456. (when (> y 0)
  15457. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15458. (push y l))
  15459. (when (> d 0)
  15460. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15461. (push d l))
  15462. (when (> h 0)
  15463. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15464. (push h l))
  15465. (when (> m 0)
  15466. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15467. (push m l))
  15468. (apply 'format fmt (nreverse l))))
  15469. (defun org-time-string-to-time (s)
  15470. "Convert timestamp string S into internal time."
  15471. (apply #'encode-time (org-parse-time-string s)))
  15472. (defun org-time-string-to-seconds (s)
  15473. "Convert a timestamp string S into a number of seconds."
  15474. (float-time (org-time-string-to-time s)))
  15475. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15476. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15477. "Convert time stamp S to an absolute day number.
  15478. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15479. stamp, get the closest date to DAYNR. If PREFER is
  15480. `past' (respectively `future') return a date past (respectively
  15481. after) or equal to DAYNR.
  15482. POS is the location of time stamp S, as a buffer position in
  15483. BUFFER.
  15484. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15485. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15486. signaled."
  15487. (cond
  15488. ((string-match "\\`%%\\((.*)\\)" s)
  15489. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15490. ;; only able to match individual dates. If it fails, raise an
  15491. ;; error.
  15492. (if (and daynr
  15493. (org-diary-sexp-entry
  15494. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15495. daynr
  15496. (signal 'org-diary-sexp-no-match (list s))))
  15497. (daynr (org-closest-date s daynr prefer))
  15498. (t (time-to-days
  15499. (condition-case errdata
  15500. (apply #'encode-time (org-parse-time-string s))
  15501. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15502. s
  15503. (if (not (and buffer pos)) ""
  15504. (format-message " at %d in buffer `%s'" pos buffer))
  15505. (cdr errdata))))))))
  15506. (defun org-days-to-iso-week (days)
  15507. "Return the iso week number."
  15508. (require 'cal-iso)
  15509. (car (calendar-iso-from-absolute days)))
  15510. (defun org-small-year-to-year (year)
  15511. "Convert 2-digit years into 4-digit years.
  15512. YEAR is expanded into one of the 30 next years, if possible, or
  15513. into a past one. Any year larger than 99 is returned unchanged."
  15514. (if (>= year 100) year
  15515. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15516. (century (/ current 100))
  15517. (offset (- year (% current 100))))
  15518. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15519. ((> offset -70) (+ (* century 100) year))
  15520. (t (+ (* (1+ century) 100) year))))))
  15521. (defun org-time-from-absolute (d)
  15522. "Return the time corresponding to date D.
  15523. D may be an absolute day number, or a calendar-type list (month day year)."
  15524. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15525. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15526. (defvar org-agenda-current-date)
  15527. (defun org-calendar-holiday ()
  15528. "List of holidays, for Diary display in Org mode."
  15529. (require 'holidays)
  15530. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15531. (and hl (mapconcat #'identity hl "; "))))
  15532. (defun org-diary-sexp-entry (sexp entry d)
  15533. "Process a SEXP diary ENTRY for date D."
  15534. (require 'diary-lib)
  15535. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15536. ;; dynamically.
  15537. (let* ((sexp `(let ((entry ,entry)
  15538. (date ',d))
  15539. ,(car (read-from-string sexp))))
  15540. (result (if calendar-debug-sexp (eval sexp)
  15541. (condition-case nil
  15542. (eval sexp)
  15543. (error
  15544. (beep)
  15545. (message "Bad sexp at line %d in %s: %s"
  15546. (org-current-line)
  15547. (buffer-file-name) sexp)
  15548. (sleep-for 2))))))
  15549. (cond ((stringp result) (split-string result "; "))
  15550. ((and (consp result)
  15551. (not (consp (cdr result)))
  15552. (stringp (cdr result))) (cdr result))
  15553. ((and (consp result)
  15554. (stringp (car result))) result)
  15555. (result entry))))
  15556. (defun org-diary-to-ical-string (frombuf)
  15557. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15558. This uses the icalendar.el library."
  15559. (let* ((tmpdir temporary-file-directory)
  15560. (tmpfile (make-temp-name
  15561. (expand-file-name "orgics" tmpdir)))
  15562. buf rtn b e)
  15563. (with-current-buffer frombuf
  15564. (icalendar-export-region (point-min) (point-max) tmpfile)
  15565. (setq buf (find-buffer-visiting tmpfile))
  15566. (set-buffer buf)
  15567. (goto-char (point-min))
  15568. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15569. (setq b (match-beginning 0)))
  15570. (goto-char (point-max))
  15571. (when (re-search-backward "^END:VEVENT" nil t)
  15572. (setq e (match-end 0)))
  15573. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15574. (kill-buffer buf)
  15575. (delete-file tmpfile)
  15576. rtn))
  15577. (defun org-closest-date (start current prefer)
  15578. "Return closest date to CURRENT starting from START.
  15579. CURRENT and START are both time stamps.
  15580. When PREFER is `past', return a date that is either CURRENT or
  15581. past. When PREFER is `future', return a date that is either
  15582. CURRENT or future.
  15583. Only time stamps with a repeater are modified. Any other time
  15584. stamp stay unchanged. In any case, return value is an absolute
  15585. day number."
  15586. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15587. ;; No repeater. Do not shift time stamp.
  15588. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15589. (let ((value (string-to-number (match-string 1 start)))
  15590. (type (match-string 2 start)))
  15591. (if (= 0 value)
  15592. ;; Repeater with a 0-value is considered as void.
  15593. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15594. (let* ((base (org-date-to-gregorian start))
  15595. (target (org-date-to-gregorian current))
  15596. (sday (calendar-absolute-from-gregorian base))
  15597. (cday (calendar-absolute-from-gregorian target))
  15598. n1 n2)
  15599. ;; If START is already past CURRENT, just return START.
  15600. (if (<= cday sday) sday
  15601. ;; Compute closest date before (N1) and closest date past
  15602. ;; (N2) CURRENT.
  15603. (pcase type
  15604. ("h"
  15605. (let ((missing-hours
  15606. (mod (+ (- (* 24 (- cday sday))
  15607. (nth 2 (org-parse-time-string start)))
  15608. org-extend-today-until)
  15609. value)))
  15610. (setf n1 (if (= missing-hours 0) cday
  15611. (- cday (1+ (/ missing-hours 24)))))
  15612. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15613. ((or "d" "w")
  15614. (let ((value (if (equal type "w") (* 7 value) value)))
  15615. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15616. (setf n2 (+ n1 value))))
  15617. ("m"
  15618. (let* ((add-months
  15619. (lambda (d n)
  15620. ;; Add N months to gregorian date D, i.e.,
  15621. ;; a list (MONTH DAY YEAR). Return a valid
  15622. ;; gregorian date.
  15623. (let ((m (+ (nth 0 d) n)))
  15624. (list (mod m 12)
  15625. (nth 1 d)
  15626. (+ (/ m 12) (nth 2 d))))))
  15627. (months ; Complete months to TARGET.
  15628. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15629. (- (nth 0 target) (nth 0 base))
  15630. ;; If START's day is greater than
  15631. ;; TARGET's, remove incomplete month.
  15632. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15633. value)
  15634. value))
  15635. (before (funcall add-months base months)))
  15636. (setf n1 (calendar-absolute-from-gregorian before))
  15637. (setf n2
  15638. (calendar-absolute-from-gregorian
  15639. (funcall add-months before value)))))
  15640. (_
  15641. (let* ((d (nth 1 base))
  15642. (m (nth 0 base))
  15643. (y (nth 2 base))
  15644. (years ; Complete years to TARGET.
  15645. (* (/ (- (nth 2 target)
  15646. y
  15647. ;; If START's month and day are
  15648. ;; greater than TARGET's, remove
  15649. ;; incomplete year.
  15650. (if (or (> (nth 0 target) m)
  15651. (and (= (nth 0 target) m)
  15652. (> (nth 1 target) d)))
  15653. 0
  15654. 1))
  15655. value)
  15656. value))
  15657. (before (list m d (+ y years))))
  15658. (setf n1 (calendar-absolute-from-gregorian before))
  15659. (setf n2 (calendar-absolute-from-gregorian
  15660. (list m d (+ (nth 2 before) value)))))))
  15661. ;; Handle PREFER parameter, if any.
  15662. (cond
  15663. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15664. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15665. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15666. (defun org-date-to-gregorian (d)
  15667. "Turn any specification of date D into a Gregorian date for the calendar."
  15668. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15669. ((and (listp d) (= (length d) 3)) d)
  15670. ((stringp d)
  15671. (let ((d (org-parse-time-string d)))
  15672. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15673. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15674. (defun org-timestamp-up (&optional arg)
  15675. "Increase the date item at the cursor by one.
  15676. If the cursor is on the year, change the year. If it is on the month,
  15677. the day or the time, change that. If the cursor is on the enclosing
  15678. bracket, change the timestamp type.
  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. If the cursor is on the enclosing
  15686. bracket, change the timestamp type.
  15687. With prefix ARG, change by that many units."
  15688. (interactive "p")
  15689. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15690. (defun org-timestamp-up-day (&optional arg)
  15691. "Increase the date in the time stamp by one day.
  15692. With prefix ARG, change that many days."
  15693. (interactive "p")
  15694. (if (and (not (org-at-timestamp-p 'lax))
  15695. (org-at-heading-p))
  15696. (org-todo 'up)
  15697. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15698. (defun org-timestamp-down-day (&optional arg)
  15699. "Decrease the date in the time stamp by one day.
  15700. With prefix ARG, change that many days."
  15701. (interactive "p")
  15702. (if (and (not (org-at-timestamp-p 'lax))
  15703. (org-at-heading-p))
  15704. (org-todo 'down)
  15705. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15706. (defun org-at-timestamp-p (&optional extended)
  15707. "Non-nil if point is inside a timestamp.
  15708. By default, the function only consider syntactically valid active
  15709. timestamps. However, the caller may have a broader definition
  15710. for timestamps. As a consequence, optional argument EXTENDED can
  15711. be set to the following values
  15712. `inactive'
  15713. Include also syntactically valid inactive timestamps.
  15714. `agenda'
  15715. Include timestamps allowed in Agenda, i.e., those in
  15716. properties drawers, planning lines and clock lines.
  15717. `lax'
  15718. Ignore context. The function matches any part of the
  15719. document looking like a timestamp. This includes comments,
  15720. example blocks...
  15721. For backward-compatibility with Org 9.0, every other non-nil
  15722. value is equivalent to `inactive'.
  15723. When at a timestamp, return the position of the point as a symbol
  15724. among `bracket', `after', `year', `month', `hour', `minute',
  15725. `day' or a number of character from the last know part of the
  15726. time stamp.
  15727. When matching, the match groups are the following:
  15728. group 1: year
  15729. group 2: month
  15730. group 3: day number
  15731. group 4: day name
  15732. group 5: hours, if any
  15733. group 6: minutes, if any"
  15734. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15735. (pos (point))
  15736. (match?
  15737. (let ((boundaries (org-in-regexp regexp)))
  15738. (save-match-data
  15739. (cond ((null boundaries) nil)
  15740. ((eq extended 'lax) t)
  15741. (t
  15742. (or (and (eq extended 'agenda)
  15743. (or (org-at-planning-p)
  15744. (org-at-property-p)
  15745. (and (bound-and-true-p
  15746. org-agenda-include-inactive-timestamps)
  15747. (org-at-clock-log-p))))
  15748. (eq 'timestamp
  15749. (save-excursion
  15750. (when (= pos (cdr boundaries)) (forward-char -1))
  15751. (org-element-type (org-element-context)))))))))))
  15752. (cond
  15753. ((not match?) nil)
  15754. ((= pos (match-beginning 0)) 'bracket)
  15755. ;; Distinguish location right before the closing bracket from
  15756. ;; right after it.
  15757. ((= pos (1- (match-end 0))) 'bracket)
  15758. ((= pos (match-end 0)) 'after)
  15759. ((org-pos-in-match-range pos 2) 'year)
  15760. ((org-pos-in-match-range pos 3) 'month)
  15761. ((org-pos-in-match-range pos 7) 'hour)
  15762. ((org-pos-in-match-range pos 8) 'minute)
  15763. ((or (org-pos-in-match-range pos 4)
  15764. (org-pos-in-match-range pos 5)) 'day)
  15765. ((and (> pos (or (match-end 8) (match-end 5)))
  15766. (< pos (match-end 0)))
  15767. (- pos (or (match-end 8) (match-end 5))))
  15768. (t 'day))))
  15769. (defun org-toggle-timestamp-type ()
  15770. "Toggle the type (<active> or [inactive]) of a time stamp."
  15771. (interactive)
  15772. (when (org-at-timestamp-p 'lax)
  15773. (let ((beg (match-beginning 0)) (end (match-end 0))
  15774. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15775. (save-excursion
  15776. (goto-char beg)
  15777. (while (re-search-forward "[][<>]" end t)
  15778. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15779. t t)))
  15780. (message "Timestamp is now %sactive"
  15781. (if (equal (char-after beg) ?<) "" "in")))))
  15782. (defun org-at-clock-log-p ()
  15783. "Non-nil if point is on a clock log line."
  15784. (and (org-match-line org-clock-line-re)
  15785. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15786. (defvar org-clock-history) ; defined in org-clock.el
  15787. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15788. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15789. "Change the date in the time stamp at point.
  15790. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15791. `year', `minute', `second'. If WHAT is not given, the cursor position
  15792. in the timestamp determines what will be changed.
  15793. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15794. (let ((origin (point))
  15795. (timestamp? (org-at-timestamp-p 'lax))
  15796. origin-cat
  15797. with-hm inactive
  15798. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15799. extra rem
  15800. ts time time0 fixnext clrgx)
  15801. (unless timestamp? (user-error "Not at a timestamp"))
  15802. (if (and (not what) (eq timestamp? 'bracket))
  15803. (org-toggle-timestamp-type)
  15804. ;; Point isn't on brackets. Remember the part of the time-stamp
  15805. ;; the point was in. Indeed, size of time-stamps may change,
  15806. ;; but point must be kept in the same category nonetheless.
  15807. (setq origin-cat timestamp?)
  15808. (when (and (not what) (not (eq timestamp? 'day))
  15809. org-display-custom-times
  15810. (get-text-property (point) 'display)
  15811. (not (get-text-property (1- (point)) 'display)))
  15812. (setq timestamp? 'day))
  15813. (setq timestamp? (or what timestamp?)
  15814. inactive (= (char-after (match-beginning 0)) ?\[)
  15815. ts (match-string 0))
  15816. (replace-match "")
  15817. (when (string-match
  15818. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15819. ts)
  15820. (setq extra (match-string 1 ts))
  15821. (when suppress-tmp-delay
  15822. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15823. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15824. (setq with-hm t))
  15825. (setq time0 (org-parse-time-string ts))
  15826. (when (and updown
  15827. (eq timestamp? 'minute)
  15828. (not current-prefix-arg))
  15829. ;; This looks like s-up and s-down. Change by one rounding step.
  15830. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15831. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15832. (setcar (cdr time0) (+ (nth 1 time0)
  15833. (if (> n 0) (- rem) (- dm rem))))))
  15834. (setq time
  15835. (apply #'encode-time
  15836. (or (car time0) 0)
  15837. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15838. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15839. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15840. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15841. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15842. (nthcdr 6 time0)))
  15843. (when (and (memq timestamp? '(hour minute))
  15844. extra
  15845. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15846. (setq extra (org-modify-ts-extra
  15847. extra
  15848. (if (eq timestamp? 'hour) 2 5)
  15849. n dm)))
  15850. (when (integerp timestamp?)
  15851. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15852. (when (eq what 'calendar)
  15853. (let ((cal-date (org-get-date-from-calendar)))
  15854. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15855. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15856. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15857. (setcar time0 (or (car time0) 0))
  15858. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15859. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15860. (setq time (apply 'encode-time time0))))
  15861. ;; Insert the new time-stamp, and ensure point stays in the same
  15862. ;; category as before (i.e. not after the last position in that
  15863. ;; category).
  15864. (let ((pos (point)))
  15865. ;; Stay before inserted string. `save-excursion' is of no use.
  15866. (setq org-last-changed-timestamp
  15867. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15868. (goto-char pos))
  15869. (save-match-data
  15870. (looking-at org-ts-regexp3)
  15871. (goto-char
  15872. (pcase origin-cat
  15873. ;; `day' category ends before `hour' if any, or at the end
  15874. ;; of the day name.
  15875. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15876. (`hour (min (match-end 7) origin))
  15877. (`minute (min (1- (match-end 8)) origin))
  15878. ((pred integerp) (min (1- (match-end 0)) origin))
  15879. ;; Point was right after the time-stamp. However, the
  15880. ;; time-stamp length might have changed, so refer to
  15881. ;; (match-end 0) instead.
  15882. (`after (match-end 0))
  15883. ;; `year' and `month' have both fixed size: point couldn't
  15884. ;; have moved into another part.
  15885. (_ origin))))
  15886. ;; Update clock if on a CLOCK line.
  15887. (org-clock-update-time-maybe)
  15888. ;; Maybe adjust the closest clock in `org-clock-history'
  15889. (when org-clock-adjust-closest
  15890. (if (not (and (org-at-clock-log-p)
  15891. (< 1 (length (delq nil (mapcar 'marker-position
  15892. org-clock-history))))))
  15893. (message "No clock to adjust")
  15894. (cond ((save-excursion ; fix previous clock?
  15895. (re-search-backward org-ts-regexp0 nil t)
  15896. (looking-back (concat org-clock-string " \\[")
  15897. (line-beginning-position)))
  15898. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15899. ((save-excursion ; fix next clock?
  15900. (re-search-backward org-ts-regexp0 nil t)
  15901. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15902. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15903. (save-window-excursion
  15904. ;; Find closest clock to point, adjust the previous/next one in history
  15905. (let* ((p (save-excursion (org-back-to-heading t)))
  15906. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15907. (clfixnth
  15908. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15909. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15910. (if (not clfixpos)
  15911. (message "No clock to adjust")
  15912. (save-excursion
  15913. (org-goto-marker-or-bmk clfixpos)
  15914. (org-show-subtree)
  15915. (when (re-search-forward clrgx nil t)
  15916. (goto-char (match-beginning 1))
  15917. (let (org-clock-adjust-closest)
  15918. (org-timestamp-change n timestamp? updown))
  15919. (message "Clock adjusted in %s for heading: %s"
  15920. (file-name-nondirectory (buffer-file-name))
  15921. (org-get-heading t t)))))))))
  15922. ;; Try to recenter the calendar window, if any.
  15923. (when (and org-calendar-follow-timestamp-change
  15924. (get-buffer-window "*Calendar*" t)
  15925. (memq timestamp? '(day month year)))
  15926. (org-recenter-calendar (time-to-days time))))))
  15927. (defun org-modify-ts-extra (s pos n dm)
  15928. "Change the different parts of the lead-time and repeat fields in timestamp."
  15929. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15930. ng h m new rem)
  15931. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15932. (cond
  15933. ((or (org-pos-in-match-range pos 2)
  15934. (org-pos-in-match-range pos 3))
  15935. (setq m (string-to-number (match-string 3 s))
  15936. h (string-to-number (match-string 2 s)))
  15937. (if (org-pos-in-match-range pos 2)
  15938. (setq h (+ h n))
  15939. (setq n (* dm (with-no-warnings (signum n))))
  15940. (unless (= 0 (setq rem (% m dm)))
  15941. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15942. (setq m (+ m n)))
  15943. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15944. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15945. (setq h (mod h 24))
  15946. (setq ng 1 new (format "-%02d:%02d" h m)))
  15947. ((org-pos-in-match-range pos 6)
  15948. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15949. ((org-pos-in-match-range pos 5)
  15950. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15951. ((org-pos-in-match-range pos 9)
  15952. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15953. ((org-pos-in-match-range pos 8)
  15954. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15955. (when ng
  15956. (setq s (concat
  15957. (substring s 0 (match-beginning ng))
  15958. new
  15959. (substring s (match-end ng))))))
  15960. s))
  15961. (defun org-recenter-calendar (d)
  15962. "If the calendar is visible, recenter it to date D."
  15963. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15964. (when cwin
  15965. (let ((calendar-move-hook nil))
  15966. (with-selected-window cwin
  15967. (calendar-goto-date
  15968. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15969. (defun org-goto-calendar (&optional arg)
  15970. "Go to the Emacs calendar at the current date.
  15971. If there is a time stamp in the current line, go to that date.
  15972. A prefix ARG can be used to force the current date."
  15973. (interactive "P")
  15974. (let ((calendar-move-hook nil)
  15975. (calendar-view-holidays-initially-flag nil)
  15976. (calendar-view-diary-initially-flag nil)
  15977. diff)
  15978. (when (or (org-at-timestamp-p 'lax)
  15979. (org-match-line (concat ".*" org-ts-regexp)))
  15980. (let ((d1 (time-to-days (current-time)))
  15981. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15982. (setq diff (- d2 d1))))
  15983. (calendar)
  15984. (calendar-goto-today)
  15985. (when (and diff (not arg)) (calendar-forward-day diff))))
  15986. (defun org-get-date-from-calendar ()
  15987. "Return a list (month day year) of date at point in calendar."
  15988. (with-current-buffer "*Calendar*"
  15989. (save-match-data
  15990. (calendar-cursor-to-date))))
  15991. (defun org-date-from-calendar ()
  15992. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15993. If there is already a time stamp at the cursor position, update it."
  15994. (interactive)
  15995. (if (org-at-timestamp-p 'lax)
  15996. (org-timestamp-change 0 'calendar)
  15997. (let ((cal-date (org-get-date-from-calendar)))
  15998. (org-insert-time-stamp
  15999. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16000. (defcustom org-image-actual-width t
  16001. "Should we use the actual width of images when inlining them?
  16002. When set to t, always use the image width.
  16003. When set to a number, use imagemagick (when available) to set
  16004. the image's width to this value.
  16005. When set to a number in a list, try to get the width from any
  16006. #+ATTR.* keyword if it matches a width specification like
  16007. #+ATTR_HTML: :width 300px
  16008. and fall back on that number if none is found.
  16009. When set to nil, try to get the width from an #+ATTR.* keyword
  16010. and fall back on the original width if none is found.
  16011. This requires Emacs >= 24.1, build with imagemagick support."
  16012. :group 'org-appearance
  16013. :version "24.4"
  16014. :package-version '(Org . "8.0")
  16015. :type '(choice
  16016. (const :tag "Use the image width" t)
  16017. (integer :tag "Use a number of pixels")
  16018. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16019. (const :tag "Use #+ATTR* or don't resize" nil)))
  16020. (defcustom org-agenda-inhibit-startup nil
  16021. "Inhibit startup when preparing agenda buffers.
  16022. When this variable is t, the initialization of the Org agenda
  16023. buffers is inhibited: e.g. the visibility state is not set, the
  16024. tables are not re-aligned, etc."
  16025. :type 'boolean
  16026. :version "24.3"
  16027. :group 'org-agenda)
  16028. (defcustom org-agenda-ignore-properties nil
  16029. "Avoid updating text properties when building the agenda.
  16030. Properties are used to prepare buffers for effort estimates,
  16031. appointments, statistics and subtree-local categories.
  16032. If you don't use these in the agenda, you can add them to this
  16033. list and agenda building will be a bit faster.
  16034. The value is a list, with zero or more of the symbols `effort', `appt',
  16035. `stats' or `category'."
  16036. :type '(set :greedy t
  16037. (const effort)
  16038. (const appt)
  16039. (const stats)
  16040. (const category))
  16041. :version "26.1"
  16042. :package-version '(Org . "8.3")
  16043. :group 'org-agenda)
  16044. ;;;; Files
  16045. (defun org-save-all-org-buffers ()
  16046. "Save all Org buffers without user confirmation."
  16047. (interactive)
  16048. (message "Saving all Org buffers...")
  16049. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16050. (when (featurep 'org-id) (org-id-locations-save))
  16051. (message "Saving all Org buffers... done"))
  16052. (defun org-revert-all-org-buffers ()
  16053. "Revert all Org buffers.
  16054. Prompt for confirmation when there are unsaved changes.
  16055. Be sure you know what you are doing before letting this function
  16056. overwrite your changes.
  16057. This function is useful in a setup where one tracks Org files
  16058. with a version control system, to revert on one machine after pulling
  16059. changes from another. I believe the procedure must be like this:
  16060. 1. M-x org-save-all-org-buffers
  16061. 2. Pull changes from the other machine, resolve conflicts
  16062. 3. M-x org-revert-all-org-buffers"
  16063. (interactive)
  16064. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16065. (user-error "Abort"))
  16066. (save-excursion
  16067. (save-window-excursion
  16068. (dolist (b (buffer-list))
  16069. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16070. (with-current-buffer b buffer-file-name))
  16071. (pop-to-buffer-same-window b)
  16072. (revert-buffer t 'no-confirm)))
  16073. (when (and (featurep 'org-id) org-id-track-globally)
  16074. (org-id-locations-load)))))
  16075. ;;;; Agenda files
  16076. ;;;###autoload
  16077. (defun org-switchb (&optional arg)
  16078. "Switch between Org buffers.
  16079. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16080. With `\\[universal-argument] \\[universal-argument]' \
  16081. prefix, restrict available buffers to agenda files."
  16082. (interactive "P")
  16083. (let ((blist (org-buffer-list
  16084. (cond ((equal arg '(4)) 'files)
  16085. ((equal arg '(16)) 'agenda)))))
  16086. (pop-to-buffer-same-window
  16087. (completing-read "Org buffer: "
  16088. (mapcar #'list (mapcar #'buffer-name blist))
  16089. nil t))))
  16090. (defun org-buffer-list (&optional predicate exclude-tmp)
  16091. "Return a list of Org buffers.
  16092. PREDICATE can be `export', `files' or `agenda'.
  16093. export restrict the list to Export buffers.
  16094. files restrict the list to buffers visiting Org files.
  16095. agenda restrict the list to buffers visiting agenda files.
  16096. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16097. (let* ((bfn nil)
  16098. (agenda-files (and (eq predicate 'agenda)
  16099. (mapcar 'file-truename (org-agenda-files t))))
  16100. (filter
  16101. (cond
  16102. ((eq predicate 'files)
  16103. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16104. ((eq predicate 'export)
  16105. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16106. ((eq predicate 'agenda)
  16107. (lambda (b)
  16108. (with-current-buffer b
  16109. (and (derived-mode-p 'org-mode)
  16110. (setq bfn (buffer-file-name b))
  16111. (member (file-truename bfn) agenda-files)))))
  16112. (t (lambda (b) (with-current-buffer b
  16113. (or (derived-mode-p 'org-mode)
  16114. (string-match "\\*Org .*Export"
  16115. (buffer-name b)))))))))
  16116. (delq nil
  16117. (mapcar
  16118. (lambda(b)
  16119. (if (and (funcall filter b)
  16120. (or (not exclude-tmp)
  16121. (not (string-match "tmp" (buffer-name b)))))
  16122. b
  16123. nil))
  16124. (buffer-list)))))
  16125. (defun org-agenda-files (&optional unrestricted archives)
  16126. "Get the list of agenda files.
  16127. Optional UNRESTRICTED means return the full list even if a restriction
  16128. is currently in place.
  16129. When ARCHIVES is t, include all archive files that are really being
  16130. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16131. `org-agenda-archives-mode' is t."
  16132. (let ((files
  16133. (cond
  16134. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16135. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16136. ((listp org-agenda-files) org-agenda-files)
  16137. (t (error "Invalid value of `org-agenda-files'")))))
  16138. (setq files (apply 'append
  16139. (mapcar (lambda (f)
  16140. (if (file-directory-p f)
  16141. (directory-files
  16142. f t org-agenda-file-regexp)
  16143. (list f)))
  16144. files)))
  16145. (when org-agenda-skip-unavailable-files
  16146. (setq files (delq nil
  16147. (mapcar (function
  16148. (lambda (file)
  16149. (and (file-readable-p file) file)))
  16150. files))))
  16151. (when (or (eq archives t)
  16152. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16153. (setq files (org-add-archive-files files)))
  16154. files))
  16155. (defun org-agenda-file-p (&optional file)
  16156. "Return non-nil, if FILE is an agenda file.
  16157. If FILE is omitted, use the file associated with the current
  16158. buffer."
  16159. (let ((fname (or file (buffer-file-name))))
  16160. (and fname
  16161. (member (file-truename fname)
  16162. (mapcar #'file-truename (org-agenda-files t))))))
  16163. (defun org-edit-agenda-file-list ()
  16164. "Edit the list of agenda files.
  16165. Depending on setup, this either uses customize to edit the variable
  16166. `org-agenda-files', or it visits the file that is holding the list. In the
  16167. latter case, the buffer is set up in a way that saving it automatically kills
  16168. the buffer and restores the previous window configuration."
  16169. (interactive)
  16170. (if (stringp org-agenda-files)
  16171. (let ((cw (current-window-configuration)))
  16172. (find-file org-agenda-files)
  16173. (setq-local org-window-configuration cw)
  16174. (add-hook 'after-save-hook
  16175. (lambda ()
  16176. (set-window-configuration
  16177. (prog1 org-window-configuration
  16178. (kill-buffer (current-buffer))))
  16179. (org-install-agenda-files-menu)
  16180. (message "New agenda file list installed"))
  16181. nil 'local)
  16182. (message "%s" (substitute-command-keys
  16183. "Edit list and finish with \\[save-buffer]")))
  16184. (customize-variable 'org-agenda-files)))
  16185. (defun org-store-new-agenda-file-list (list)
  16186. "Set new value for the agenda file list and save it correctly."
  16187. (if (stringp org-agenda-files)
  16188. (let ((fe (org-read-agenda-file-list t)) b u)
  16189. (while (setq b (find-buffer-visiting org-agenda-files))
  16190. (kill-buffer b))
  16191. (with-temp-file org-agenda-files
  16192. (insert
  16193. (mapconcat
  16194. (lambda (f) ;; Keep un-expanded entries.
  16195. (if (setq u (assoc f fe))
  16196. (cdr u)
  16197. f))
  16198. list "\n")
  16199. "\n")))
  16200. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16201. (org-insert-mode-line-in-empty-file nil))
  16202. (setq org-agenda-files list)
  16203. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16204. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16205. "Read the list of agenda files from a file.
  16206. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16207. filenames, used by `org-store-new-agenda-file-list' to write back
  16208. un-expanded file names."
  16209. (when (file-directory-p org-agenda-files)
  16210. (error "`org-agenda-files' cannot be a single directory"))
  16211. (when (stringp org-agenda-files)
  16212. (with-temp-buffer
  16213. (insert-file-contents org-agenda-files)
  16214. (mapcar
  16215. (lambda (f)
  16216. (let ((e (expand-file-name (substitute-in-file-name f)
  16217. org-directory)))
  16218. (if pair-with-expansion
  16219. (cons e f)
  16220. e)))
  16221. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16222. ;;;###autoload
  16223. (defun org-cycle-agenda-files ()
  16224. "Cycle through the files in `org-agenda-files'.
  16225. If the current buffer visits an agenda file, find the next one in the list.
  16226. If the current buffer does not, find the first agenda file."
  16227. (interactive)
  16228. (let* ((fs (or (org-agenda-files t)
  16229. (user-error "No agenda files")))
  16230. (files (copy-sequence fs))
  16231. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16232. file)
  16233. (when tcf
  16234. (while (and (setq file (pop files))
  16235. (not (equal (file-truename file) tcf)))))
  16236. (find-file (car (or files fs)))
  16237. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16238. (defun org-agenda-file-to-front (&optional to-end)
  16239. "Move/add the current file to the top of the agenda file list.
  16240. If the file is not present in the list, it is added to the front. If it is
  16241. present, it is moved there. With optional argument TO-END, add/move to the
  16242. end of the list."
  16243. (interactive "P")
  16244. (let ((org-agenda-skip-unavailable-files nil)
  16245. (file-alist (mapcar (lambda (x)
  16246. (cons (file-truename x) x))
  16247. (org-agenda-files t)))
  16248. (ctf (file-truename
  16249. (or buffer-file-name
  16250. (user-error "Please save the current buffer to a file"))))
  16251. x had)
  16252. (setq x (assoc ctf file-alist) had x)
  16253. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16254. (if to-end
  16255. (setq file-alist (append (delq x file-alist) (list x)))
  16256. (setq file-alist (cons x (delq x file-alist))))
  16257. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16258. (org-install-agenda-files-menu)
  16259. (message "File %s to %s of agenda file list"
  16260. (if had "moved" "added") (if to-end "end" "front"))))
  16261. (defun org-remove-file (&optional file)
  16262. "Remove current file from the list of files in variable `org-agenda-files'.
  16263. These are the files which are being checked for agenda entries.
  16264. Optional argument FILE means use this file instead of the current."
  16265. (interactive)
  16266. (let* ((org-agenda-skip-unavailable-files nil)
  16267. (file (or file buffer-file-name
  16268. (user-error "Current buffer does not visit a file")))
  16269. (true-file (file-truename file))
  16270. (afile (abbreviate-file-name file))
  16271. (files (delq nil (mapcar
  16272. (lambda (x)
  16273. (unless (equal true-file
  16274. (file-truename x))
  16275. x))
  16276. (org-agenda-files t)))))
  16277. (if (not (= (length files) (length (org-agenda-files t))))
  16278. (progn
  16279. (org-store-new-agenda-file-list files)
  16280. (org-install-agenda-files-menu)
  16281. (message "Removed from Org Agenda list: %s" afile))
  16282. (message "File was not in list: %s (not removed)" afile))))
  16283. (defun org-file-menu-entry (file)
  16284. (vector file (list 'find-file file) t))
  16285. (defun org-check-agenda-file (file)
  16286. "Make sure FILE exists. If not, ask user what to do."
  16287. (unless (file-exists-p file)
  16288. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16289. (abbreviate-file-name file))
  16290. (let ((r (downcase (read-char-exclusive))))
  16291. (cond
  16292. ((equal r ?r)
  16293. (org-remove-file file)
  16294. (throw 'nextfile t))
  16295. (t (user-error "Abort"))))))
  16296. (defun org-get-agenda-file-buffer (file)
  16297. "Get an agenda buffer visiting FILE.
  16298. If the buffer needs to be created, add it to the list of buffers
  16299. which might be released later."
  16300. (let ((buf (org-find-base-buffer-visiting file)))
  16301. (if buf
  16302. buf ; just return it
  16303. ;; Make a new buffer and remember it
  16304. (setq buf (find-file-noselect file))
  16305. (when buf (push buf org-agenda-new-buffers))
  16306. buf)))
  16307. (defun org-release-buffers (blist)
  16308. "Release all buffers in list, asking the user for confirmation when needed.
  16309. When a buffer is unmodified, it is just killed. When modified, it is saved
  16310. \(if the user agrees) and then killed."
  16311. (let (file)
  16312. (dolist (buf blist)
  16313. (setq file (buffer-file-name buf))
  16314. (when (and (buffer-modified-p buf)
  16315. file
  16316. (y-or-n-p (format "Save file %s? " file)))
  16317. (with-current-buffer buf (save-buffer)))
  16318. (kill-buffer buf))))
  16319. (defun org-agenda-prepare-buffers (files)
  16320. "Create buffers for all agenda files, protect archived trees and comments."
  16321. (interactive)
  16322. (let ((pa '(:org-archived t))
  16323. (pc '(:org-comment t))
  16324. (pall '(:org-archived t :org-comment t))
  16325. (inhibit-read-only t)
  16326. (org-inhibit-startup org-agenda-inhibit-startup)
  16327. (rea (org-make-tag-string (list org-archive-tag)))
  16328. re pos)
  16329. (setq org-tag-alist-for-agenda nil
  16330. org-tag-groups-alist-for-agenda nil)
  16331. (save-excursion
  16332. (save-restriction
  16333. (dolist (file files)
  16334. (catch 'nextfile
  16335. (if (bufferp file)
  16336. (set-buffer file)
  16337. (org-check-agenda-file file)
  16338. (set-buffer (org-get-agenda-file-buffer file)))
  16339. (widen)
  16340. (org-set-regexps-and-options 'tags-only)
  16341. (setq pos (point))
  16342. (or (memq 'category org-agenda-ignore-properties)
  16343. (org-refresh-category-properties))
  16344. (or (memq 'stats org-agenda-ignore-properties)
  16345. (org-refresh-stats-properties))
  16346. (or (memq 'effort org-agenda-ignore-properties)
  16347. (org-refresh-effort-properties))
  16348. (or (memq 'appt org-agenda-ignore-properties)
  16349. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16350. (setq org-todo-keywords-for-agenda
  16351. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16352. (setq org-done-keywords-for-agenda
  16353. (append org-done-keywords-for-agenda org-done-keywords))
  16354. (setq org-todo-keyword-alist-for-agenda
  16355. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16356. (setq org-tag-alist-for-agenda
  16357. (org--tag-add-to-alist
  16358. org-tag-alist-for-agenda
  16359. org-current-tag-alist))
  16360. ;; Merge current file's tag groups into global
  16361. ;; `org-tag-groups-alist-for-agenda'.
  16362. (when org-group-tags
  16363. (dolist (alist org-tag-groups-alist)
  16364. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16365. (if old
  16366. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16367. (push alist org-tag-groups-alist-for-agenda)))))
  16368. (with-silent-modifications
  16369. (save-excursion
  16370. (remove-text-properties (point-min) (point-max) pall)
  16371. (when org-agenda-skip-archived-trees
  16372. (goto-char (point-min))
  16373. (while (re-search-forward rea nil t)
  16374. (when (org-at-heading-p t)
  16375. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16376. (goto-char (point-min))
  16377. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16378. (while (re-search-forward re nil t)
  16379. (when (save-match-data (org-in-commented-heading-p t))
  16380. (add-text-properties
  16381. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16382. (goto-char pos)))))
  16383. (setq org-todo-keywords-for-agenda
  16384. (org-uniquify org-todo-keywords-for-agenda))
  16385. (setq org-todo-keyword-alist-for-agenda
  16386. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16387. ;;;; CDLaTeX minor mode
  16388. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16389. "Keymap for the minor `org-cdlatex-mode'.")
  16390. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16391. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16392. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16393. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16394. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16395. (defvar org-cdlatex-texmathp-advice-is-done nil
  16396. "Flag remembering if we have applied the advice to texmathp already.")
  16397. (define-minor-mode org-cdlatex-mode
  16398. "Toggle the minor `org-cdlatex-mode'.
  16399. This mode supports entering LaTeX environment and math in LaTeX fragments
  16400. in Org mode.
  16401. \\{org-cdlatex-mode-map}"
  16402. nil " OCDL" nil
  16403. (when org-cdlatex-mode
  16404. (require 'cdlatex)
  16405. (run-hooks 'cdlatex-mode-hook)
  16406. (cdlatex-compute-tables))
  16407. (unless org-cdlatex-texmathp-advice-is-done
  16408. (setq org-cdlatex-texmathp-advice-is-done t)
  16409. (defadvice texmathp (around org-math-always-on activate)
  16410. "Always return t in Org buffers.
  16411. This is because we want to insert math symbols without dollars even outside
  16412. the LaTeX math segments. If Org mode thinks that point is actually inside
  16413. an embedded LaTeX fragment, let `texmathp' do its job.
  16414. `\\[org-cdlatex-mode-map]'"
  16415. (interactive)
  16416. (let (p)
  16417. (cond
  16418. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16419. ((eq this-command 'cdlatex-math-symbol)
  16420. (setq ad-return-value t
  16421. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16422. (t
  16423. (let ((p (org-inside-LaTeX-fragment-p)))
  16424. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16425. (setq ad-return-value t
  16426. texmathp-why '("Org mode embedded math" . 0))
  16427. (when p ad-do-it)))))))))
  16428. (defun turn-on-org-cdlatex ()
  16429. "Unconditionally turn on `org-cdlatex-mode'."
  16430. (org-cdlatex-mode 1))
  16431. (defun org-try-cdlatex-tab ()
  16432. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16433. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16434. - inside a LaTeX fragment, or
  16435. - after the first word in a line, where an abbreviation expansion could
  16436. insert a LaTeX environment."
  16437. (when org-cdlatex-mode
  16438. (cond
  16439. ;; Before any word on the line: No expansion possible.
  16440. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16441. ;; Just after first word on the line: Expand it. Make sure it
  16442. ;; cannot happen on headlines, though.
  16443. ((save-excursion
  16444. (skip-chars-backward "a-zA-Z0-9*")
  16445. (skip-chars-backward " \t")
  16446. (and (bolp) (not (org-at-heading-p))))
  16447. (cdlatex-tab) t)
  16448. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16449. (defun org-cdlatex-underscore-caret (&optional _arg)
  16450. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16451. Revert to the normal definition outside of these fragments."
  16452. (interactive "P")
  16453. (if (org-inside-LaTeX-fragment-p)
  16454. (call-interactively 'cdlatex-sub-superscript)
  16455. (let (org-cdlatex-mode)
  16456. (call-interactively (key-binding (vector last-input-event))))))
  16457. (defun org-cdlatex-math-modify (&optional _arg)
  16458. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16459. Revert to the normal definition outside of these fragments."
  16460. (interactive "P")
  16461. (if (org-inside-LaTeX-fragment-p)
  16462. (call-interactively 'cdlatex-math-modify)
  16463. (let (org-cdlatex-mode)
  16464. (call-interactively (key-binding (vector last-input-event))))))
  16465. (defun org-cdlatex-environment-indent (&optional environment item)
  16466. "Execute `cdlatex-environment' and indent the inserted environment.
  16467. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16468. The inserted environment is indented to current indentation
  16469. unless point is at the beginning of the line, in which the
  16470. environment remains unintended."
  16471. (interactive)
  16472. ;; cdlatex-environment always return nil. Therefore, capture output
  16473. ;; first and determine if an environment was selected.
  16474. (let* ((beg (point-marker))
  16475. (end (copy-marker (point) t))
  16476. (inserted (progn
  16477. (ignore-errors (cdlatex-environment environment item))
  16478. (< beg end)))
  16479. ;; Figure out how many lines to move forward after the
  16480. ;; environment has been inserted.
  16481. (lines (when inserted
  16482. (save-excursion
  16483. (- (cl-loop while (< beg (point))
  16484. with x = 0
  16485. do (forward-line -1)
  16486. (cl-incf x)
  16487. finally return x)
  16488. (if (progn (goto-char beg)
  16489. (and (progn (skip-chars-forward " \t") (eolp))
  16490. (progn (skip-chars-backward " \t") (bolp))))
  16491. 1 0)))))
  16492. (env (org-trim (delete-and-extract-region beg end))))
  16493. (when inserted
  16494. ;; Get indentation of next line unless at column 0.
  16495. (let ((ind (if (bolp) 0
  16496. (save-excursion
  16497. (org-return-indent)
  16498. (prog1 (current-indentation)
  16499. (when (progn (skip-chars-forward " \t") (eolp))
  16500. (delete-region beg (point)))))))
  16501. (bol (progn (skip-chars-backward " \t") (bolp))))
  16502. ;; Insert a newline before environment unless at column zero
  16503. ;; to "escape" the current line. Insert a newline if
  16504. ;; something is one the same line as \end{ENVIRONMENT}.
  16505. (insert
  16506. (concat (unless bol "\n") env
  16507. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16508. (unless (zerop ind)
  16509. (save-excursion
  16510. (goto-char beg)
  16511. (while (< (point) end)
  16512. (unless (eolp) (indent-line-to ind))
  16513. (forward-line))))
  16514. (goto-char beg)
  16515. (forward-line lines)
  16516. (indent-line-to ind)))
  16517. (set-marker beg nil)
  16518. (set-marker end nil)))
  16519. ;;;; LaTeX fragments
  16520. (defun org-inside-LaTeX-fragment-p ()
  16521. "Test if point is inside a LaTeX fragment.
  16522. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16523. sequence appearing also before point.
  16524. Even though the matchers for math are configurable, this function assumes
  16525. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16526. delimiters are skipped when they have been removed by customization.
  16527. The return value is nil, or a cons cell with the delimiter and the
  16528. position of this delimiter.
  16529. This function does a reasonably good job, but can locally be fooled by
  16530. for example currency specifications. For example it will assume being in
  16531. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16532. fragments that are properly closed, but during editing, we have to live
  16533. with the uncertainty caused by missing closing delimiters. This function
  16534. looks only before point, not after."
  16535. (catch 'exit
  16536. (let ((pos (point))
  16537. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16538. (lim (save-excursion (org-backward-paragraph) (point)))
  16539. dd-on str (start 0) m re)
  16540. (goto-char pos)
  16541. (when dodollar
  16542. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16543. re (nth 1 (assoc "$" org-latex-regexps)))
  16544. (while (string-match re str start)
  16545. (cond
  16546. ((= (match-end 0) (length str))
  16547. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16548. ((= (match-end 0) (- (length str) 5))
  16549. (throw 'exit nil))
  16550. (t (setq start (match-end 0))))))
  16551. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16552. (goto-char pos)
  16553. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16554. (and (match-beginning 2) (throw 'exit nil))
  16555. ;; count $$
  16556. (while (re-search-backward "\\$\\$" lim t)
  16557. (setq dd-on (not dd-on)))
  16558. (goto-char pos)
  16559. (when dd-on (cons "$$" m))))))
  16560. (defun org-inside-latex-macro-p ()
  16561. "Is point inside a LaTeX macro or its arguments?"
  16562. (save-match-data
  16563. (org-in-regexp
  16564. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16565. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16566. "Build an overlay between BEG and END using IMAGE file.
  16567. Argument IMAGETYPE is the extension of the displayed image,
  16568. as a string. It defaults to \"png\"."
  16569. (let ((ov (make-overlay beg end))
  16570. (imagetype (or (intern imagetype) 'png)))
  16571. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16572. (overlay-put ov 'evaporate t)
  16573. (overlay-put ov
  16574. 'modification-hooks
  16575. (list (lambda (o _flag _beg _end &optional _l)
  16576. (delete-overlay o))))
  16577. (overlay-put ov
  16578. 'display
  16579. (list 'image :type imagetype :file image :ascent 'center))))
  16580. (defun org--list-latex-overlays (&optional beg end)
  16581. "List all Org LaTeX overlays in current buffer.
  16582. Limit to overlays between BEG and END when those are provided."
  16583. (cl-remove-if-not
  16584. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16585. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16586. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16587. "Remove all overlays with LaTeX fragment images in current buffer.
  16588. When optional arguments BEG and END are non-nil, remove all
  16589. overlays between them instead. Return a non-nil value when some
  16590. overlays were removed, nil otherwise."
  16591. (let ((overlays (org--list-latex-overlays beg end)))
  16592. (mapc #'delete-overlay overlays)
  16593. overlays))
  16594. (defun org-toggle-latex-fragment (&optional arg)
  16595. "Preview the LaTeX fragment at point, or all locally or globally.
  16596. If the cursor is on a LaTeX fragment, create the image and overlay
  16597. it over the source code, if there is none. Remove it otherwise.
  16598. If there is no fragment at point, display all fragments in the
  16599. current section.
  16600. With prefix ARG, preview or clear image for all fragments in the
  16601. current subtree or in the whole buffer when used before the first
  16602. headline. With a prefix ARG `\\[universal-argument] \
  16603. \\[universal-argument]' preview or clear images
  16604. for all fragments in the buffer."
  16605. (interactive "P")
  16606. (when (display-graphic-p)
  16607. (catch 'exit
  16608. (save-excursion
  16609. (let (beg end msg)
  16610. (cond
  16611. ((or (equal arg '(16))
  16612. (and (equal arg '(4))
  16613. (org-with-limited-levels (org-before-first-heading-p))))
  16614. (if (org-remove-latex-fragment-image-overlays)
  16615. (progn (message "LaTeX fragments images removed from buffer")
  16616. (throw 'exit nil))
  16617. (setq msg "Creating images for buffer...")))
  16618. ((equal arg '(4))
  16619. (org-with-limited-levels (org-back-to-heading t))
  16620. (setq beg (point))
  16621. (setq end (progn (org-end-of-subtree t) (point)))
  16622. (if (org-remove-latex-fragment-image-overlays beg end)
  16623. (progn
  16624. (message "LaTeX fragment images removed from subtree")
  16625. (throw 'exit nil))
  16626. (setq msg "Creating images for subtree...")))
  16627. ((let ((datum (org-element-context)))
  16628. (when (memq (org-element-type datum)
  16629. '(latex-environment latex-fragment))
  16630. (setq beg (org-element-property :begin datum))
  16631. (setq end (org-element-property :end datum))
  16632. (if (org-remove-latex-fragment-image-overlays beg end)
  16633. (progn (message "LaTeX fragment image removed")
  16634. (throw 'exit nil))
  16635. (setq msg "Creating image...")))))
  16636. (t
  16637. (org-with-limited-levels
  16638. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16639. (outline-previous-heading)
  16640. (point)))
  16641. (setq end (progn (outline-next-heading) (point)))
  16642. (if (org-remove-latex-fragment-image-overlays beg end)
  16643. (progn
  16644. (message "LaTeX fragment images removed from section")
  16645. (throw 'exit nil))
  16646. (setq msg "Creating images for section...")))))
  16647. (let ((file (buffer-file-name (buffer-base-buffer))))
  16648. (org-format-latex
  16649. (concat org-preview-latex-image-directory "org-ltximg")
  16650. beg end
  16651. ;; Emacs cannot overlay images from remote hosts. Create
  16652. ;; it in `temporary-file-directory' instead.
  16653. (if (or (not file) (file-remote-p file))
  16654. temporary-file-directory
  16655. default-directory)
  16656. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16657. (message (concat msg "done")))))))
  16658. (defun org-format-latex
  16659. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16660. "Replace LaTeX fragments with links to an image.
  16661. The function takes care of creating the replacement image.
  16662. Only consider fragments between BEG and END when those are
  16663. provided.
  16664. When optional argument OVERLAYS is non-nil, display the image on
  16665. top of the fragment instead of replacing it.
  16666. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16667. Some of the options can be changed using the variable
  16668. `org-format-latex-options', which see."
  16669. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16670. (unless (eq processing-type 'verbatim)
  16671. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16672. (cnt 0)
  16673. checkdir-flag)
  16674. (goto-char (or beg (point-min)))
  16675. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16676. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16677. (overlay-recenter (or end (point-max))))
  16678. (while (re-search-forward math-regexp end t)
  16679. (unless (and overlays
  16680. (eq (get-char-property (point) 'org-overlay-type)
  16681. 'org-latex-overlay))
  16682. (let* ((context (org-element-context))
  16683. (type (org-element-type context)))
  16684. (when (memq type '(latex-environment latex-fragment))
  16685. (let ((block-type (eq type 'latex-environment))
  16686. (value (org-element-property :value context))
  16687. (beg (org-element-property :begin context))
  16688. (end (save-excursion
  16689. (goto-char (org-element-property :end context))
  16690. (skip-chars-backward " \r\t\n")
  16691. (point))))
  16692. (cond
  16693. ((eq processing-type 'mathjax)
  16694. ;; Prepare for MathJax processing.
  16695. (if (not (string-match "\\`\\$\\$?" value))
  16696. (goto-char end)
  16697. (delete-region beg end)
  16698. (if (string= (match-string 0 value) "$$")
  16699. (insert "\\[" (substring value 2 -2) "\\]")
  16700. (insert "\\(" (substring value 1 -1) "\\)"))))
  16701. ((assq processing-type org-preview-latex-process-alist)
  16702. ;; Process to an image.
  16703. (cl-incf cnt)
  16704. (goto-char beg)
  16705. (let* ((processing-info
  16706. (cdr (assq processing-type org-preview-latex-process-alist)))
  16707. (face (face-at-point))
  16708. ;; Get the colors from the face at point.
  16709. (fg
  16710. (let ((color (plist-get org-format-latex-options
  16711. :foreground)))
  16712. (if (and forbuffer (eq color 'auto))
  16713. (face-attribute face :foreground nil 'default)
  16714. color)))
  16715. (bg
  16716. (let ((color (plist-get org-format-latex-options
  16717. :background)))
  16718. (if (and forbuffer (eq color 'auto))
  16719. (face-attribute face :background nil 'default)
  16720. color)))
  16721. (hash (sha1 (prin1-to-string
  16722. (list org-format-latex-header
  16723. org-latex-default-packages-alist
  16724. org-latex-packages-alist
  16725. org-format-latex-options
  16726. forbuffer value fg bg))))
  16727. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16728. (absprefix (expand-file-name prefix dir))
  16729. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16730. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16731. (sep (and block-type "\n\n"))
  16732. (link (concat sep "[[file:" linkfile "]]" sep))
  16733. (options
  16734. (org-combine-plists
  16735. org-format-latex-options
  16736. `(:foreground ,fg :background ,bg))))
  16737. (when msg (message msg cnt))
  16738. (unless checkdir-flag ; Ensure the directory exists.
  16739. (setq checkdir-flag t)
  16740. (let ((todir (file-name-directory absprefix)))
  16741. (unless (file-directory-p todir)
  16742. (make-directory todir t))))
  16743. (unless (file-exists-p movefile)
  16744. (org-create-formula-image
  16745. value movefile options forbuffer processing-type))
  16746. (if overlays
  16747. (progn
  16748. (dolist (o (overlays-in beg end))
  16749. (when (eq (overlay-get o 'org-overlay-type)
  16750. 'org-latex-overlay)
  16751. (delete-overlay o)))
  16752. (org--format-latex-make-overlay beg end movefile imagetype)
  16753. (goto-char end))
  16754. (delete-region beg end)
  16755. (insert
  16756. (org-add-props link
  16757. (list 'org-latex-src
  16758. (replace-regexp-in-string "\"" "" value)
  16759. 'org-latex-src-embed-type
  16760. (if block-type 'paragraph 'character)))))))
  16761. ((eq processing-type 'mathml)
  16762. ;; Process to MathML.
  16763. (unless (org-format-latex-mathml-available-p)
  16764. (user-error "LaTeX to MathML converter not configured"))
  16765. (cl-incf cnt)
  16766. (when msg (message msg cnt))
  16767. (goto-char beg)
  16768. (delete-region beg end)
  16769. (insert (org-format-latex-as-mathml
  16770. value block-type prefix dir)))
  16771. (t
  16772. (error "Unknown conversion process %s for LaTeX fragments"
  16773. processing-type)))))))))))
  16774. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16775. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16776. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16777. sucessful, return the portion between \"<math...> </math>\"
  16778. elements otherwise return nil. When MATHML-FILE is specified,
  16779. write the results in to that file. When invoked as an
  16780. interactive command, prompt for LATEX-FRAG, with initial value
  16781. set to the current active region and echo the results for user
  16782. inspection."
  16783. (interactive (list (let ((frag (when (org-region-active-p)
  16784. (buffer-substring-no-properties
  16785. (region-beginning) (region-end)))))
  16786. (read-string "LaTeX Fragment: " frag nil frag))))
  16787. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16788. (let* ((tmp-in-file
  16789. (let ((file (file-relative-name
  16790. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16791. (write-region latex-frag nil file)
  16792. file))
  16793. (tmp-out-file (file-relative-name
  16794. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16795. (cmd (format-spec
  16796. org-latex-to-mathml-convert-command
  16797. `((?j . ,(and org-latex-to-mathml-jar-file
  16798. (shell-quote-argument
  16799. (expand-file-name
  16800. org-latex-to-mathml-jar-file))))
  16801. (?I . ,(shell-quote-argument tmp-in-file))
  16802. (?i . ,latex-frag)
  16803. (?o . ,(shell-quote-argument tmp-out-file)))))
  16804. mathml shell-command-output)
  16805. (when (called-interactively-p 'any)
  16806. (unless (org-format-latex-mathml-available-p)
  16807. (user-error "LaTeX to MathML converter not configured")))
  16808. (message "Running %s" cmd)
  16809. (setq shell-command-output (shell-command-to-string cmd))
  16810. (setq mathml
  16811. (when (file-readable-p tmp-out-file)
  16812. (with-current-buffer (find-file-noselect tmp-out-file t)
  16813. (goto-char (point-min))
  16814. (when (re-search-forward
  16815. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16816. (regexp-quote
  16817. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16818. nil t)
  16819. (prog1 (match-string 0) (kill-buffer))))))
  16820. (cond
  16821. (mathml
  16822. (setq mathml
  16823. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16824. (when mathml-file
  16825. (write-region mathml nil mathml-file))
  16826. (when (called-interactively-p 'any)
  16827. (message mathml)))
  16828. ((message "LaTeX to MathML conversion failed")
  16829. (message shell-command-output)))
  16830. (delete-file tmp-in-file)
  16831. (when (file-exists-p tmp-out-file)
  16832. (delete-file tmp-out-file))
  16833. mathml))
  16834. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16835. prefix &optional dir)
  16836. "Use `org-create-math-formula' but check local cache first."
  16837. (let* ((absprefix (expand-file-name prefix dir))
  16838. (print-length nil) (print-level nil)
  16839. (formula-id (concat
  16840. "formula-"
  16841. (sha1
  16842. (prin1-to-string
  16843. (list latex-frag
  16844. org-latex-to-mathml-convert-command)))))
  16845. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16846. (formula-cache-dir (file-name-directory formula-cache)))
  16847. (unless (file-directory-p formula-cache-dir)
  16848. (make-directory formula-cache-dir t))
  16849. (unless (file-exists-p formula-cache)
  16850. (org-create-math-formula latex-frag formula-cache))
  16851. (if (file-exists-p formula-cache)
  16852. ;; Successful conversion. Return the link to MathML file.
  16853. (org-add-props
  16854. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16855. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16856. 'org-latex-src-embed-type (if latex-frag-type
  16857. 'paragraph 'character)))
  16858. ;; Failed conversion. Return the LaTeX fragment verbatim
  16859. latex-frag)))
  16860. (defun org--get-display-dpi ()
  16861. "Get the DPI of the display.
  16862. The function assumes that the display has the same pixel width in
  16863. the horizontal and vertical directions."
  16864. (if (display-graphic-p)
  16865. (round (/ (display-pixel-height)
  16866. (/ (display-mm-height) 25.4)))
  16867. (error "Attempt to calculate the dpi of a non-graphic display")))
  16868. (defun org-create-formula-image
  16869. (string tofile options buffer &optional processing-type)
  16870. "Create an image from LaTeX source using external processes.
  16871. The LaTeX STRING is saved to a temporary LaTeX file, then
  16872. converted to an image file by process PROCESSING-TYPE defined in
  16873. `org-preview-latex-process-alist'. A nil value defaults to
  16874. `org-preview-latex-default-process'.
  16875. The generated image file is eventually moved to TOFILE.
  16876. The OPTIONS argument controls the size, foreground color and
  16877. background color of the generated image.
  16878. When BUFFER non-nil, this function is used for LaTeX previewing.
  16879. Otherwise, it is used to deal with LaTeX snippets showed in
  16880. a HTML file."
  16881. (let* ((processing-type (or processing-type
  16882. org-preview-latex-default-process))
  16883. (processing-info
  16884. (cdr (assq processing-type org-preview-latex-process-alist)))
  16885. (programs (plist-get processing-info :programs))
  16886. (error-message (or (plist-get processing-info :message) ""))
  16887. (use-xcolor (plist-get processing-info :use-xcolor))
  16888. (image-input-type (plist-get processing-info :image-input-type))
  16889. (image-output-type (plist-get processing-info :image-output-type))
  16890. (post-clean (or (plist-get processing-info :post-clean)
  16891. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16892. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16893. (latex-header
  16894. (or (plist-get processing-info :latex-header)
  16895. (org-latex-make-preamble
  16896. (org-export-get-environment (org-export-get-backend 'latex))
  16897. org-format-latex-header
  16898. 'snippet)))
  16899. (latex-compiler (plist-get processing-info :latex-compiler))
  16900. (image-converter (plist-get processing-info :image-converter))
  16901. (tmpdir temporary-file-directory)
  16902. (texfilebase (make-temp-name
  16903. (expand-file-name "orgtex" tmpdir)))
  16904. (texfile (concat texfilebase ".tex"))
  16905. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16906. '(1.0 . 1.0)))
  16907. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16908. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16909. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16910. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16911. "Black"))
  16912. (bg (or (plist-get options (if buffer :background :html-background))
  16913. "Transparent"))
  16914. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16915. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16916. (dolist (program programs)
  16917. (org-check-external-command program error-message))
  16918. (if use-xcolor
  16919. (progn (if (eq fg 'default)
  16920. (setq fg (org-latex-color :foreground))
  16921. (setq fg (org-latex-color-format fg)))
  16922. (if (eq bg 'default)
  16923. (setq bg (org-latex-color :background))
  16924. (setq bg (org-latex-color-format
  16925. (if (string= bg "Transparent") "white" bg))))
  16926. (with-temp-file texfile
  16927. (insert latex-header)
  16928. (insert "\n\\begin{document}\n"
  16929. "\\definecolor{fg}{rgb}{" fg "}\n"
  16930. "\\definecolor{bg}{rgb}{" bg "}\n"
  16931. "\n\\pagecolor{bg}\n"
  16932. "\n{\\color{fg}\n"
  16933. string
  16934. "\n}\n"
  16935. "\n\\end{document}\n")))
  16936. (if (eq fg 'default)
  16937. (setq fg (org-dvipng-color :foreground))
  16938. (unless (string= fg "Transparent")
  16939. (setq fg (org-dvipng-color-format fg))))
  16940. (if (eq bg 'default)
  16941. (setq bg (org-dvipng-color :background))
  16942. (unless (string= bg "Transparent")
  16943. (setq bg (org-dvipng-color-format bg))))
  16944. (with-temp-file texfile
  16945. (insert latex-header)
  16946. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16947. (let* ((err-msg (format "Please adjust `%s' part of \
  16948. `org-preview-latex-process-alist'."
  16949. processing-type))
  16950. (image-input-file
  16951. (org-compile-file
  16952. texfile latex-compiler image-input-type err-msg log-buf))
  16953. (image-output-file
  16954. (org-compile-file
  16955. image-input-file image-converter image-output-type err-msg log-buf
  16956. `((?F . ,(shell-quote-argument fg))
  16957. (?B . ,(shell-quote-argument bg))
  16958. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16959. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16960. (copy-file image-output-file tofile 'replace)
  16961. (dolist (e post-clean)
  16962. (when (file-exists-p (concat texfilebase e))
  16963. (delete-file (concat texfilebase e))))
  16964. image-output-file)))
  16965. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16966. "Fill a LaTeX header template TPL.
  16967. In the template, the following place holders will be recognized:
  16968. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16969. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16970. [PACKAGES] \\usepackage statements for PKG
  16971. [NO-PACKAGES] do not include PKG
  16972. [EXTRA] the string EXTRA
  16973. [NO-EXTRA] do not include EXTRA
  16974. For backward compatibility, if both the positive and the negative place
  16975. holder is missing, the positive one (without the \"NO-\") will be
  16976. assumed to be present at the end of the template.
  16977. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16978. EXTRA is a string.
  16979. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16980. (let (rpl (end ""))
  16981. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16982. (setq rpl (if (or (match-end 1) (not def-pkg))
  16983. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16984. tpl (replace-match rpl t t tpl))
  16985. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16986. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16987. (setq rpl (if (or (match-end 1) (not pkg))
  16988. "" (org-latex-packages-to-string pkg snippets-p t))
  16989. tpl (replace-match rpl t t tpl))
  16990. (when pkg (setq end
  16991. (concat end "\n"
  16992. (org-latex-packages-to-string pkg snippets-p)))))
  16993. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16994. (setq rpl (if (or (match-end 1) (not extra))
  16995. "" (concat extra "\n"))
  16996. tpl (replace-match rpl t t tpl))
  16997. (when (and extra (string-match "\\S-" extra))
  16998. (setq end (concat end "\n" extra))))
  16999. (if (string-match "\\S-" end)
  17000. (concat tpl "\n" end)
  17001. tpl)))
  17002. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17003. "Turn an alist of packages into a string with the \\usepackage macros."
  17004. (setq pkg (mapconcat (lambda(p)
  17005. (cond
  17006. ((stringp p) p)
  17007. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17008. (format "%% Package %s omitted" (cadr p)))
  17009. ((equal "" (car p))
  17010. (format "\\usepackage{%s}" (cadr p)))
  17011. (t
  17012. (format "\\usepackage[%s]{%s}"
  17013. (car p) (cadr p)))))
  17014. pkg
  17015. "\n"))
  17016. (if newline (concat pkg "\n") pkg))
  17017. (defun org-dvipng-color (attr)
  17018. "Return a RGB color specification for dvipng."
  17019. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17020. (defun org-dvipng-color-format (color-name)
  17021. "Convert COLOR-NAME to a RGB color value for dvipng."
  17022. (apply #'format "rgb %s %s %s"
  17023. (mapcar 'org-normalize-color
  17024. (color-values color-name))))
  17025. (defun org-latex-color (attr)
  17026. "Return a RGB color for the LaTeX color package."
  17027. (org-latex-color-format (face-attribute 'default attr nil)))
  17028. (defun org-latex-color-format (color-name)
  17029. "Convert COLOR-NAME to a RGB color value."
  17030. (apply #'format "%s,%s,%s"
  17031. (mapcar 'org-normalize-color
  17032. (color-values color-name))))
  17033. (defun org-normalize-color (value)
  17034. "Return string to be used as color value for an RGB component."
  17035. (format "%g" (/ value 65535.0)))
  17036. ;; Image display
  17037. (defvar-local org-inline-image-overlays nil)
  17038. (defun org-toggle-inline-images (&optional include-linked)
  17039. "Toggle the display of inline images.
  17040. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17041. (interactive "P")
  17042. (if org-inline-image-overlays
  17043. (progn
  17044. (org-remove-inline-images)
  17045. (when (called-interactively-p 'interactive)
  17046. (message "Inline image display turned off")))
  17047. (org-display-inline-images include-linked)
  17048. (when (called-interactively-p 'interactive)
  17049. (message (if org-inline-image-overlays
  17050. (format "%d images displayed inline"
  17051. (length org-inline-image-overlays))
  17052. "No images to display inline")))))
  17053. (defun org-redisplay-inline-images ()
  17054. "Refresh the display of inline images."
  17055. (interactive)
  17056. (if (not org-inline-image-overlays)
  17057. (org-toggle-inline-images)
  17058. (org-toggle-inline-images)
  17059. (org-toggle-inline-images)))
  17060. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17061. "Display inline images.
  17062. An inline image is a link which follows either of these
  17063. conventions:
  17064. 1. Its path is a file with an extension matching return value
  17065. from `image-file-name-regexp' and it has no contents.
  17066. 2. Its description consists in a single link of the previous
  17067. type.
  17068. When optional argument INCLUDE-LINKED is non-nil, also links with
  17069. a text description part will be inlined. This can be nice for
  17070. a quick look at those images, but it does not reflect what
  17071. exported files will look like.
  17072. When optional argument REFRESH is non-nil, refresh existing
  17073. images between BEG and END. This will create new image displays
  17074. only if necessary. BEG and END default to the buffer
  17075. boundaries."
  17076. (interactive "P")
  17077. (when (display-graphic-p)
  17078. (unless refresh
  17079. (org-remove-inline-images)
  17080. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17081. (org-with-wide-buffer
  17082. (goto-char (or beg (point-min)))
  17083. (let* ((case-fold-search t)
  17084. (file-extension-re (image-file-name-regexp))
  17085. (link-abbrevs (mapcar #'car
  17086. (append org-link-abbrev-alist-local
  17087. org-link-abbrev-alist)))
  17088. ;; Check absolute, relative file names and explicit
  17089. ;; "file:" links. Also check link abbreviations since
  17090. ;; some might expand to "file" links.
  17091. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17092. (if (not link-abbrevs) ""
  17093. (format "\\|\\(?:%s:\\)"
  17094. (regexp-opt link-abbrevs))))))
  17095. (while (re-search-forward file-types-re end t)
  17096. (let ((link (save-match-data (org-element-context))))
  17097. ;; Check if we're at an inline image, i.e., an image file
  17098. ;; link without a description (unless INCLUDE-LINKED is
  17099. ;; non-nil).
  17100. (when (and (equal "file" (org-element-property :type link))
  17101. (or include-linked
  17102. (null (org-element-contents link)))
  17103. (string-match-p file-extension-re
  17104. (org-element-property :path link)))
  17105. (let ((file (expand-file-name
  17106. (org-link-unescape
  17107. (org-element-property :path link)))))
  17108. (when (file-exists-p file)
  17109. (let ((width
  17110. ;; Apply `org-image-actual-width' specifications.
  17111. (cond
  17112. ((not (image-type-available-p 'imagemagick)) nil)
  17113. ((eq org-image-actual-width t) nil)
  17114. ((listp org-image-actual-width)
  17115. (or
  17116. ;; First try to find a width among
  17117. ;; attributes associated to the paragraph
  17118. ;; containing link.
  17119. (let ((paragraph
  17120. (let ((e link))
  17121. (while (and (setq e (org-element-property
  17122. :parent e))
  17123. (not (eq (org-element-type e)
  17124. 'paragraph))))
  17125. e)))
  17126. (when paragraph
  17127. (save-excursion
  17128. (goto-char (org-element-property :begin paragraph))
  17129. (when
  17130. (re-search-forward
  17131. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17132. (org-element-property
  17133. :post-affiliated paragraph)
  17134. t)
  17135. (string-to-number (match-string 1))))))
  17136. ;; Otherwise, fall-back to provided number.
  17137. (car org-image-actual-width)))
  17138. ((numberp org-image-actual-width)
  17139. org-image-actual-width)))
  17140. (old (get-char-property-and-overlay
  17141. (org-element-property :begin link)
  17142. 'org-image-overlay)))
  17143. (if (and (car-safe old) refresh)
  17144. (image-refresh (overlay-get (cdr old) 'display))
  17145. (let ((image (create-image file
  17146. (and width 'imagemagick)
  17147. nil
  17148. :width width)))
  17149. (when image
  17150. (let ((ov (make-overlay
  17151. (org-element-property :begin link)
  17152. (progn
  17153. (goto-char
  17154. (org-element-property :end link))
  17155. (skip-chars-backward " \t")
  17156. (point)))))
  17157. (overlay-put ov 'display image)
  17158. (overlay-put ov 'face 'default)
  17159. (overlay-put ov 'org-image-overlay t)
  17160. (overlay-put
  17161. ov 'modification-hooks
  17162. (list 'org-display-inline-remove-overlay))
  17163. (push ov org-inline-image-overlays)))))))))))))))
  17164. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17165. "Remove inline-display overlay if a corresponding region is modified."
  17166. (let ((inhibit-modification-hooks t))
  17167. (when (and ov after)
  17168. (delete ov org-inline-image-overlays)
  17169. (delete-overlay ov))))
  17170. (defun org-remove-inline-images ()
  17171. "Remove inline display of images."
  17172. (interactive)
  17173. (mapc #'delete-overlay org-inline-image-overlays)
  17174. (setq org-inline-image-overlays nil))
  17175. ;;; Key bindings
  17176. (defun org-remap (map &rest commands)
  17177. "In MAP, remap the functions given in COMMANDS.
  17178. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17179. (let (new old)
  17180. (while commands
  17181. (setq old (pop commands) new (pop commands))
  17182. (org-defkey map (vector 'remap old) new))))
  17183. ;;;; Outline functions that can be remapped in Org
  17184. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17185. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17186. (define-key org-mode-map [remap outline-forward-same-level]
  17187. #'org-forward-heading-same-level)
  17188. (define-key org-mode-map [remap outline-backward-same-level]
  17189. #'org-backward-heading-same-level)
  17190. (define-key org-mode-map [remap outline-show-branches]
  17191. #'org-kill-note-or-show-branches)
  17192. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17193. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17194. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17195. (define-key org-mode-map [remap outline-next-visible-heading]
  17196. #'org-next-visible-heading)
  17197. (define-key org-mode-map [remap outline-previous-visible-heading]
  17198. #'org-previous-visible-heading)
  17199. (define-key org-mode-map [remap show-children] #'org-show-children)
  17200. ;;;; Make `C-c C-x' a prefix key
  17201. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17202. ;;;; TAB key with modifiers
  17203. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17204. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17205. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17206. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17207. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17208. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17209. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17210. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17211. ;;;; RET key with modifiers
  17212. (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
  17213. (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
  17214. (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
  17215. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17216. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17217. ;;;; Cursor keys with modifiers
  17218. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17219. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17220. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17221. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17222. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17223. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17224. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17225. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17226. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17227. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17228. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17229. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17230. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17231. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17232. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17233. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17234. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17235. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17236. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17237. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17238. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17239. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17240. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17241. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17242. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17243. ;;;; Babel keys
  17244. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17245. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17246. (define-key org-babel-map key def))
  17247. ;;;; Extra keys for TTY access.
  17248. ;; We only set them when really needed because otherwise the
  17249. ;; menus don't show the simple keys
  17250. (when (or org-use-extra-keys (not window-system))
  17251. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17252. (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
  17253. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17254. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17255. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17256. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17257. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17258. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17259. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17260. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17261. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17262. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17263. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17264. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17265. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17266. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17267. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17268. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17269. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17270. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17271. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17272. ;;;; Narrow map
  17273. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17274. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17275. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17276. ;;;; Remap usual Emacs bindings
  17277. (org-remap org-mode-map
  17278. 'self-insert-command 'org-self-insert-command
  17279. 'delete-char 'org-delete-char
  17280. 'delete-backward-char 'org-delete-backward-char
  17281. 'kill-line 'org-kill-line
  17282. 'open-line 'org-open-line
  17283. 'yank 'org-yank
  17284. 'comment-dwim 'org-comment-dwim
  17285. 'move-beginning-of-line 'org-beginning-of-line
  17286. 'move-end-of-line 'org-end-of-line
  17287. 'forward-paragraph 'org-forward-paragraph
  17288. 'backward-paragraph 'org-backward-paragraph
  17289. 'backward-sentence 'org-backward-sentence
  17290. 'forward-sentence 'org-forward-sentence
  17291. 'fill-paragraph 'org-fill-paragraph
  17292. 'delete-indentation 'org-delete-indentation
  17293. 'transpose-words 'org-transpose-words)
  17294. ;;;; All the other keys
  17295. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17296. (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
  17297. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17298. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17299. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17300. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17301. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17302. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17303. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17304. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17305. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17306. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17307. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17308. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17309. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17310. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17311. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17312. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17313. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17314. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17315. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17316. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17317. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17318. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17319. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17320. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17321. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17322. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17323. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17324. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17325. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17326. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17327. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17328. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17329. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17330. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17331. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17332. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17333. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17334. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17335. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17336. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17337. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17338. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17339. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17340. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17341. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17342. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17343. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17344. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17345. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17346. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17347. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17348. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17349. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17350. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17351. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17352. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17353. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17354. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17355. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17356. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17357. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17358. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17359. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17360. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17361. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17362. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17363. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17364. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17365. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17366. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17367. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17368. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17369. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17370. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17371. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17372. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17373. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17374. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17375. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17376. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17377. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17378. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17379. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17380. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17381. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17382. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17383. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17384. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17385. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17386. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17387. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17388. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17389. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17390. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17391. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17392. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17393. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17394. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17395. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17396. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17397. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17398. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17399. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17400. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17401. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17402. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17403. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17404. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17405. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17406. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17407. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17408. (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
  17409. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17410. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17411. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17412. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17413. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17414. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17415. (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17416. (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
  17417. (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17418. (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17419. (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17420. ;;; Speed commands
  17421. (defconst org-speed-commands-default
  17422. '(
  17423. ("Outline Navigation")
  17424. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17425. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17426. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17427. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17428. ("F" . org-next-block)
  17429. ("B" . org-previous-block)
  17430. ("u" . (org-speed-move-safe 'outline-up-heading))
  17431. ("j" . org-goto)
  17432. ("g" . (org-refile t))
  17433. ("Outline Visibility")
  17434. ("c" . org-cycle)
  17435. ("C" . org-shifttab)
  17436. (" " . org-display-outline-path)
  17437. ("s" . org-toggle-narrow-to-subtree)
  17438. ("k" . org-cut-subtree)
  17439. ("=" . org-columns)
  17440. ("Outline Structure Editing")
  17441. ("U" . org-metaup)
  17442. ("D" . org-metadown)
  17443. ("r" . org-metaright)
  17444. ("l" . org-metaleft)
  17445. ("R" . org-shiftmetaright)
  17446. ("L" . org-shiftmetaleft)
  17447. ("i" . (progn (forward-char 1) (call-interactively
  17448. 'org-insert-heading-respect-content)))
  17449. ("^" . org-sort)
  17450. ("w" . org-refile)
  17451. ("a" . org-archive-subtree-default-with-confirmation)
  17452. ("@" . org-mark-subtree)
  17453. ("#" . org-toggle-comment)
  17454. ("Clock Commands")
  17455. ("I" . org-clock-in)
  17456. ("O" . org-clock-out)
  17457. ("Meta Data Editing")
  17458. ("t" . org-todo)
  17459. ("," . (org-priority))
  17460. ("0" . (org-priority ?\ ))
  17461. ("1" . (org-priority ?A))
  17462. ("2" . (org-priority ?B))
  17463. ("3" . (org-priority ?C))
  17464. (":" . org-set-tags-command)
  17465. ("e" . org-set-effort)
  17466. ("E" . org-inc-effort)
  17467. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17468. (org-entry-put (point) "APPT_WARNTIME" m)))
  17469. ("Agenda Views etc")
  17470. ("v" . org-agenda)
  17471. ("/" . org-sparse-tree)
  17472. ("Misc")
  17473. ("o" . org-open-at-point)
  17474. ("?" . org-speed-command-help)
  17475. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17476. (">" . (org-agenda-remove-restriction-lock))
  17477. )
  17478. "The default speed commands.")
  17479. (defun org-print-speed-command (e)
  17480. (if (> (length (car e)) 1)
  17481. (progn
  17482. (princ "\n")
  17483. (princ (car e))
  17484. (princ "\n")
  17485. (princ (make-string (length (car e)) ?-))
  17486. (princ "\n"))
  17487. (princ (car e))
  17488. (princ " ")
  17489. (if (symbolp (cdr e))
  17490. (princ (symbol-name (cdr e)))
  17491. (prin1 (cdr e)))
  17492. (princ "\n")))
  17493. (defun org-speed-command-help ()
  17494. "Show the available speed commands."
  17495. (interactive)
  17496. (if (not org-use-speed-commands)
  17497. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17498. (with-output-to-temp-buffer "*Help*"
  17499. (princ "User-defined Speed commands\n===========================\n")
  17500. (mapc #'org-print-speed-command org-speed-commands-user)
  17501. (princ "\n")
  17502. (princ "Built-in Speed commands\n=======================\n")
  17503. (mapc #'org-print-speed-command org-speed-commands-default))
  17504. (with-current-buffer "*Help*"
  17505. (setq truncate-lines t))))
  17506. (defun org-speed-move-safe (cmd)
  17507. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17508. If not, return to the original position and throw an error."
  17509. (interactive)
  17510. (let ((pos (point)))
  17511. (call-interactively cmd)
  17512. (unless (and (bolp) (org-at-heading-p))
  17513. (goto-char pos)
  17514. (error "Boundary reached while executing %s" cmd))))
  17515. (defvar org-self-insert-command-undo-counter 0)
  17516. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17517. (defvar org-speed-command nil)
  17518. (defun org-speed-command-activate (keys)
  17519. "Hook for activating single-letter speed commands.
  17520. `org-speed-commands-default' specifies a minimal command set.
  17521. Use `org-speed-commands-user' for further customization."
  17522. (when (or (and (bolp) (looking-at org-outline-regexp))
  17523. (and (functionp org-use-speed-commands)
  17524. (funcall org-use-speed-commands)))
  17525. (cdr (assoc keys (append org-speed-commands-user
  17526. org-speed-commands-default)))))
  17527. (defun org-babel-speed-command-activate (keys)
  17528. "Hook for activating single-letter code block commands."
  17529. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17530. (cdr (assoc keys org-babel-key-bindings))))
  17531. (defcustom org-speed-command-hook
  17532. '(org-speed-command-activate org-babel-speed-command-activate)
  17533. "Hook for activating speed commands at strategic locations.
  17534. Hook functions are called in sequence until a valid handler is
  17535. found.
  17536. Each hook takes a single argument, a user-pressed command key
  17537. which is also a `self-insert-command' from the global map.
  17538. Within the hook, examine the cursor position and the command key
  17539. and return nil or a valid handler as appropriate. Handler could
  17540. be one of an interactive command, a function, or a form.
  17541. Set `org-use-speed-commands' to non-nil value to enable this
  17542. hook. The default setting is `org-speed-command-activate'."
  17543. :group 'org-structure
  17544. :version "24.1"
  17545. :type 'hook)
  17546. (defun org-self-insert-command (N)
  17547. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17548. If the cursor is in a table looking at whitespace, the whitespace is
  17549. overwritten, and the table is not marked as requiring realignment."
  17550. (interactive "p")
  17551. (org-check-before-invisible-edit 'insert)
  17552. (cond
  17553. ((and org-use-speed-commands
  17554. (let ((kv (this-command-keys-vector)))
  17555. (setq org-speed-command
  17556. (run-hook-with-args-until-success
  17557. 'org-speed-command-hook
  17558. (make-string 1 (aref kv (1- (length kv))))))))
  17559. (cond
  17560. ((commandp org-speed-command)
  17561. (setq this-command org-speed-command)
  17562. (call-interactively org-speed-command))
  17563. ((functionp org-speed-command)
  17564. (funcall org-speed-command))
  17565. ((and org-speed-command (listp org-speed-command))
  17566. (eval org-speed-command))
  17567. (t (let (org-use-speed-commands)
  17568. (call-interactively 'org-self-insert-command)))))
  17569. ((and
  17570. (= N 1)
  17571. (not (org-region-active-p))
  17572. (org-at-table-p)
  17573. (progn
  17574. ;; Check if we blank the field, and if that triggers align.
  17575. (and (featurep 'org-table)
  17576. org-table-auto-blank-field
  17577. (memq last-command
  17578. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17579. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17580. ;; Got extra space, this field does not determine
  17581. ;; column width.
  17582. (let (org-table-may-need-update) (org-table-blank-field))
  17583. ;; No extra space, this field may determine column
  17584. ;; width.
  17585. (org-table-blank-field)))
  17586. t)
  17587. (looking-at "[^|\n]* |"))
  17588. ;; There is room for insertion without re-aligning the table.
  17589. (self-insert-command N)
  17590. (org-table-with-shrunk-field
  17591. (save-excursion
  17592. (skip-chars-forward "^|")
  17593. ;; Do not delete last space, which is
  17594. ;; `org-table-separator-space', but the regular space before
  17595. ;; it.
  17596. (delete-region (- (point) 2) (1- (point))))))
  17597. (t
  17598. (setq org-table-may-need-update t)
  17599. (self-insert-command N)
  17600. (org-fix-tags-on-the-fly)
  17601. (when org-self-insert-cluster-for-undo
  17602. (if (not (eq last-command 'org-self-insert-command))
  17603. (setq org-self-insert-command-undo-counter 1)
  17604. (if (>= org-self-insert-command-undo-counter 20)
  17605. (setq org-self-insert-command-undo-counter 1)
  17606. (and (> org-self-insert-command-undo-counter 0)
  17607. buffer-undo-list (listp buffer-undo-list)
  17608. (not (cadr buffer-undo-list)) ; remove nil entry
  17609. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17610. (setq org-self-insert-command-undo-counter
  17611. (1+ org-self-insert-command-undo-counter))))))))
  17612. (defun org-check-before-invisible-edit (kind)
  17613. "Check is editing if kind KIND would be dangerous with invisible text around.
  17614. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17615. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17616. (when (and org-catch-invisible-edits
  17617. (or (not (boundp 'visible-mode)) (not visible-mode))
  17618. (or (get-char-property (point) 'invisible)
  17619. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17620. ;; OK, we need to take a closer look. Do not consider
  17621. ;; invisibility obtained through text properties (e.g., link
  17622. ;; fontification), as it cannot be toggled.
  17623. (let* ((invisible-at-point
  17624. (pcase (get-char-property-and-overlay (point) 'invisible)
  17625. (`(,_ . ,(and (pred overlayp) o)) o)))
  17626. ;; Assume that point cannot land in the middle of an
  17627. ;; overlay, or between two overlays.
  17628. (invisible-before-point
  17629. (and (not invisible-at-point)
  17630. (not (bobp))
  17631. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17632. (`(,_ . ,(and (pred overlayp) o)) o))))
  17633. (border-and-ok-direction
  17634. (or
  17635. ;; Check if we are acting predictably before invisible
  17636. ;; text.
  17637. (and invisible-at-point
  17638. (memq kind '(insert delete-backward)))
  17639. ;; Check if we are acting predictably after invisible text
  17640. ;; This works not well, and I have turned it off. It seems
  17641. ;; better to always show and stop after invisible text.
  17642. ;; (and (not invisible-at-point) invisible-before-point
  17643. ;; (memq kind '(insert delete)))
  17644. )))
  17645. (when (or invisible-at-point invisible-before-point)
  17646. (when (eq org-catch-invisible-edits 'error)
  17647. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17648. (if (and org-custom-properties-overlays
  17649. (y-or-n-p "Display invisible properties in this buffer? "))
  17650. (org-toggle-custom-properties-visibility)
  17651. ;; Make the area visible
  17652. (save-excursion
  17653. (when invisible-before-point
  17654. (goto-char
  17655. (previous-single-char-property-change (point) 'invisible)))
  17656. ;; Remove whatever overlay is currently making yet-to-be
  17657. ;; edited text invisible. Also remove nested invisibility
  17658. ;; related overlays.
  17659. (delete-overlay (or invisible-at-point invisible-before-point))
  17660. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17661. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17662. (`(,_ . ,(and (pred overlayp) o))
  17663. (delete-overlay o)
  17664. t)))))
  17665. (cond
  17666. ((eq org-catch-invisible-edits 'show)
  17667. ;; That's it, we do the edit after showing
  17668. (message
  17669. "Unfolding invisible region around point before editing")
  17670. (sit-for 1))
  17671. ((and (eq org-catch-invisible-edits 'smart)
  17672. border-and-ok-direction)
  17673. (message "Unfolding invisible region around point before editing"))
  17674. (t
  17675. ;; Don't do the edit, make the user repeat it in full visibility
  17676. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17677. (defun org-fix-tags-on-the-fly ()
  17678. "Align tags in headline at point.
  17679. Unlike `org-align-tags', this function does nothing if point is
  17680. either not currently on a tagged headline or on a tag."
  17681. (when (and (org-match-line org-tag-line-re)
  17682. (< (point) (match-beginning 1)))
  17683. (org-align-tags)))
  17684. (defun org-delete-backward-char (N)
  17685. "Like `delete-backward-char', insert whitespace at field end in tables.
  17686. When deleting backwards, in tables this function will insert whitespace in
  17687. front of the next \"|\" separator, to keep the table aligned. The table will
  17688. still be marked for re-alignment if the field did fill the entire column,
  17689. because, in this case the deletion might narrow the column."
  17690. (interactive "p")
  17691. (save-match-data
  17692. (org-check-before-invisible-edit 'delete-backward)
  17693. (if (and (= N 1)
  17694. (not overwrite-mode)
  17695. (not (org-region-active-p))
  17696. (not (eq (char-before) ?|))
  17697. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17698. (looking-at-p ".*?|")
  17699. (org-at-table-p))
  17700. (progn (forward-char -1) (org-delete-char 1))
  17701. (backward-delete-char N)
  17702. (org-fix-tags-on-the-fly))))
  17703. (defun org-delete-char (N)
  17704. "Like `delete-char', but insert whitespace at field end in tables.
  17705. When deleting characters, in tables this function will insert whitespace in
  17706. front of the next \"|\" separator, to keep the table aligned. The table will
  17707. still be marked for re-alignment if the field did fill the entire column,
  17708. because, in this case the deletion might narrow the column."
  17709. (interactive "p")
  17710. (save-match-data
  17711. (org-check-before-invisible-edit 'delete)
  17712. (cond
  17713. ((or (/= N 1)
  17714. (eq (char-after) ?|)
  17715. (save-excursion (skip-chars-backward " \t") (bolp))
  17716. (not (org-at-table-p)))
  17717. (delete-char N)
  17718. (org-fix-tags-on-the-fly))
  17719. ((looking-at ".\\(.*?\\)|")
  17720. (let* ((update? org-table-may-need-update)
  17721. (noalign (looking-at-p ".*? |")))
  17722. (delete-char 1)
  17723. (org-table-with-shrunk-field
  17724. (save-excursion
  17725. ;; Last space is `org-table-separator-space', so insert
  17726. ;; a regular one before it instead.
  17727. (goto-char (- (match-end 0) 2))
  17728. (insert " ")))
  17729. ;; If there were two spaces at the end, this field does not
  17730. ;; determine the width of the column.
  17731. (when noalign (setq org-table-may-need-update update?))))
  17732. (t
  17733. (delete-char N)))))
  17734. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17735. (put 'org-self-insert-command 'delete-selection
  17736. (lambda ()
  17737. (not (run-hook-with-args-until-success
  17738. 'self-insert-uses-region-functions))))
  17739. (put 'orgtbl-self-insert-command 'delete-selection
  17740. (lambda ()
  17741. (not (run-hook-with-args-until-success
  17742. 'self-insert-uses-region-functions))))
  17743. (put 'org-delete-char 'delete-selection 'supersede)
  17744. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17745. (put 'org-yank 'delete-selection 'yank)
  17746. ;; Make `flyspell-mode' delay after some commands
  17747. (put 'org-self-insert-command 'flyspell-delayed t)
  17748. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17749. (put 'org-delete-char 'flyspell-delayed t)
  17750. (put 'org-delete-backward-char 'flyspell-delayed t)
  17751. ;; Make pabbrev-mode expand after Org mode commands
  17752. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17753. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17754. (defun org-transpose-words ()
  17755. "Transpose words for Org.
  17756. This uses the `org-mode-transpose-word-syntax-table' syntax
  17757. table, which interprets characters in `org-emphasis-alist' as
  17758. word constituents."
  17759. (interactive)
  17760. (with-syntax-table org-mode-transpose-word-syntax-table
  17761. (call-interactively 'transpose-words)))
  17762. (defvar org-ctrl-c-ctrl-c-hook nil
  17763. "Hook for functions attaching themselves to `C-c C-c'.
  17764. This can be used to add additional functionality to the C-c C-c
  17765. key which executes context-dependent commands. This hook is run
  17766. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17767. run after the last test.
  17768. Each function will be called with no arguments. The function
  17769. must check if the context is appropriate for it to act. If yes,
  17770. it should do its thing and then return a non-nil value. If the
  17771. context is wrong, just do nothing and return nil.")
  17772. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17773. "Hook for functions attaching themselves to `C-c C-c'.
  17774. This can be used to add additional functionality to the C-c C-c
  17775. key which executes context-dependent commands. This hook is run
  17776. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17777. before the first test.
  17778. Each function will be called with no arguments. The function
  17779. must check if the context is appropriate for it to act. If yes,
  17780. it should do its thing and then return a non-nil value. If the
  17781. context is wrong, just do nothing and return nil.")
  17782. (defvar org-tab-first-hook nil
  17783. "Hook for functions to attach themselves to TAB.
  17784. See `org-ctrl-c-ctrl-c-hook' for more information.
  17785. This hook runs as the first action when TAB is pressed, even before
  17786. `org-cycle' messes around with the `outline-regexp' to cater for
  17787. inline tasks and plain list item folding.
  17788. If any function in this hook returns t, any other actions that
  17789. would have been caused by TAB (such as table field motion or visibility
  17790. cycling) will not occur.")
  17791. (defvar org-tab-after-check-for-table-hook nil
  17792. "Hook for functions to attach themselves to TAB.
  17793. See `org-ctrl-c-ctrl-c-hook' for more information.
  17794. This hook runs after it has been established that the cursor is not in a
  17795. table, but before checking if the cursor is in a headline or if global cycling
  17796. should be done.
  17797. If any function in this hook returns t, not other actions like visibility
  17798. cycling will be done.")
  17799. (defvar org-tab-after-check-for-cycling-hook nil
  17800. "Hook for functions to attach themselves to TAB.
  17801. See `org-ctrl-c-ctrl-c-hook' for more information.
  17802. This hook runs after it has been established that not table field motion and
  17803. not visibility should be done because of current context. This is probably
  17804. the place where a package like yasnippets can hook in.")
  17805. (defvar org-tab-before-tab-emulation-hook nil
  17806. "Hook for functions to attach themselves to TAB.
  17807. See `org-ctrl-c-ctrl-c-hook' for more information.
  17808. This hook runs after every other options for TAB have been exhausted, but
  17809. before indentation and \t insertion takes place.")
  17810. (defvar org-metaleft-hook nil
  17811. "Hook for functions attaching themselves to `M-left'.
  17812. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17813. (defvar org-metaright-hook nil
  17814. "Hook for functions attaching themselves to `M-right'.
  17815. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17816. (defvar org-metaup-hook nil
  17817. "Hook for functions attaching themselves to `M-up'.
  17818. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17819. (defvar org-metadown-hook nil
  17820. "Hook for functions attaching themselves to `M-down'.
  17821. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17822. (defvar org-shiftmetaleft-hook nil
  17823. "Hook for functions attaching themselves to `M-S-left'.
  17824. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17825. (defvar org-shiftmetaright-hook nil
  17826. "Hook for functions attaching themselves to `M-S-right'.
  17827. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17828. (defvar org-shiftmetaup-hook nil
  17829. "Hook for functions attaching themselves to `M-S-up'.
  17830. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17831. (defvar org-shiftmetadown-hook nil
  17832. "Hook for functions attaching themselves to `M-S-down'.
  17833. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17834. (defvar org-metareturn-hook nil
  17835. "Hook for functions attaching themselves to `M-RET'.
  17836. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17837. (defvar org-shiftup-hook nil
  17838. "Hook for functions attaching themselves to `S-up'.
  17839. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17840. (defvar org-shiftup-final-hook nil
  17841. "Hook for functions attaching themselves to `S-up'.
  17842. This one runs after all other options except shift-select have been excluded.
  17843. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17844. (defvar org-shiftdown-hook nil
  17845. "Hook for functions attaching themselves to `S-down'.
  17846. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17847. (defvar org-shiftdown-final-hook nil
  17848. "Hook for functions attaching themselves to `S-down'.
  17849. This one runs after all other options except shift-select have been excluded.
  17850. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17851. (defvar org-shiftleft-hook nil
  17852. "Hook for functions attaching themselves to `S-left'.
  17853. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17854. (defvar org-shiftleft-final-hook nil
  17855. "Hook for functions attaching themselves to `S-left'.
  17856. This one runs after all other options except shift-select have been excluded.
  17857. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17858. (defvar org-shiftright-hook nil
  17859. "Hook for functions attaching themselves to `S-right'.
  17860. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17861. (defvar org-shiftright-final-hook nil
  17862. "Hook for functions attaching themselves to `S-right'.
  17863. This one runs after all other options except shift-select have been excluded.
  17864. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17865. (defun org-modifier-cursor-error ()
  17866. "Throw an error, a modified cursor command was applied in wrong context."
  17867. (user-error "This command is active in special context like tables, headlines or items"))
  17868. (defun org-shiftselect-error ()
  17869. "Throw an error because Shift-Cursor command was applied in wrong context."
  17870. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17871. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17872. (user-error "This command works only in special context like headlines or timestamps")))
  17873. (defun org-call-for-shift-select (cmd)
  17874. (let ((this-command-keys-shift-translated t))
  17875. (call-interactively cmd)))
  17876. (defun org-shifttab (&optional arg)
  17877. "Global visibility cycling or move to previous table field.
  17878. Call `org-table-previous-field' within a table.
  17879. When ARG is nil, cycle globally through visibility states.
  17880. When ARG is a numeric prefix, show contents of this level."
  17881. (interactive "P")
  17882. (cond
  17883. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17884. ((integerp arg)
  17885. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17886. (message "Content view to level: %d" arg)
  17887. (org-content (prefix-numeric-value arg2))
  17888. (org-cycle-show-empty-lines t)
  17889. (setq org-cycle-global-status 'overview)))
  17890. (t (call-interactively 'org-global-cycle))))
  17891. (defun org-shiftmetaleft ()
  17892. "Promote subtree or delete table column.
  17893. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17894. `org-table-delete-column', depending on context. See the
  17895. individual commands for more information."
  17896. (interactive)
  17897. (cond
  17898. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17899. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17900. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17901. ((if (not (org-region-active-p)) (org-at-item-p)
  17902. (save-excursion (goto-char (region-beginning))
  17903. (org-at-item-p)))
  17904. (call-interactively 'org-outdent-item-tree))
  17905. (t (org-modifier-cursor-error))))
  17906. (defun org-shiftmetaright ()
  17907. "Demote subtree or insert table column.
  17908. Calls `org-demote-subtree', `org-indent-item-tree', or
  17909. `org-table-insert-column', depending on context. See the
  17910. individual commands for more information."
  17911. (interactive)
  17912. (cond
  17913. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17914. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17915. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17916. ((if (not (org-region-active-p)) (org-at-item-p)
  17917. (save-excursion (goto-char (region-beginning))
  17918. (org-at-item-p)))
  17919. (call-interactively 'org-indent-item-tree))
  17920. (t (org-modifier-cursor-error))))
  17921. (defun org-shiftmetaup (&optional _arg)
  17922. "Drag the line at point up.
  17923. In a table, kill the current row.
  17924. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17925. but also adjust the previous clocked item in the clock history.
  17926. Everywhere else, drag the line at point up."
  17927. (interactive "P")
  17928. (cond
  17929. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17930. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17931. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17932. (call-interactively 'org-timestamp-up)))
  17933. (t (call-interactively 'org-drag-line-backward))))
  17934. (defun org-shiftmetadown (&optional _arg)
  17935. "Drag the line at point down.
  17936. In a table, insert an empty row at the current line.
  17937. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17938. but also adjust the previous clocked item in the clock history.
  17939. Everywhere else, drag the line at point down."
  17940. (interactive "P")
  17941. (cond
  17942. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17943. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17944. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17945. (call-interactively 'org-timestamp-down)))
  17946. (t (call-interactively 'org-drag-line-forward))))
  17947. (defsubst org-hidden-tree-error ()
  17948. (user-error
  17949. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17950. (defun org-metaleft (&optional _arg)
  17951. "Promote heading, list item at point or move table column left.
  17952. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17953. depending on context. With no specific context, calls the Emacs
  17954. default `backward-word'. See the individual commands for more
  17955. information.
  17956. This function runs the hook `org-metaleft-hook' as a first step,
  17957. and returns at first non-nil value."
  17958. (interactive "P")
  17959. (cond
  17960. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17961. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17962. ((org-with-limited-levels
  17963. (or (org-at-heading-p)
  17964. (and (org-region-active-p)
  17965. (save-excursion
  17966. (goto-char (region-beginning))
  17967. (org-at-heading-p)))))
  17968. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17969. (call-interactively 'org-do-promote))
  17970. ;; At an inline task.
  17971. ((org-at-heading-p)
  17972. (call-interactively 'org-inlinetask-promote))
  17973. ((or (org-at-item-p)
  17974. (and (org-region-active-p)
  17975. (save-excursion
  17976. (goto-char (region-beginning))
  17977. (org-at-item-p))))
  17978. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17979. (call-interactively 'org-outdent-item))
  17980. (t (call-interactively 'backward-word))))
  17981. (defun org-metaright (&optional _arg)
  17982. "Demote heading, list item at point or move table column right.
  17983. In front of a drawer or a block keyword, indent it correctly.
  17984. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17985. `org-indent-drawer' or `org-indent-block' depending on context.
  17986. With no specific context, calls the Emacs default `forward-word'.
  17987. See the individual commands for more information.
  17988. This function runs the hook `org-metaright-hook' as a first step,
  17989. and returns at first non-nil value."
  17990. (interactive "P")
  17991. (cond
  17992. ((run-hook-with-args-until-success 'org-metaright-hook))
  17993. ((org-at-table-p) (call-interactively 'org-table-move-column))
  17994. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  17995. ((org-at-block-p) (call-interactively 'org-indent-block))
  17996. ((org-with-limited-levels
  17997. (or (org-at-heading-p)
  17998. (and (org-region-active-p)
  17999. (save-excursion
  18000. (goto-char (region-beginning))
  18001. (org-at-heading-p)))))
  18002. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18003. (call-interactively 'org-do-demote))
  18004. ;; At an inline task.
  18005. ((org-at-heading-p)
  18006. (call-interactively 'org-inlinetask-demote))
  18007. ((or (org-at-item-p)
  18008. (and (org-region-active-p)
  18009. (save-excursion
  18010. (goto-char (region-beginning))
  18011. (org-at-item-p))))
  18012. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18013. (call-interactively 'org-indent-item))
  18014. (t (call-interactively 'forward-word))))
  18015. (defun org-check-for-hidden (what)
  18016. "Check if there are hidden headlines/items in the current visual line.
  18017. WHAT can be either `headlines' or `items'. If the current line is
  18018. an outline or item heading and it has a folded subtree below it,
  18019. this function returns t, nil otherwise."
  18020. (let ((re (cond
  18021. ((eq what 'headlines) org-outline-regexp-bol)
  18022. ((eq what 'items) (org-item-beginning-re))
  18023. (t (error "This should not happen"))))
  18024. beg end)
  18025. (save-excursion
  18026. (catch 'exit
  18027. (unless (org-region-active-p)
  18028. (setq beg (point-at-bol))
  18029. (beginning-of-line 2)
  18030. (while (and (not (eobp)) ;; this is like `next-line'
  18031. (get-char-property (1- (point)) 'invisible))
  18032. (beginning-of-line 2))
  18033. (setq end (point))
  18034. (goto-char beg)
  18035. (goto-char (point-at-eol))
  18036. (setq end (max end (point)))
  18037. (while (re-search-forward re end t)
  18038. (when (get-char-property (match-beginning 0) 'invisible)
  18039. (throw 'exit t))))
  18040. nil))))
  18041. (defun org-metaup (&optional _arg)
  18042. "Move subtree up or move table row up.
  18043. Calls `org-move-subtree-up' or `org-table-move-row' or
  18044. `org-move-item-up', depending on context. See the individual commands
  18045. for more information."
  18046. (interactive "P")
  18047. (cond
  18048. ((run-hook-with-args-until-success 'org-metaup-hook))
  18049. ((org-region-active-p)
  18050. (let* ((a (save-excursion
  18051. (goto-char (min (region-beginning) (region-end)))
  18052. (line-beginning-position)))
  18053. (b (save-excursion
  18054. (goto-char (max (region-beginning) (region-end)))
  18055. (if (bolp) (1- (point)) (line-end-position))))
  18056. (c (save-excursion
  18057. (goto-char a)
  18058. (move-beginning-of-line 0)
  18059. (point)))
  18060. (d (save-excursion
  18061. (goto-char a)
  18062. (move-end-of-line 0)
  18063. (point))))
  18064. (transpose-regions a b c d)
  18065. (goto-char c)))
  18066. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18067. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18068. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18069. (t (org-drag-element-backward))))
  18070. (defun org-metadown (&optional _arg)
  18071. "Move subtree down or move table row down.
  18072. Calls `org-move-subtree-down' or `org-table-move-row' or
  18073. `org-move-item-down', depending on context. See the individual
  18074. commands for more information."
  18075. (interactive "P")
  18076. (cond
  18077. ((run-hook-with-args-until-success 'org-metadown-hook))
  18078. ((org-region-active-p)
  18079. (let* ((a (save-excursion
  18080. (goto-char (min (region-beginning) (region-end)))
  18081. (line-beginning-position)))
  18082. (b (save-excursion
  18083. (goto-char (max (region-beginning) (region-end)))
  18084. (if (bolp) (1- (point)) (line-end-position))))
  18085. (c (save-excursion
  18086. (goto-char b)
  18087. (move-beginning-of-line (if (bolp) 1 2))
  18088. (point)))
  18089. (d (save-excursion
  18090. (goto-char b)
  18091. (move-end-of-line (if (bolp) 1 2))
  18092. (point))))
  18093. (transpose-regions a b c d)
  18094. (goto-char d)))
  18095. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18096. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18097. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18098. (t (org-drag-element-forward))))
  18099. (defun org-shiftup (&optional arg)
  18100. "Increase item in timestamp or increase priority of current headline.
  18101. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18102. depending on context. See the individual commands for more information."
  18103. (interactive "P")
  18104. (cond
  18105. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18106. ((and org-support-shift-select (org-region-active-p))
  18107. (org-call-for-shift-select 'previous-line))
  18108. ((org-at-timestamp-p 'lax)
  18109. (call-interactively (if org-edit-timestamp-down-means-later
  18110. 'org-timestamp-down 'org-timestamp-up)))
  18111. ((and (not (eq org-support-shift-select 'always))
  18112. org-enable-priority-commands
  18113. (org-at-heading-p))
  18114. (call-interactively 'org-priority-up))
  18115. ((and (not org-support-shift-select) (org-at-item-p))
  18116. (call-interactively 'org-previous-item))
  18117. ((org-clocktable-try-shift 'up arg))
  18118. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18119. (org-support-shift-select
  18120. (org-call-for-shift-select 'previous-line))
  18121. (t (org-shiftselect-error))))
  18122. (defun org-shiftdown (&optional arg)
  18123. "Decrease item in timestamp or decrease priority of current headline.
  18124. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18125. depending on context. See the individual commands for more information."
  18126. (interactive "P")
  18127. (cond
  18128. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18129. ((and org-support-shift-select (org-region-active-p))
  18130. (org-call-for-shift-select 'next-line))
  18131. ((org-at-timestamp-p 'lax)
  18132. (call-interactively (if org-edit-timestamp-down-means-later
  18133. 'org-timestamp-up 'org-timestamp-down)))
  18134. ((and (not (eq org-support-shift-select 'always))
  18135. org-enable-priority-commands
  18136. (org-at-heading-p))
  18137. (call-interactively 'org-priority-down))
  18138. ((and (not org-support-shift-select) (org-at-item-p))
  18139. (call-interactively 'org-next-item))
  18140. ((org-clocktable-try-shift 'down arg))
  18141. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18142. (org-support-shift-select
  18143. (org-call-for-shift-select 'next-line))
  18144. (t (org-shiftselect-error))))
  18145. (defun org-shiftright (&optional arg)
  18146. "Cycle the thing at point or in the current line, depending on context.
  18147. Depending on context, this does one of the following:
  18148. - switch a timestamp at point one day into the future
  18149. - on a headline, switch to the next TODO keyword.
  18150. - on an item, switch entire list to the next bullet type
  18151. - on a property line, switch to the next allowed value
  18152. - on a clocktable definition line, move time block into the future"
  18153. (interactive "P")
  18154. (cond
  18155. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18156. ((and org-support-shift-select (org-region-active-p))
  18157. (org-call-for-shift-select 'forward-char))
  18158. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18159. ((and (not (eq org-support-shift-select 'always))
  18160. (org-at-heading-p))
  18161. (let ((org-inhibit-logging
  18162. (not org-treat-S-cursor-todo-selection-as-state-change))
  18163. (org-inhibit-blocking
  18164. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18165. (org-call-with-arg 'org-todo 'right)))
  18166. ((or (and org-support-shift-select
  18167. (not (eq org-support-shift-select 'always))
  18168. (org-at-item-bullet-p))
  18169. (and (not org-support-shift-select) (org-at-item-p)))
  18170. (org-call-with-arg 'org-cycle-list-bullet nil))
  18171. ((and (not (eq org-support-shift-select 'always))
  18172. (org-at-property-p))
  18173. (call-interactively 'org-property-next-allowed-value))
  18174. ((org-clocktable-try-shift 'right arg))
  18175. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18176. (org-support-shift-select
  18177. (org-call-for-shift-select 'forward-char))
  18178. (t (org-shiftselect-error))))
  18179. (defun org-shiftleft (&optional arg)
  18180. "Cycle the thing at point or in the current line, depending on context.
  18181. Depending on context, this does one of the following:
  18182. - switch a timestamp at point one day into the past
  18183. - on a headline, switch to the previous TODO keyword.
  18184. - on an item, switch entire list to the previous bullet type
  18185. - on a property line, switch to the previous allowed value
  18186. - on a clocktable definition line, move time block into the past"
  18187. (interactive "P")
  18188. (cond
  18189. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18190. ((and org-support-shift-select (org-region-active-p))
  18191. (org-call-for-shift-select 'backward-char))
  18192. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18193. ((and (not (eq org-support-shift-select 'always))
  18194. (org-at-heading-p))
  18195. (let ((org-inhibit-logging
  18196. (not org-treat-S-cursor-todo-selection-as-state-change))
  18197. (org-inhibit-blocking
  18198. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18199. (org-call-with-arg 'org-todo 'left)))
  18200. ((or (and org-support-shift-select
  18201. (not (eq org-support-shift-select 'always))
  18202. (org-at-item-bullet-p))
  18203. (and (not org-support-shift-select) (org-at-item-p)))
  18204. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18205. ((and (not (eq org-support-shift-select 'always))
  18206. (org-at-property-p))
  18207. (call-interactively 'org-property-previous-allowed-value))
  18208. ((org-clocktable-try-shift 'left arg))
  18209. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18210. (org-support-shift-select
  18211. (org-call-for-shift-select 'backward-char))
  18212. (t (org-shiftselect-error))))
  18213. (defun org-shiftcontrolright ()
  18214. "Switch to next TODO set."
  18215. (interactive)
  18216. (cond
  18217. ((and org-support-shift-select (org-region-active-p))
  18218. (org-call-for-shift-select 'forward-word))
  18219. ((and (not (eq org-support-shift-select 'always))
  18220. (org-at-heading-p))
  18221. (org-call-with-arg 'org-todo 'nextset))
  18222. (org-support-shift-select
  18223. (org-call-for-shift-select 'forward-word))
  18224. (t (org-shiftselect-error))))
  18225. (defun org-shiftcontrolleft ()
  18226. "Switch to previous TODO set."
  18227. (interactive)
  18228. (cond
  18229. ((and org-support-shift-select (org-region-active-p))
  18230. (org-call-for-shift-select 'backward-word))
  18231. ((and (not (eq org-support-shift-select 'always))
  18232. (org-at-heading-p))
  18233. (org-call-with-arg 'org-todo 'previousset))
  18234. (org-support-shift-select
  18235. (org-call-for-shift-select 'backward-word))
  18236. (t (org-shiftselect-error))))
  18237. (defun org-shiftcontrolup (&optional n)
  18238. "Change timestamps synchronously up in CLOCK log lines.
  18239. Optional argument N tells to change by that many units."
  18240. (interactive "P")
  18241. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18242. (let (org-support-shift-select)
  18243. (org-clock-timestamps-up n))
  18244. (user-error "Not at a clock log")))
  18245. (defun org-shiftcontroldown (&optional n)
  18246. "Change timestamps synchronously down in CLOCK log lines.
  18247. Optional argument N tells to change by that many units."
  18248. (interactive "P")
  18249. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18250. (let (org-support-shift-select)
  18251. (org-clock-timestamps-down n))
  18252. (user-error "Not at a clock log")))
  18253. (defun org-increase-number-at-point (&optional inc)
  18254. "Increment the number at point.
  18255. With an optional prefix numeric argument INC, increment using
  18256. this numeric value."
  18257. (interactive "p")
  18258. (if (not (number-at-point))
  18259. (user-error "Not on a number")
  18260. (unless inc (setq inc 1))
  18261. (let ((pos (point))
  18262. (beg (skip-chars-backward "-+^/*0-9eE."))
  18263. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18264. (setq nap (buffer-substring-no-properties
  18265. (+ pos beg) (+ pos beg end)))
  18266. (delete-region (+ pos beg) (+ pos beg end))
  18267. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18268. (when (org-at-table-p)
  18269. (org-table-align)
  18270. (org-table-end-of-field 1))))
  18271. (defun org-decrease-number-at-point (&optional inc)
  18272. "Decrement the number at point.
  18273. With an optional prefix numeric argument INC, decrement using
  18274. this numeric value."
  18275. (interactive "p")
  18276. (org-increase-number-at-point (- (or inc 1))))
  18277. (defun org-ctrl-c-ret ()
  18278. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18279. (interactive)
  18280. (cond
  18281. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18282. (t (call-interactively 'org-insert-heading))))
  18283. (defun org-find-visible ()
  18284. (let ((s (point)))
  18285. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18286. (get-char-property s 'invisible)))
  18287. s))
  18288. (defun org-find-invisible ()
  18289. (let ((s (point)))
  18290. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18291. (not (get-char-property s 'invisible))))
  18292. s))
  18293. (defun org-copy-visible (beg end)
  18294. "Copy the visible parts of the region."
  18295. (interactive "r")
  18296. (let ((result ""))
  18297. (while (/= beg end)
  18298. (when (get-char-property beg 'invisible)
  18299. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18300. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18301. (setq result (concat result (buffer-substring beg next)))
  18302. (setq beg next)))
  18303. (kill-new result)
  18304. (message "Visible strings have been copied to the kill ring.")))
  18305. (defun org-copy-special ()
  18306. "Copy region in table or copy current subtree.
  18307. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18308. context. See the individual commands for more information."
  18309. (interactive)
  18310. (call-interactively
  18311. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18312. (defun org-cut-special ()
  18313. "Cut region in table or cut current subtree.
  18314. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18315. context. See the individual commands for more information."
  18316. (interactive)
  18317. (call-interactively
  18318. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18319. (defun org-paste-special (arg)
  18320. "Paste rectangular region into table, or past subtree relative to level.
  18321. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18322. See the individual commands for more information."
  18323. (interactive "P")
  18324. (if (org-at-table-p)
  18325. (org-table-paste-rectangle)
  18326. (org-paste-subtree arg)))
  18327. (defun org-edit-special (&optional arg)
  18328. "Call a special editor for the element at point.
  18329. When at a table, call the formula editor with `org-table-edit-formulas'.
  18330. When in a source code block, call `org-edit-src-code'.
  18331. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18332. When in an export block, call `org-edit-export-block'.
  18333. When in a LaTeX environment, call `org-edit-latex-environment'.
  18334. When at an #+INCLUDE keyword, visit the included file.
  18335. When at a footnote reference, call `org-edit-footnote-reference'
  18336. On a link, call `ffap' to visit the link at point.
  18337. Otherwise, return a user error."
  18338. (interactive "P")
  18339. (let ((element (org-element-at-point)))
  18340. (barf-if-buffer-read-only)
  18341. (pcase (org-element-type element)
  18342. (`src-block
  18343. (if (not arg) (org-edit-src-code)
  18344. (let* ((info (org-babel-get-src-block-info))
  18345. (lang (nth 0 info))
  18346. (params (nth 2 info))
  18347. (session (cdr (assq :session params))))
  18348. (if (not session) (org-edit-src-code)
  18349. ;; At a src-block with a session and function called with
  18350. ;; an ARG: switch to the buffer related to the inferior
  18351. ;; process.
  18352. (switch-to-buffer
  18353. (funcall (intern (concat "org-babel-prep-session:" lang))
  18354. session params))))))
  18355. (`keyword
  18356. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18357. (org-open-link-from-string
  18358. (format "[[%s]]"
  18359. (expand-file-name
  18360. (let ((value (org-element-property :value element)))
  18361. (cond ((org-file-url-p value)
  18362. (user-error "The file is specified as a URL, cannot be edited"))
  18363. ((not (org-string-nw-p value))
  18364. (user-error "No file to edit"))
  18365. ((string-match "\\`\"\\(.*?\\)\"" value)
  18366. (match-string 1 value))
  18367. ((string-match "\\`[^ \t\"]\\S-*" value)
  18368. (match-string 0 value))
  18369. (t (user-error "No valid file specified")))))))
  18370. (user-error "No special environment to edit here")))
  18371. (`table
  18372. (if (eq (org-element-property :type element) 'table.el)
  18373. (org-edit-table.el)
  18374. (call-interactively 'org-table-edit-formulas)))
  18375. ;; Only Org tables contain `table-row' type elements.
  18376. (`table-row (call-interactively 'org-table-edit-formulas))
  18377. (`example-block (org-edit-src-code))
  18378. (`export-block (org-edit-export-block))
  18379. (`fixed-width (org-edit-fixed-width-region))
  18380. (`latex-environment (org-edit-latex-environment))
  18381. (_
  18382. ;; No notable element at point. Though, we may be at a link or
  18383. ;; a footnote reference, which are objects. Thus, scan deeper.
  18384. (let ((context (org-element-context element)))
  18385. (pcase (org-element-type context)
  18386. (`footnote-reference (org-edit-footnote-reference))
  18387. (`inline-src-block (org-edit-inline-src-code))
  18388. (`link (call-interactively #'ffap))
  18389. (_ (user-error "No special environment to edit here"))))))))
  18390. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18391. (defun org-ctrl-c-ctrl-c (&optional arg)
  18392. "Set tags in headline, or update according to changed information at point.
  18393. This command does many different things, depending on context:
  18394. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18395. this is what we do.
  18396. - If the cursor is on a statistics cookie, update it.
  18397. - If the cursor is in a headline, prompt for tags and insert them
  18398. into the current line, aligned to `org-tags-column'. When called
  18399. with prefix arg, realign all tags in the current buffer.
  18400. - If the cursor is in one of the special #+KEYWORD lines, this
  18401. triggers scanning the buffer for these lines and updating the
  18402. information.
  18403. - If the cursor is inside a table, realign the table. This command
  18404. works even if the automatic table editor has been turned off.
  18405. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18406. the entire table.
  18407. - If the cursor is at a footnote reference or definition, jump to
  18408. the corresponding definition or references, respectively.
  18409. - If the cursor is a the beginning of a dynamic block, update it.
  18410. - If the current buffer is a capture buffer, close note and file it.
  18411. - If the cursor is on a <<<target>>>, update radio targets and
  18412. corresponding links in this buffer.
  18413. - If the cursor is on a numbered item in a plain list, renumber the
  18414. ordered list.
  18415. - If the cursor is on a checkbox, toggle it.
  18416. - If the cursor is on a code block, evaluate it. The variable
  18417. `org-confirm-babel-evaluate' can be used to control prompting
  18418. before code block evaluation, by default every code block
  18419. evaluation requires confirmation. Code block evaluation can be
  18420. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18421. (interactive "P")
  18422. (cond
  18423. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18424. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18425. (org-remove-occur-highlights)
  18426. (message "Temporary highlights/overlays removed from current buffer"))
  18427. ((and (local-variable-p 'org-finish-function)
  18428. (fboundp org-finish-function))
  18429. (funcall org-finish-function))
  18430. ((org-babel-hash-at-point))
  18431. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18432. (t
  18433. (let* ((context
  18434. (org-element-lineage
  18435. (org-element-context)
  18436. ;; Limit to supported contexts.
  18437. '(babel-call clock dynamic-block footnote-definition
  18438. footnote-reference inline-babel-call inline-src-block
  18439. inlinetask item keyword node-property paragraph
  18440. plain-list planning property-drawer radio-target
  18441. src-block statistics-cookie table table-cell table-row
  18442. timestamp)
  18443. t))
  18444. (type (org-element-type context)))
  18445. ;; For convenience: at the first line of a paragraph on the same
  18446. ;; line as an item, apply function on that item instead.
  18447. (when (eq type 'paragraph)
  18448. (let ((parent (org-element-property :parent context)))
  18449. (when (and (eq (org-element-type parent) 'item)
  18450. (= (line-beginning-position)
  18451. (org-element-property :begin parent)))
  18452. (setq context parent)
  18453. (setq type 'item))))
  18454. ;; Act according to type of element or object at point.
  18455. ;;
  18456. ;; Do nothing on a blank line, except if it is contained in
  18457. ;; a src block. Hence, we first check if point is in such
  18458. ;; a block and then if it is at a blank line.
  18459. (pcase type
  18460. ((or `inline-src-block `src-block)
  18461. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18462. (org-babel-eval-wipe-error-buffer)
  18463. (org-babel-execute-src-block
  18464. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18465. ((guard (org-match-line "[ \t]*$"))
  18466. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18467. (user-error
  18468. (substitute-command-keys
  18469. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18470. ((or `babel-call `inline-babel-call)
  18471. (let ((info (org-babel-lob-get-info context)))
  18472. (when info (org-babel-execute-src-block nil info))))
  18473. (`clock (org-clock-update-time-maybe))
  18474. (`dynamic-block
  18475. (save-excursion
  18476. (goto-char (org-element-property :post-affiliated context))
  18477. (org-update-dblock)))
  18478. (`footnote-definition
  18479. (goto-char (org-element-property :post-affiliated context))
  18480. (call-interactively 'org-footnote-action))
  18481. (`footnote-reference (call-interactively #'org-footnote-action))
  18482. ((or `headline `inlinetask)
  18483. (save-excursion (goto-char (org-element-property :begin context))
  18484. (call-interactively #'org-set-tags-command)))
  18485. (`item
  18486. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18487. ;; unconditionally, whereas `C-u' will toggle its presence.
  18488. ;; Without a universal argument, if the item has a checkbox,
  18489. ;; toggle it. Otherwise repair the list.
  18490. (let* ((box (org-element-property :checkbox context))
  18491. (struct (org-element-property :structure context))
  18492. (old-struct (copy-tree struct))
  18493. (parents (org-list-parents-alist struct))
  18494. (prevs (org-list-prevs-alist struct))
  18495. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18496. (org-list-set-checkbox
  18497. (org-element-property :begin context) struct
  18498. (cond ((equal arg '(16)) "[-]")
  18499. ((and (not box) (equal arg '(4))) "[ ]")
  18500. ((or (not box) (equal arg '(4))) nil)
  18501. ((eq box 'on) "[ ]")
  18502. (t "[X]")))
  18503. ;; Mimic `org-list-write-struct' but with grabbing a return
  18504. ;; value from `org-list-struct-fix-box'.
  18505. (org-list-struct-fix-ind struct parents 2)
  18506. (org-list-struct-fix-item-end struct)
  18507. (org-list-struct-fix-bul struct prevs)
  18508. (org-list-struct-fix-ind struct parents)
  18509. (let ((block-item
  18510. (org-list-struct-fix-box struct parents prevs orderedp)))
  18511. (if (and box (equal struct old-struct))
  18512. (if (equal arg '(16))
  18513. (message "Checkboxes already reset")
  18514. (user-error "Cannot toggle this checkbox: %s"
  18515. (if (eq box 'on)
  18516. "all subitems checked"
  18517. "unchecked subitems")))
  18518. (org-list-struct-apply-struct struct old-struct)
  18519. (org-update-checkbox-count-maybe))
  18520. (when block-item
  18521. (message "Checkboxes were removed due to empty box at line %d"
  18522. (org-current-line block-item))))))
  18523. (`keyword
  18524. (let ((org-inhibit-startup-visibility-stuff t)
  18525. (org-startup-align-all-tables nil))
  18526. (when (boundp 'org-table-coordinate-overlays)
  18527. (mapc #'delete-overlay org-table-coordinate-overlays)
  18528. (setq org-table-coordinate-overlays nil))
  18529. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18530. (message "Local setup has been refreshed"))
  18531. (`plain-list
  18532. ;; At a plain list, with a double C-u argument, set
  18533. ;; checkboxes of each item to "[-]", whereas a single one
  18534. ;; will toggle their presence according to the state of the
  18535. ;; first item in the list. Without an argument, repair the
  18536. ;; list.
  18537. (let* ((begin (org-element-property :contents-begin context))
  18538. (struct (org-element-property :structure context))
  18539. (old-struct (copy-tree struct))
  18540. (first-box (save-excursion
  18541. (goto-char begin)
  18542. (looking-at org-list-full-item-re)
  18543. (match-string-no-properties 3)))
  18544. (new-box (cond ((equal arg '(16)) "[-]")
  18545. ((equal arg '(4)) (unless first-box "[ ]"))
  18546. ((equal first-box "[X]") "[ ]")
  18547. (t "[X]"))))
  18548. (cond
  18549. (arg
  18550. (dolist (pos
  18551. (org-list-get-all-items
  18552. begin struct (org-list-prevs-alist struct)))
  18553. (org-list-set-checkbox pos struct new-box)))
  18554. ((and first-box (eq (point) begin))
  18555. ;; For convenience, when point is at bol on the first
  18556. ;; item of the list and no argument is provided, simply
  18557. ;; toggle checkbox of that item, if any.
  18558. (org-list-set-checkbox begin struct new-box)))
  18559. (when (equal
  18560. (org-list-write-struct
  18561. struct (org-list-parents-alist struct) old-struct)
  18562. old-struct)
  18563. (message "Cannot update this checkbox"))
  18564. (org-update-checkbox-count-maybe)))
  18565. ((or `property-drawer `node-property)
  18566. (call-interactively #'org-property-action))
  18567. (`radio-target
  18568. (call-interactively #'org-update-radio-target-regexp))
  18569. (`statistics-cookie
  18570. (call-interactively #'org-update-statistics-cookies))
  18571. ((or `table `table-cell `table-row)
  18572. ;; At a table, recalculate every field and align it. Also
  18573. ;; send the table if necessary. If the table has
  18574. ;; a `table.el' type, just give up. At a table row or cell,
  18575. ;; maybe recalculate line but always align table.
  18576. (if (eq (org-element-property :type context) 'table.el)
  18577. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18578. Use `\\[org-edit-special]' to edit table.el tables"))
  18579. (if (or (eq type 'table)
  18580. ;; Check if point is at a TBLFM line.
  18581. (and (eq type 'table-row)
  18582. (= (point) (org-element-property :end context))))
  18583. (save-excursion
  18584. (if (org-at-TBLFM-p)
  18585. (progn (require 'org-table)
  18586. (org-table-calc-current-TBLFM))
  18587. (goto-char (org-element-property :contents-begin context))
  18588. (org-call-with-arg 'org-table-recalculate (or arg t))
  18589. (orgtbl-send-table 'maybe)))
  18590. (org-table-maybe-eval-formula)
  18591. (cond (arg (call-interactively #'org-table-recalculate))
  18592. ((org-table-maybe-recalculate-line))
  18593. (t (org-table-align))))))
  18594. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18595. (org-timestamp-change 0 'day))
  18596. ((and `nil (guard (org-at-heading-p)))
  18597. ;; When point is on an unsupported object type, we can miss
  18598. ;; the fact that it also is at a heading. Handle it here.
  18599. (call-interactively #'org-set-tags-command))
  18600. ((guard
  18601. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18602. (_
  18603. (user-error
  18604. (substitute-command-keys
  18605. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18606. (defun org-mode-restart ()
  18607. (interactive)
  18608. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18609. (funcall major-mode)
  18610. (hack-local-variables)
  18611. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18612. (org-indent-mode -1))
  18613. (org-reset-file-cache))
  18614. (message "%s restarted" major-mode))
  18615. (defun org-kill-note-or-show-branches ()
  18616. "Abort storing current note, or call `outline-show-branches'."
  18617. (interactive)
  18618. (if (not org-finish-function)
  18619. (save-excursion
  18620. (save-restriction
  18621. (org-narrow-to-subtree)
  18622. (org-flag-subtree t)
  18623. (call-interactively 'outline-show-branches)
  18624. (org-hide-archived-subtrees (point-min) (point-max))))
  18625. (let ((org-note-abort t))
  18626. (funcall org-finish-function))))
  18627. (defun org-delete-indentation (&optional arg)
  18628. "Join current line to previous and fix whitespace at join.
  18629. If previous line is a headline add to headline title. Otherwise
  18630. the function calls `delete-indentation'.
  18631. With a non-nil optional argument, join it to the following one."
  18632. (interactive "*P")
  18633. (if (save-excursion
  18634. (beginning-of-line (if arg 1 0))
  18635. (let ((case-fold-search nil))
  18636. (looking-at org-complex-heading-regexp)))
  18637. ;; At headline.
  18638. (let ((tags-column (when (match-beginning 5)
  18639. (save-excursion (goto-char (match-beginning 5))
  18640. (current-column))))
  18641. (string (concat " " (progn (when arg (forward-line 1))
  18642. (org-trim (delete-and-extract-region
  18643. (line-beginning-position)
  18644. (line-end-position)))))))
  18645. (unless (bobp) (delete-region (point) (1- (point))))
  18646. (goto-char (or (match-end 4)
  18647. (match-beginning 5)
  18648. (match-end 0)))
  18649. (skip-chars-backward " \t")
  18650. (save-excursion (insert string))
  18651. ;; Adjust alignment of tags.
  18652. (cond
  18653. ((not tags-column)) ;no tags
  18654. (org-auto-align-tags (org-align-tags))
  18655. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18656. (delete-indentation arg)))
  18657. (defun org-open-line (n)
  18658. "Insert a new row in tables, call `open-line' elsewhere.
  18659. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18660. As a special case, when a document starts with a table, allow to
  18661. call `open-line' on the very first character."
  18662. (interactive "*p")
  18663. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18664. (org-table-insert-row)
  18665. (open-line n)))
  18666. (defun org-return (&optional indent)
  18667. "Goto next table row or insert a newline.
  18668. Calls `org-table-next-row' or `newline', depending on context.
  18669. When optional INDENT argument is non-nil, call
  18670. `newline-and-indent' instead of `newline'.
  18671. When `org-return-follows-link' is non-nil and point is on
  18672. a timestamp or a link, call `org-open-at-point'. However, it
  18673. will not happen if point is in a table or on a \"dead\"
  18674. object (e.g., within a comment). In these case, you need to use
  18675. `org-open-at-point' directly."
  18676. (interactive)
  18677. (let ((context (if org-return-follows-link (org-element-context)
  18678. (org-element-at-point))))
  18679. (cond
  18680. ;; In a table, call `org-table-next-row'. However, before first
  18681. ;; column or after last one, split the table.
  18682. ((or (and (eq (org-element-type context) 'table)
  18683. (>= (point) (org-element-property :contents-begin context))
  18684. (< (point) (org-element-property :contents-end context)))
  18685. (org-element-lineage context '(table-row table-cell) t))
  18686. (if (or (looking-at-p "[ \t]*$")
  18687. (save-excursion (skip-chars-backward " \t") (bolp)))
  18688. (insert "\n")
  18689. (org-table-justify-field-maybe)
  18690. (call-interactively #'org-table-next-row)))
  18691. ;; On a link or a timestamp, call `org-open-at-point' if
  18692. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18693. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18694. ((and org-return-follows-link
  18695. (or (and (eq 'link (org-element-type context))
  18696. ;; Ensure point is not on the white spaces after
  18697. ;; the link.
  18698. (let ((origin (point)))
  18699. (org-with-point-at (org-element-property :end context)
  18700. (skip-chars-backward " \t")
  18701. (> (point) origin))))
  18702. (org-in-regexp org-ts-regexp-both nil t)
  18703. (org-in-regexp org-tsr-regexp-both nil t)
  18704. (org-in-regexp org-any-link-re nil t)))
  18705. (call-interactively #'org-open-at-point))
  18706. ;; Insert newline in heading, but preserve tags.
  18707. ((and (not (bolp))
  18708. (save-excursion (beginning-of-line)
  18709. (let ((case-fold-search nil))
  18710. (looking-at org-complex-heading-regexp))))
  18711. ;; At headline. Split line. However, if point is on keyword,
  18712. ;; priority cookie or tags, do not break any of them: add
  18713. ;; a newline after the headline instead.
  18714. (let ((tags-column (and (match-beginning 5)
  18715. (save-excursion (goto-char (match-beginning 5))
  18716. (current-column))))
  18717. (string
  18718. (when (and (match-end 4) (org-point-in-group (point) 4))
  18719. (delete-and-extract-region (point) (match-end 4)))))
  18720. ;; Adjust tag alignment.
  18721. (cond
  18722. ((not (and tags-column string)))
  18723. (org-auto-align-tags (org-align-tags))
  18724. (t (org--align-tags-here tags-column))) ;preserve tags column
  18725. (end-of-line)
  18726. (org-show-entry)
  18727. (if indent (newline-and-indent) (newline))
  18728. (when string (save-excursion (insert (org-trim string))))))
  18729. ;; In a list, make sure indenting keeps trailing text within.
  18730. ((and indent
  18731. (not (eolp))
  18732. (org-element-lineage context '(item)))
  18733. (let ((trailing-data
  18734. (delete-and-extract-region (point) (line-end-position))))
  18735. (newline-and-indent)
  18736. (save-excursion (insert trailing-data))))
  18737. (t
  18738. ;; Do not auto-fill when point is in an Org property drawer.
  18739. (let ((auto-fill-function (and (not (org-at-property-p))
  18740. auto-fill-function)))
  18741. (if indent
  18742. (newline-and-indent)
  18743. (newline)))))))
  18744. (defun org-return-indent ()
  18745. "Goto next table row or insert a newline and indent.
  18746. Calls `org-table-next-row' or `newline-and-indent', depending on
  18747. context. See the individual commands for more information."
  18748. (interactive)
  18749. (org-return t))
  18750. (defun org-ctrl-c-tab (&optional _arg)
  18751. "Toggle columns width in a table, or show children.
  18752. Call `org-table-toggle-column-width' if point is in a table.
  18753. Otherwise, call `org-show-children'."
  18754. (interactive "p")
  18755. (call-interactively
  18756. (if (org-at-table-p) #'org-table-toggle-column-width
  18757. #'org-show-children)))
  18758. (defun org-ctrl-c-star ()
  18759. "Compute table, or change heading status of lines.
  18760. Calls `org-table-recalculate' or `org-toggle-heading',
  18761. depending on context."
  18762. (interactive)
  18763. (cond
  18764. ((org-at-table-p)
  18765. (call-interactively 'org-table-recalculate))
  18766. (t
  18767. ;; Convert all lines in region to list items
  18768. (call-interactively 'org-toggle-heading))))
  18769. (defun org-ctrl-c-minus ()
  18770. "Insert separator line in table or modify bullet status of line.
  18771. Also turns a plain line or a region of lines into list items.
  18772. Calls `org-table-insert-hline', `org-toggle-item', or
  18773. `org-cycle-list-bullet', depending on context."
  18774. (interactive)
  18775. (cond
  18776. ((org-at-table-p)
  18777. (call-interactively 'org-table-insert-hline))
  18778. ((org-region-active-p)
  18779. (call-interactively 'org-toggle-item))
  18780. ((org-in-item-p)
  18781. (call-interactively 'org-cycle-list-bullet))
  18782. (t
  18783. (call-interactively 'org-toggle-item))))
  18784. (defun org-toggle-heading (&optional nstars)
  18785. "Convert headings to normal text, or items or text to headings.
  18786. If there is no active region, only convert the current line.
  18787. With a `\\[universal-argument]' prefix, convert the whole list at
  18788. point into heading.
  18789. In a region:
  18790. - If the first non blank line is a headline, remove the stars
  18791. from all headlines in the region.
  18792. - If it is a normal line, turn each and every normal line (i.e.,
  18793. not an heading or an item) in the region into headings. If you
  18794. want to convert only the first line of this region, use one
  18795. universal prefix argument.
  18796. - If it is a plain list item, turn all plain list items into headings.
  18797. When converting a line into a heading, the number of stars is chosen
  18798. such that the lines become children of the current entry. However,
  18799. when a numeric prefix argument is given, its value determines the
  18800. number of stars to add."
  18801. (interactive "P")
  18802. (let ((skip-blanks
  18803. (function
  18804. ;; Return beginning of first non-blank line, starting from
  18805. ;; line at POS.
  18806. (lambda (pos)
  18807. (save-excursion
  18808. (goto-char pos)
  18809. (while (org-at-comment-p) (forward-line))
  18810. (skip-chars-forward " \r\t\n")
  18811. (point-at-bol)))))
  18812. beg end toggled)
  18813. ;; Determine boundaries of changes. If a universal prefix has
  18814. ;; been given, put the list in a region. If region ends at a bol,
  18815. ;; do not consider the last line to be in the region.
  18816. (when (and current-prefix-arg (org-at-item-p))
  18817. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18818. (org-mark-element))
  18819. (if (org-region-active-p)
  18820. (setq beg (funcall skip-blanks (region-beginning))
  18821. end (copy-marker (save-excursion
  18822. (goto-char (region-end))
  18823. (if (bolp) (point) (point-at-eol)))))
  18824. (setq beg (funcall skip-blanks (point-at-bol))
  18825. end (copy-marker (point-at-eol))))
  18826. ;; Ensure inline tasks don't count as headings.
  18827. (org-with-limited-levels
  18828. (save-excursion
  18829. (goto-char beg)
  18830. (cond
  18831. ;; Case 1. Started at an heading: de-star headings.
  18832. ((org-at-heading-p)
  18833. (while (< (point) end)
  18834. (when (org-at-heading-p t)
  18835. (looking-at org-outline-regexp) (replace-match "")
  18836. (setq toggled t))
  18837. (forward-line)))
  18838. ;; Case 2. Started at an item: change items into headlines.
  18839. ;; One star will be added by `org-list-to-subtree'.
  18840. ((org-at-item-p)
  18841. (while (< (point) end)
  18842. (when (org-at-item-p)
  18843. ;; Pay attention to cases when region ends before list.
  18844. (let* ((struct (org-list-struct))
  18845. (list-end
  18846. (min (org-list-get-bottom-point struct) (1+ end))))
  18847. (save-restriction
  18848. (narrow-to-region (point) list-end)
  18849. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18850. (setq toggled t))
  18851. (forward-line)))
  18852. ;; Case 3. Started at normal text: make every line an heading,
  18853. ;; skipping headlines and items.
  18854. (t (let* ((stars
  18855. (make-string
  18856. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18857. (add-stars
  18858. (cond (nstars "") ; stars from prefix only
  18859. ((equal stars "") "*") ; before first heading
  18860. (org-odd-levels-only "**") ; inside heading, odd
  18861. (t "*"))) ; inside heading, oddeven
  18862. (rpl (concat stars add-stars " "))
  18863. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18864. (while (< (point) (if (equal nstars '(4)) lend end))
  18865. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18866. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18867. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18868. (forward-line)))))))
  18869. (unless toggled (message "Cannot toggle heading from here"))))
  18870. (defun org-meta-return (&optional arg)
  18871. "Insert a new heading or wrap a region in a table.
  18872. Calls `org-insert-heading', `org-insert-item' or
  18873. `org-table-wrap-region', depending on context. When called with
  18874. an argument, unconditionally call `org-insert-heading'."
  18875. (interactive "P")
  18876. (org-check-before-invisible-edit 'insert)
  18877. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18878. (call-interactively (cond (arg #'org-insert-heading)
  18879. ((org-at-table-p) #'org-table-wrap-region)
  18880. ((org-in-item-p) #'org-insert-item)
  18881. (t #'org-insert-heading)))))
  18882. ;;; Menu entries
  18883. (defsubst org-in-subtree-not-table-p ()
  18884. "Are we in a subtree and not in a table?"
  18885. (and (not (org-before-first-heading-p))
  18886. (not (org-at-table-p))))
  18887. ;; Define the Org mode menus
  18888. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18889. '("Tbl"
  18890. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18891. ["Next Field" org-cycle (org-at-table-p)]
  18892. ["Previous Field" org-shifttab (org-at-table-p)]
  18893. ["Next Row" org-return (org-at-table-p)]
  18894. "--"
  18895. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18896. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18897. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18898. "--"
  18899. ("Column"
  18900. ["Move Column Left" org-metaleft (org-at-table-p)]
  18901. ["Move Column Right" org-metaright (org-at-table-p)]
  18902. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18903. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18904. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18905. ("Row"
  18906. ["Move Row Up" org-metaup (org-at-table-p)]
  18907. ["Move Row Down" org-metadown (org-at-table-p)]
  18908. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18909. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18910. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18911. "--"
  18912. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18913. ("Rectangle"
  18914. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18915. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18916. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18917. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18918. "--"
  18919. ("Calculate"
  18920. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18921. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18922. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18923. "--"
  18924. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18925. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18926. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18927. "--"
  18928. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18929. "--"
  18930. ["Sum Column/Rectangle" org-table-sum
  18931. (or (org-at-table-p) (org-region-active-p))]
  18932. ["Which Column?" org-table-current-column (org-at-table-p)])
  18933. ["Debug Formulas"
  18934. org-table-toggle-formula-debugger
  18935. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18936. ["Show Col/Row Numbers"
  18937. org-table-toggle-coordinate-overlays
  18938. :style toggle
  18939. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18940. "--"
  18941. ["Create" org-table-create (not (org-at-table-p))]
  18942. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18943. ["Import from File" org-table-import (not (org-at-table-p))]
  18944. ["Export to File" org-table-export (org-at-table-p)]
  18945. "--"
  18946. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18947. "--"
  18948. ("Plot"
  18949. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18950. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18951. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18952. '("Org"
  18953. ("Show/Hide"
  18954. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18955. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18956. ["Sparse Tree..." org-sparse-tree t]
  18957. ["Reveal Context" org-reveal t]
  18958. ["Show All" org-show-all t]
  18959. "--"
  18960. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18961. "--"
  18962. ["New Heading" org-insert-heading t]
  18963. ("Navigate Headings"
  18964. ["Up" outline-up-heading t]
  18965. ["Next" outline-next-visible-heading t]
  18966. ["Previous" outline-previous-visible-heading t]
  18967. ["Next Same Level" outline-forward-same-level t]
  18968. ["Previous Same Level" outline-backward-same-level t]
  18969. "--"
  18970. ["Jump" org-goto t])
  18971. ("Edit Structure"
  18972. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18973. "--"
  18974. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18975. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18976. "--"
  18977. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18978. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18979. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18980. "--"
  18981. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18982. "--"
  18983. ["Copy visible text" org-copy-visible t]
  18984. "--"
  18985. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18986. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18987. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18988. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18989. "--"
  18990. ["Sort Region/Children" org-sort t]
  18991. "--"
  18992. ["Convert to odd levels" org-convert-to-odd-levels t]
  18993. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18994. ("Editing"
  18995. ["Emphasis..." org-emphasize t]
  18996. ["Edit Source Example" org-edit-special t]
  18997. "--"
  18998. ["Footnote new/jump" org-footnote-action t]
  18999. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19000. ("Archive"
  19001. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19002. "--"
  19003. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19004. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19005. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19006. )
  19007. "--"
  19008. ("Hyperlinks"
  19009. ["Store Link (Global)" org-store-link t]
  19010. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19011. ["Insert Link" org-insert-link t]
  19012. ["Follow Link" org-open-at-point t]
  19013. "--"
  19014. ["Next link" org-next-link t]
  19015. ["Previous link" org-previous-link t]
  19016. "--"
  19017. ["Descriptive Links"
  19018. org-toggle-link-display
  19019. :style radio
  19020. :selected org-descriptive-links
  19021. ]
  19022. ["Literal Links"
  19023. org-toggle-link-display
  19024. :style radio
  19025. :selected (not org-descriptive-links)])
  19026. "--"
  19027. ("TODO Lists"
  19028. ["TODO/DONE/-" org-todo t]
  19029. ("Select keyword"
  19030. ["Next keyword" org-shiftright (org-at-heading-p)]
  19031. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19032. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19033. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19034. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19035. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19036. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19037. "--"
  19038. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19039. :selected org-enforce-todo-dependencies :style toggle :active t]
  19040. "Settings for tree at point"
  19041. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19042. :selected (org-entry-get nil "ORDERED")
  19043. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19044. ["Do Children parallel" org-toggle-ordered-property :style radio
  19045. :selected (not (org-entry-get nil "ORDERED"))
  19046. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19047. "--"
  19048. ["Set Priority" org-priority t]
  19049. ["Priority Up" org-shiftup t]
  19050. ["Priority Down" org-shiftdown t]
  19051. "--"
  19052. ["Get news from all feeds" org-feed-update-all t]
  19053. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19054. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19055. ("TAGS and Properties"
  19056. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19057. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19058. "--"
  19059. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19060. ["Column view of properties" org-columns t]
  19061. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19062. ("Dates and Scheduling"
  19063. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19064. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19065. ("Change Date"
  19066. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19067. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19068. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19069. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19070. ["Compute Time Range" org-evaluate-time-range t]
  19071. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19072. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19073. "--"
  19074. ["Custom time format" org-toggle-time-stamp-overlays
  19075. :style radio :selected org-display-custom-times]
  19076. "--"
  19077. ["Goto Calendar" org-goto-calendar t]
  19078. ["Date from Calendar" org-date-from-calendar t]
  19079. "--"
  19080. ["Start/Restart Timer" org-timer-start t]
  19081. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19082. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19083. ["Insert Timer String" org-timer t]
  19084. ["Insert Timer Item" org-timer-item t])
  19085. ("Logging work"
  19086. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19087. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19088. ["Clock out" org-clock-out t]
  19089. ["Clock cancel" org-clock-cancel t]
  19090. "--"
  19091. ["Mark as default task" org-clock-mark-default-task t]
  19092. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19093. ["Goto running clock" org-clock-goto t]
  19094. "--"
  19095. ["Display times" org-clock-display t]
  19096. ["Create clock table" org-clock-report t]
  19097. "--"
  19098. ["Record DONE time"
  19099. (progn (setq org-log-done (not org-log-done))
  19100. (message "Switching to %s will %s record a timestamp"
  19101. (car org-done-keywords)
  19102. (if org-log-done "automatically" "not")))
  19103. :style toggle :selected org-log-done])
  19104. "--"
  19105. ["Agenda Command..." org-agenda t]
  19106. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19107. ("File List for Agenda")
  19108. ("Special views current file"
  19109. ["TODO Tree" org-show-todo-tree t]
  19110. ["Check Deadlines" org-check-deadlines t]
  19111. ["Tags/Property tree" org-match-sparse-tree t])
  19112. "--"
  19113. ["Export/Publish..." org-export-dispatch t]
  19114. ("LaTeX"
  19115. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19116. :style toggle :selected org-cdlatex-mode]
  19117. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19118. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19119. ["Modify math symbol" org-cdlatex-math-modify
  19120. (org-inside-LaTeX-fragment-p)]
  19121. ["Insert citation" org-reftex-citation t])
  19122. "--"
  19123. ("MobileOrg"
  19124. ["Push Files and Views" org-mobile-push t]
  19125. ["Get Captured and Flagged" org-mobile-pull t]
  19126. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19127. "--"
  19128. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19129. "--"
  19130. ("Documentation"
  19131. ["Show Version" org-version t]
  19132. ["Info Documentation" org-info t]
  19133. ["Browse Org News" org-browse-news t])
  19134. ("Customize"
  19135. ["Browse Org Group" org-customize t]
  19136. "--"
  19137. ["Expand This Menu" org-create-customize-menu
  19138. (fboundp 'customize-menu-create)])
  19139. ["Send bug report" org-submit-bug-report t]
  19140. "--"
  19141. ("Refresh/Reload"
  19142. ["Refresh setup current buffer" org-mode-restart t]
  19143. ["Reload Org (after update)" org-reload t]
  19144. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  19145. (defun org-info (&optional node)
  19146. "Read documentation for Org in the info system.
  19147. With optional NODE, go directly to that node."
  19148. (interactive)
  19149. (info (format "(org)%s" (or node ""))))
  19150. (defun org-browse-news ()
  19151. "Browse the news for the latest major release."
  19152. (interactive)
  19153. (browse-url "https://orgmode.org/Changes.html"))
  19154. ;;;###autoload
  19155. (defun org-submit-bug-report ()
  19156. "Submit a bug report on Org via mail.
  19157. Don't hesitate to report any problems or inaccurate documentation.
  19158. If you don't have setup sending mail from (X)Emacs, please copy the
  19159. output buffer into your mail program, as it gives us important
  19160. information about your Org version and configuration."
  19161. (interactive)
  19162. (require 'reporter)
  19163. (defvar reporter-prompt-for-summary-p)
  19164. (org-load-modules-maybe)
  19165. (org-require-autoloaded-modules)
  19166. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19167. (reporter-submit-bug-report
  19168. "emacs-orgmode@gnu.org"
  19169. (org-version nil 'full)
  19170. (let (list)
  19171. (save-window-excursion
  19172. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19173. (delete-other-windows)
  19174. (erase-buffer)
  19175. (insert "You are about to submit a bug report to the Org mailing list.
  19176. We would like to add your full Org and Outline configuration to the
  19177. bug report. This greatly simplifies the work of the maintainer and
  19178. other experts on the mailing list.
  19179. HOWEVER, some variables you have customized may contain private
  19180. information. The names of customers, colleagues, or friends, might
  19181. appear in the form of file names, tags, todo states, or search strings.
  19182. If you answer yes to the prompt, you might want to check and remove
  19183. such private information before sending the email.")
  19184. (add-text-properties (point-min) (point-max) '(face org-warning))
  19185. (when (yes-or-no-p "Include your Org configuration ")
  19186. (mapatoms
  19187. (lambda (v)
  19188. (and (boundp v)
  19189. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19190. (or (and (symbol-value v)
  19191. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19192. (and
  19193. (get v 'custom-type) (get v 'standard-value)
  19194. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19195. (push v list)))))
  19196. (kill-buffer (get-buffer "*Warn about privacy*"))
  19197. list))
  19198. nil nil
  19199. "Remember to cover the basics, that is, what you expected to happen and
  19200. what in fact did happen. You don't know how to make a good report? See
  19201. https://orgmode.org/manual/Feedback.html#Feedback
  19202. Your bug report will be posted to the Org mailing list.
  19203. ------------------------------------------------------------------------")
  19204. (save-excursion
  19205. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19206. (replace-match "\\1Bug: \\3 [\\2]")))))
  19207. (defun org-install-agenda-files-menu ()
  19208. (let ((bl (buffer-list)))
  19209. (save-excursion
  19210. (while bl
  19211. (set-buffer (pop bl))
  19212. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19213. (when (derived-mode-p 'org-mode)
  19214. (easy-menu-change
  19215. '("Org") "File List for Agenda"
  19216. (append
  19217. (list
  19218. ["Edit File List" (org-edit-agenda-file-list) t]
  19219. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19220. ["Remove Current File from List" org-remove-file t]
  19221. ["Cycle through agenda files" org-cycle-agenda-files t]
  19222. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19223. "--")
  19224. (mapcar 'org-file-menu-entry
  19225. ;; Prevent initialization from failing.
  19226. (ignore-errors (org-agenda-files t)))))))))
  19227. ;;;; Documentation
  19228. (defun org-require-autoloaded-modules ()
  19229. (interactive)
  19230. (mapc #'require
  19231. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19232. org-table org-timer)))
  19233. ;;;###autoload
  19234. (defun org-reload (&optional uncompiled)
  19235. "Reload all Org Lisp files.
  19236. With prefix arg UNCOMPILED, load the uncompiled versions."
  19237. (interactive "P")
  19238. (require 'loadhist)
  19239. (let* ((org-dir (org-find-library-dir "org"))
  19240. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19241. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19242. (remove-re (format "\\`%s\\'"
  19243. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19244. (feats (delete-dups
  19245. (mapcar 'file-name-sans-extension
  19246. (mapcar 'file-name-nondirectory
  19247. (delq nil
  19248. (mapcar 'feature-file
  19249. features))))))
  19250. (lfeat (append
  19251. (sort
  19252. (setq feats
  19253. (delq nil (mapcar
  19254. (lambda (f)
  19255. (if (and (string-match feature-re f)
  19256. (not (string-match remove-re f)))
  19257. f nil))
  19258. feats)))
  19259. 'string-lessp)
  19260. (list "org-version" "org")))
  19261. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19262. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19263. load-uncore load-misses)
  19264. (setq load-misses
  19265. (delq 't
  19266. (mapcar (lambda (f)
  19267. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19268. (and (string= org-dir contrib-dir)
  19269. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19270. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19271. (add-to-list 'load-uncore f 'append)
  19272. 't)
  19273. f))
  19274. lfeat)))
  19275. (when load-uncore
  19276. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19277. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19278. (if load-misses
  19279. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19280. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19281. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19282. ;;;###autoload
  19283. (defun org-customize ()
  19284. "Call the customize function with org as argument."
  19285. (interactive)
  19286. (org-load-modules-maybe)
  19287. (org-require-autoloaded-modules)
  19288. (customize-browse 'org))
  19289. (defun org-create-customize-menu ()
  19290. "Create a full customization menu for Org mode, insert it into the menu."
  19291. (interactive)
  19292. (org-load-modules-maybe)
  19293. (org-require-autoloaded-modules)
  19294. (if (fboundp 'customize-menu-create)
  19295. (progn
  19296. (easy-menu-change
  19297. '("Org") "Customize"
  19298. `(["Browse Org group" org-customize t]
  19299. "--"
  19300. ,(customize-menu-create 'org)
  19301. ["Set" Custom-set t]
  19302. ["Save" Custom-save t]
  19303. ["Reset to Current" Custom-reset-current t]
  19304. ["Reset to Saved" Custom-reset-saved t]
  19305. ["Reset to Standard Settings" Custom-reset-standard t]))
  19306. (message "\"Org\"-menu now contains full customization menu"))
  19307. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19308. ;;;; Miscellaneous stuff
  19309. ;;; Generally useful functions
  19310. (defun org-link-display-format (s)
  19311. "Replace links in string S with their description.
  19312. If there is no description, use the link target."
  19313. (save-match-data
  19314. (replace-regexp-in-string
  19315. org-bracket-link-analytic-regexp
  19316. (lambda (m)
  19317. (if (match-end 5) (match-string 5 m)
  19318. (concat (match-string 1 m) (match-string 3 m))))
  19319. s nil t)))
  19320. (defun org-toggle-link-display ()
  19321. "Toggle the literal or descriptive display of links."
  19322. (interactive)
  19323. (if org-descriptive-links
  19324. (remove-from-invisibility-spec '(org-link))
  19325. (add-to-invisibility-spec '(org-link)))
  19326. (org-restart-font-lock)
  19327. (setq org-descriptive-links (not org-descriptive-links)))
  19328. (defun org-in-clocktable-p ()
  19329. "Check if the cursor is in a clocktable."
  19330. (let ((pos (point)) start)
  19331. (save-excursion
  19332. (end-of-line 1)
  19333. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19334. (setq start (match-beginning 0))
  19335. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19336. (>= (match-end 0) pos)
  19337. start))))
  19338. (defun org-in-verbatim-emphasis ()
  19339. (save-match-data
  19340. (and (org-in-regexp org-verbatim-re 2)
  19341. (>= (point) (match-beginning 3))
  19342. (<= (point) (match-end 4)))))
  19343. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19344. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19345. (if (and marker (marker-buffer marker)
  19346. (buffer-live-p (marker-buffer marker)))
  19347. (progn
  19348. (pop-to-buffer-same-window (marker-buffer marker))
  19349. (when (or (> marker (point-max)) (< marker (point-min)))
  19350. (widen))
  19351. (goto-char marker)
  19352. (org-show-context 'org-goto))
  19353. (if bookmark
  19354. (bookmark-jump bookmark)
  19355. (error "Cannot find location"))))
  19356. (defun org-quote-csv-field (s)
  19357. "Quote field for inclusion in CSV material."
  19358. (if (string-match "[\",]" s)
  19359. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19360. s))
  19361. (defun org-force-self-insert (N)
  19362. "Needed to enforce self-insert under remapping."
  19363. (interactive "p")
  19364. (self-insert-command N))
  19365. (defun org-fill-template (template alist)
  19366. "Find each %key of ALIST in TEMPLATE and replace it."
  19367. (let ((case-fold-search nil))
  19368. (dolist (entry (sort (copy-sequence alist)
  19369. (lambda (a b) (< (length (car a)) (length (car b))))))
  19370. (setq template
  19371. (replace-regexp-in-string
  19372. (concat "%" (regexp-quote (car entry)))
  19373. (or (cdr entry) "") template t t)))
  19374. template))
  19375. (defun org-quote-vert (s)
  19376. "Replace \"|\" with \"\\vert\"."
  19377. (while (string-match "|" s)
  19378. (setq s (replace-match "\\vert" t t s)))
  19379. s)
  19380. (defun org-uuidgen-p (s)
  19381. "Is S an ID created by UUIDGEN?"
  19382. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19383. (defun org-in-src-block-p (&optional inside)
  19384. "Whether point is in a code source block.
  19385. When INSIDE is non-nil, don't consider we are within a src block
  19386. when point is at #+BEGIN_SRC or #+END_SRC."
  19387. (let ((case-fold-search t))
  19388. (or (and (eq (get-char-property (point) 'src-block) t))
  19389. (and (not inside)
  19390. (save-match-data
  19391. (save-excursion
  19392. (beginning-of-line)
  19393. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19394. (defun org-context ()
  19395. "Return a list of contexts of the current cursor position.
  19396. If several contexts apply, all are returned.
  19397. Each context entry is a list with a symbol naming the context, and
  19398. two positions indicating start and end of the context. Possible
  19399. contexts are:
  19400. :headline anywhere in a headline
  19401. :headline-stars on the leading stars in a headline
  19402. :todo-keyword on a TODO keyword (including DONE) in a headline
  19403. :tags on the TAGS in a headline
  19404. :priority on the priority cookie in a headline
  19405. :item on the first line of a plain list item
  19406. :item-bullet on the bullet/number of a plain list item
  19407. :checkbox on the checkbox in a plain list item
  19408. :table in an Org table
  19409. :table-special on a special filed in a table
  19410. :table-table in a table.el table
  19411. :clocktable in a clocktable
  19412. :src-block in a source block
  19413. :link on a hyperlink
  19414. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19415. :target on a <<target>>
  19416. :radio-target on a <<<radio-target>>>
  19417. :latex-fragment on a LaTeX fragment
  19418. :latex-preview on a LaTeX fragment with overlaid preview image
  19419. This function expects the position to be visible because it uses font-lock
  19420. faces as a help to recognize the following contexts: :table-special, :link,
  19421. and :keyword."
  19422. (let* ((f (get-text-property (point) 'face))
  19423. (faces (if (listp f) f (list f)))
  19424. (case-fold-search t)
  19425. (p (point)) clist o)
  19426. ;; First the large context
  19427. (cond
  19428. ((org-at-heading-p t)
  19429. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19430. (when (progn
  19431. (beginning-of-line 1)
  19432. (looking-at org-todo-line-tags-regexp))
  19433. (push (org-point-in-group p 1 :headline-stars) clist)
  19434. (push (org-point-in-group p 2 :todo-keyword) clist)
  19435. (push (org-point-in-group p 4 :tags) clist))
  19436. (goto-char p)
  19437. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19438. (when (looking-at "\\[#[A-Z0-9]\\]")
  19439. (push (org-point-in-group p 0 :priority) clist)))
  19440. ((org-at-item-p)
  19441. (push (org-point-in-group p 2 :item-bullet) clist)
  19442. (push (list :item (point-at-bol)
  19443. (save-excursion (org-end-of-item) (point)))
  19444. clist)
  19445. (and (org-at-item-checkbox-p)
  19446. (push (org-point-in-group p 0 :checkbox) clist)))
  19447. ((org-at-table-p)
  19448. (push (list :table (org-table-begin) (org-table-end)) clist)
  19449. (when (memq 'org-formula faces)
  19450. (push (list :table-special
  19451. (previous-single-property-change p 'face)
  19452. (next-single-property-change p 'face)) clist)))
  19453. ((org-at-table-p 'any)
  19454. (push (list :table-table) clist)))
  19455. (goto-char p)
  19456. (let ((case-fold-search t))
  19457. ;; New the "medium" contexts: clocktables, source blocks
  19458. (cond ((org-in-clocktable-p)
  19459. (push (list :clocktable
  19460. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19461. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19462. (match-beginning 1))
  19463. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19464. (match-end 0))) clist))
  19465. ((org-in-src-block-p)
  19466. (push (list :src-block
  19467. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19468. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19469. (match-beginning 1))
  19470. (and (search-forward "#+END_SRC" nil t)
  19471. (match-beginning 0))) clist))))
  19472. (goto-char p)
  19473. ;; Now the small context
  19474. (cond
  19475. ((org-at-timestamp-p)
  19476. (push (org-point-in-group p 0 :timestamp) clist))
  19477. ((memq 'org-link faces)
  19478. (push (list :link
  19479. (previous-single-property-change p 'face)
  19480. (next-single-property-change p 'face)) clist))
  19481. ((memq 'org-special-keyword faces)
  19482. (push (list :keyword
  19483. (previous-single-property-change p 'face)
  19484. (next-single-property-change p 'face)) clist))
  19485. ((org-at-target-p)
  19486. (push (org-point-in-group p 0 :target) clist)
  19487. (goto-char (1- (match-beginning 0)))
  19488. (when (looking-at org-radio-target-regexp)
  19489. (push (org-point-in-group p 0 :radio-target) clist))
  19490. (goto-char p))
  19491. ((setq o (cl-some
  19492. (lambda (o)
  19493. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19494. o))
  19495. (overlays-at (point))))
  19496. (push (list :latex-fragment
  19497. (overlay-start o) (overlay-end o)) clist)
  19498. (push (list :latex-preview
  19499. (overlay-start o) (overlay-end o)) clist))
  19500. ((org-inside-LaTeX-fragment-p)
  19501. ;; FIXME: positions wrong.
  19502. (push (list :latex-fragment (point) (point)) clist)))
  19503. (setq clist (nreverse (delq nil clist)))
  19504. clist))
  19505. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19506. "Non-nil when point is between matches of START-RE and END-RE.
  19507. Also return a non-nil value when point is on one of the matches.
  19508. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19509. buffer positions. Default values are the positions of headlines
  19510. surrounding the point.
  19511. The functions returns a cons cell whose car (resp. cdr) is the
  19512. position before START-RE (resp. after END-RE)."
  19513. (save-match-data
  19514. (let ((pos (point))
  19515. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19516. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19517. beg end)
  19518. (save-excursion
  19519. ;; Point is on a block when on START-RE or if START-RE can be
  19520. ;; found before it...
  19521. (and (or (org-in-regexp start-re)
  19522. (re-search-backward start-re limit-up t))
  19523. (setq beg (match-beginning 0))
  19524. ;; ... and END-RE after it...
  19525. (goto-char (match-end 0))
  19526. (re-search-forward end-re limit-down t)
  19527. (> (setq end (match-end 0)) pos)
  19528. ;; ... without another START-RE in-between.
  19529. (goto-char (match-beginning 0))
  19530. (not (re-search-backward start-re (1+ beg) t))
  19531. ;; Return value.
  19532. (cons beg end))))))
  19533. (defun org-in-block-p (names)
  19534. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19535. NAMES is a list of strings containing names of blocks.
  19536. Return first block name matched, or nil. Beware that in case of
  19537. nested blocks, the returned name may not belong to the closest
  19538. block from point."
  19539. (save-match-data
  19540. (catch 'exit
  19541. (let ((case-fold-search t)
  19542. (lim-up (save-excursion (outline-previous-heading)))
  19543. (lim-down (save-excursion (outline-next-heading))))
  19544. (dolist (name names)
  19545. (let ((n (regexp-quote name)))
  19546. (when (org-between-regexps-p
  19547. (concat "^[ \t]*#\\+begin_" n)
  19548. (concat "^[ \t]*#\\+end_" n)
  19549. lim-up lim-down)
  19550. (throw 'exit n)))))
  19551. nil)))
  19552. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19553. "Call `multi-occur' with buffers for all agenda files."
  19554. (interactive "sOrg-files matching: ")
  19555. (let* ((files (org-agenda-files))
  19556. (tnames (mapcar #'file-truename files))
  19557. (extra org-agenda-text-search-extra-files))
  19558. (when (eq (car extra) 'agenda-archives)
  19559. (setq extra (cdr extra))
  19560. (setq files (org-add-archive-files files)))
  19561. (dolist (f extra)
  19562. (unless (member (file-truename f) tnames)
  19563. (unless (member f files) (setq files (append files (list f))))
  19564. (setq tnames (append tnames (list (file-truename f))))))
  19565. (multi-occur
  19566. (mapcar (lambda (x)
  19567. (with-current-buffer
  19568. ;; FIXME: Why not just (find-file-noselect x)?
  19569. ;; Is it to avoid the "revert buffer" prompt?
  19570. (or (get-file-buffer x) (find-file-noselect x))
  19571. (widen)
  19572. (current-buffer)))
  19573. files)
  19574. regexp)))
  19575. (add-hook 'occur-mode-find-occurrence-hook
  19576. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19577. (defun org-occur-link-in-agenda-files ()
  19578. "Create a link and search for it in the agendas.
  19579. The link is not stored in `org-stored-links', it is just created
  19580. for the search purpose."
  19581. (interactive)
  19582. (let ((link (condition-case nil
  19583. (org-store-link nil)
  19584. (error "Unable to create a link to here"))))
  19585. (org-occur-in-agenda-files (regexp-quote link))))
  19586. (defun org-back-over-empty-lines ()
  19587. "Move backwards over whitespace, to the beginning of the first empty line.
  19588. Returns the number of empty lines passed."
  19589. (let ((pos (point)))
  19590. (if (cdr (assq 'heading org-blank-before-new-entry))
  19591. (skip-chars-backward " \t\n\r")
  19592. (unless (eobp)
  19593. (forward-line -1)))
  19594. (beginning-of-line 2)
  19595. (goto-char (min (point) pos))
  19596. (count-lines (point) pos)))
  19597. (defun org-replace-escapes (string table)
  19598. "Replace %-escapes in STRING with values in TABLE.
  19599. TABLE is an association list with keys like \"%a\" and string values.
  19600. The sequences in STRING may contain normal field width and padding information,
  19601. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19602. so values can contain further %-escapes if they are define later in TABLE."
  19603. (let ((tbl (copy-alist table))
  19604. (case-fold-search nil)
  19605. (pchg 0)
  19606. re rpl)
  19607. (dolist (e tbl)
  19608. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19609. (when (and (cdr e) (string-match re (cdr e)))
  19610. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19611. (safe "SREF"))
  19612. (add-text-properties 0 3 (list 'sref sref) safe)
  19613. (setcdr e (replace-match safe t t (cdr e)))))
  19614. (while (string-match re string)
  19615. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19616. (cdr e)))
  19617. (setq string (replace-match rpl t t string))))
  19618. (while (setq pchg (next-property-change pchg string))
  19619. (let ((sref (get-text-property pchg 'sref string)))
  19620. (when (and sref (string-match "SREF" string pchg))
  19621. (setq string (replace-match sref t t string)))))
  19622. string))
  19623. ;;; TODO: Only called once, from ox-odt which should probably use
  19624. ;;; org-export-inline-image-p or something.
  19625. (defun org-file-image-p (file)
  19626. "Return non-nil if FILE is an image."
  19627. (save-match-data
  19628. (string-match (image-file-name-regexp) file)))
  19629. (defun org-get-cursor-date (&optional with-time)
  19630. "Return the date at cursor in as a time.
  19631. This works in the calendar and in the agenda, anywhere else it just
  19632. returns the current time.
  19633. If WITH-TIME is non-nil, returns the time of the event at point (in
  19634. the agenda) or the current time of the day."
  19635. (let (date day defd tp hod mod)
  19636. (when with-time
  19637. (setq tp (get-text-property (point) 'time))
  19638. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19639. (setq hod (string-to-number (match-string 1 tp))
  19640. mod (string-to-number (match-string 2 tp))))
  19641. (or tp (let ((now (decode-time)))
  19642. (setq hod (nth 2 now)
  19643. mod (nth 1 now)))))
  19644. (cond
  19645. ((eq major-mode 'calendar-mode)
  19646. (setq date (calendar-cursor-to-date)
  19647. defd (encode-time 0 (or mod 0) (or hod 0)
  19648. (nth 1 date) (nth 0 date) (nth 2 date))))
  19649. ((eq major-mode 'org-agenda-mode)
  19650. (setq day (get-text-property (point) 'day))
  19651. (when day
  19652. (setq date (calendar-gregorian-from-absolute day)
  19653. defd (encode-time 0 (or mod 0) (or hod 0)
  19654. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19655. (or defd (current-time))))
  19656. (defun org-mark-subtree (&optional up)
  19657. "Mark the current subtree.
  19658. This puts point at the start of the current subtree, and mark at
  19659. the end. If a numeric prefix UP is given, move up into the
  19660. hierarchy of headlines by UP levels before marking the subtree."
  19661. (interactive "P")
  19662. (org-with-limited-levels
  19663. (cond ((org-at-heading-p) (beginning-of-line))
  19664. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19665. (t (outline-previous-visible-heading 1))))
  19666. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19667. (if (called-interactively-p 'any)
  19668. (call-interactively 'org-mark-element)
  19669. (org-mark-element)))
  19670. ;;; Indentation
  19671. (defvar org-element-greater-elements)
  19672. (defun org--get-expected-indentation (element contentsp)
  19673. "Expected indentation column for current line, according to ELEMENT.
  19674. ELEMENT is an element containing point. CONTENTSP is non-nil
  19675. when indentation is to be computed according to contents of
  19676. ELEMENT."
  19677. (let ((type (org-element-type element))
  19678. (start (org-element-property :begin element))
  19679. (post-affiliated (org-element-property :post-affiliated element)))
  19680. (org-with-wide-buffer
  19681. (cond
  19682. (contentsp
  19683. (cl-case type
  19684. ((diary-sexp footnote-definition) 0)
  19685. ((headline inlinetask nil)
  19686. (if (not org-adapt-indentation) 0
  19687. (let ((level (org-current-level)))
  19688. (if level (1+ level) 0))))
  19689. ((item plain-list) (org-list-item-body-column post-affiliated))
  19690. (t
  19691. (goto-char start)
  19692. (current-indentation))))
  19693. ((memq type '(headline inlinetask nil))
  19694. (if (org-match-line "[ \t]*$")
  19695. (org--get-expected-indentation element t)
  19696. 0))
  19697. ((memq type '(diary-sexp footnote-definition)) 0)
  19698. ;; First paragraph of a footnote definition or an item.
  19699. ;; Indent like parent.
  19700. ((< (line-beginning-position) start)
  19701. (org--get-expected-indentation
  19702. (org-element-property :parent element) t))
  19703. ;; At first line: indent according to previous sibling, if any,
  19704. ;; ignoring footnote definitions and inline tasks, or parent's
  19705. ;; contents.
  19706. ((= (line-beginning-position) start)
  19707. (catch 'exit
  19708. (while t
  19709. (if (= (point-min) start) (throw 'exit 0)
  19710. (goto-char (1- start))
  19711. (let* ((previous (org-element-at-point))
  19712. (parent previous))
  19713. (while (and parent (<= (org-element-property :end parent) start))
  19714. (setq previous parent
  19715. parent (org-element-property :parent parent)))
  19716. (cond
  19717. ((not previous) (throw 'exit 0))
  19718. ((> (org-element-property :end previous) start)
  19719. (throw 'exit (org--get-expected-indentation previous t)))
  19720. ((memq (org-element-type previous)
  19721. '(footnote-definition inlinetask))
  19722. (setq start (org-element-property :begin previous)))
  19723. (t (goto-char (org-element-property :begin previous))
  19724. (throw 'exit
  19725. (if (bolp) (current-indentation)
  19726. ;; At first paragraph in an item or
  19727. ;; a footnote definition.
  19728. (org--get-expected-indentation
  19729. (org-element-property :parent previous) t))))))))))
  19730. ;; Otherwise, move to the first non-blank line above.
  19731. (t
  19732. (beginning-of-line)
  19733. (let ((pos (point)))
  19734. (skip-chars-backward " \r\t\n")
  19735. (cond
  19736. ;; Two blank lines end a footnote definition or a plain
  19737. ;; list. When we indent an empty line after them, the
  19738. ;; containing list or footnote definition is over, so it
  19739. ;; qualifies as a previous sibling. Therefore, we indent
  19740. ;; like its first line.
  19741. ((and (memq type '(footnote-definition plain-list))
  19742. (> (count-lines (point) pos) 2))
  19743. (goto-char start)
  19744. (current-indentation))
  19745. ;; Line above is the first one of a paragraph at the
  19746. ;; beginning of an item or a footnote definition. Indent
  19747. ;; like parent.
  19748. ((< (line-beginning-position) start)
  19749. (org--get-expected-indentation
  19750. (org-element-property :parent element) t))
  19751. ;; Line above is the beginning of an element, i.e., point
  19752. ;; was originally on the blank lines between element's start
  19753. ;; and contents.
  19754. ((= (line-beginning-position) post-affiliated)
  19755. (org--get-expected-indentation element t))
  19756. ;; POS is after contents in a greater element. Indent like
  19757. ;; the beginning of the element.
  19758. ((and (memq type org-element-greater-elements)
  19759. (let ((cend (org-element-property :contents-end element)))
  19760. (and cend (<= cend pos))))
  19761. ;; As a special case, if point is at the end of a footnote
  19762. ;; definition or an item, indent like the very last element
  19763. ;; within. If that last element is an item, indent like
  19764. ;; its contents.
  19765. (if (memq type '(footnote-definition item plain-list))
  19766. (let ((last (org-element-at-point)))
  19767. (goto-char pos)
  19768. (org--get-expected-indentation
  19769. last (eq (org-element-type last) 'item)))
  19770. (goto-char start)
  19771. (current-indentation)))
  19772. ;; In any other case, indent like the current line.
  19773. (t (current-indentation)))))))))
  19774. (defun org--align-node-property ()
  19775. "Align node property at point.
  19776. Alignment is done according to `org-property-format', which see."
  19777. (when (save-excursion
  19778. (beginning-of-line)
  19779. (looking-at org-property-re))
  19780. (replace-match
  19781. (concat (match-string 4)
  19782. (org-trim
  19783. (format org-property-format (match-string 1) (match-string 3))))
  19784. t t)))
  19785. (defun org-indent-line ()
  19786. "Indent line depending on context.
  19787. Indentation is done according to the following rules:
  19788. - Footnote definitions, diary sexps, headlines and inline tasks
  19789. have to start at column 0.
  19790. - On the very first line of an element, consider, in order, the
  19791. next rules until one matches:
  19792. 1. If there's a sibling element before, ignoring footnote
  19793. definitions and inline tasks, indent like its first line.
  19794. 2. If element has a parent, indent like its contents. More
  19795. precisely, if parent is an item, indent after the
  19796. description part, if any, or the bullet (see
  19797. `org-list-description-max-indent'). Else, indent like
  19798. parent's first line.
  19799. 3. Otherwise, indent relatively to current level, if
  19800. `org-adapt-indentation' is non-nil, or to left margin.
  19801. - On a blank line at the end of an element, indent according to
  19802. the type of the element. More precisely
  19803. 1. If element is a plain list, an item, or a footnote
  19804. definition, indent like the very last element within.
  19805. 2. If element is a paragraph, indent like its last non blank
  19806. line.
  19807. 3. Otherwise, indent like its very first line.
  19808. - In the code part of a source block, use language major mode
  19809. to indent current line if `org-src-tab-acts-natively' is
  19810. non-nil. If it is nil, do nothing.
  19811. - Otherwise, indent like the first non-blank line above.
  19812. The function doesn't indent an item as it could break the whole
  19813. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19814. `\\[org-shiftmetaright]'.
  19815. Also align node properties according to `org-property-format'."
  19816. (interactive)
  19817. (cond
  19818. ((org-at-heading-p) 'noindent)
  19819. (t
  19820. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19821. (type (org-element-type element)))
  19822. (cond ((and (memq type '(plain-list item))
  19823. (= (line-beginning-position)
  19824. (org-element-property :post-affiliated element)))
  19825. 'noindent)
  19826. ((and (eq type 'latex-environment)
  19827. (>= (point) (org-element-property :post-affiliated element))
  19828. (< (point) (org-with-wide-buffer
  19829. (goto-char (org-element-property :end element))
  19830. (skip-chars-backward " \r\t\n")
  19831. (line-beginning-position 2))))
  19832. 'noindent)
  19833. ((and (eq type 'src-block)
  19834. org-src-tab-acts-natively
  19835. (> (line-beginning-position)
  19836. (org-element-property :post-affiliated element))
  19837. (< (line-beginning-position)
  19838. (org-with-wide-buffer
  19839. (goto-char (org-element-property :end element))
  19840. (skip-chars-backward " \r\t\n")
  19841. (line-beginning-position))))
  19842. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19843. (t
  19844. (let ((column (org--get-expected-indentation element nil)))
  19845. ;; Preserve current column.
  19846. (if (<= (current-column) (current-indentation))
  19847. (indent-line-to column)
  19848. (save-excursion (indent-line-to column))))
  19849. ;; Align node property. Also preserve current column.
  19850. (when (eq type 'node-property)
  19851. (let ((column (current-column)))
  19852. (org--align-node-property)
  19853. (org-move-to-column column)))))))))
  19854. (defun org-indent-region (start end)
  19855. "Indent each non-blank line in the region.
  19856. Called from a program, START and END specify the region to
  19857. indent. The function will not indent contents of example blocks,
  19858. verse blocks and export blocks as leading white spaces are
  19859. assumed to be significant there."
  19860. (interactive "r")
  19861. (save-excursion
  19862. (goto-char start)
  19863. (skip-chars-forward " \r\t\n")
  19864. (unless (eobp) (beginning-of-line))
  19865. (let ((indent-to
  19866. (lambda (ind pos)
  19867. ;; Set IND as indentation for all lines between point and
  19868. ;; POS. Blank lines are ignored. Leave point after POS
  19869. ;; once done.
  19870. (let ((limit (copy-marker pos)))
  19871. (while (< (point) limit)
  19872. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19873. (forward-line))
  19874. (set-marker limit nil))))
  19875. (end (copy-marker end)))
  19876. (while (< (point) end)
  19877. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19878. (let* ((element (org-element-at-point))
  19879. (type (org-element-type element))
  19880. (element-end (copy-marker (org-element-property :end element)))
  19881. (ind (org--get-expected-indentation element nil)))
  19882. (cond
  19883. ;; Element indented as a single block. Example blocks
  19884. ;; preserving indentation are a special case since the
  19885. ;; "contents" must not be indented whereas the block
  19886. ;; boundaries can.
  19887. ((or (memq type '(export-block latex-environment))
  19888. (and (eq type 'example-block)
  19889. (not
  19890. (or org-src-preserve-indentation
  19891. (org-element-property :preserve-indent element)))))
  19892. (let ((offset (- ind (current-indentation))))
  19893. (unless (zerop offset)
  19894. (indent-rigidly (org-element-property :begin element)
  19895. (org-element-property :end element)
  19896. offset)))
  19897. (goto-char element-end))
  19898. ;; Elements indented line wise. Be sure to exclude
  19899. ;; example blocks (preserving indentation) and source
  19900. ;; blocks from this category as they are treated
  19901. ;; specially later.
  19902. ((or (memq type '(paragraph table table-row))
  19903. (not (or (org-element-property :contents-begin element)
  19904. (memq type '(example-block src-block)))))
  19905. (when (eq type 'node-property)
  19906. (org--align-node-property)
  19907. (beginning-of-line))
  19908. (funcall indent-to ind (min element-end end)))
  19909. ;; Elements consisting of three parts: before the
  19910. ;; contents, the contents, and after the contents. The
  19911. ;; contents are treated specially, according to the
  19912. ;; element type, or not indented at all. Other parts are
  19913. ;; indented as a single block.
  19914. (t
  19915. (let* ((post (copy-marker
  19916. (org-element-property :post-affiliated element)))
  19917. (cbeg
  19918. (copy-marker
  19919. (cond
  19920. ((not (org-element-property :contents-begin element))
  19921. ;; Fake contents for source blocks.
  19922. (org-with-wide-buffer
  19923. (goto-char post)
  19924. (line-beginning-position 2)))
  19925. ((memq type '(footnote-definition item plain-list))
  19926. ;; Contents in these elements could start on
  19927. ;; the same line as the beginning of the
  19928. ;; element. Make sure we start indenting
  19929. ;; from the second line.
  19930. (org-with-wide-buffer
  19931. (goto-char post)
  19932. (end-of-line)
  19933. (skip-chars-forward " \r\t\n")
  19934. (if (eobp) (point) (line-beginning-position))))
  19935. (t (org-element-property :contents-begin element)))))
  19936. (cend (copy-marker
  19937. (or (org-element-property :contents-end element)
  19938. ;; Fake contents for source blocks.
  19939. (org-with-wide-buffer
  19940. (goto-char element-end)
  19941. (skip-chars-backward " \r\t\n")
  19942. (line-beginning-position)))
  19943. t)))
  19944. ;; Do not change items indentation individually as it
  19945. ;; might break the list as a whole. On the other
  19946. ;; hand, when at a plain list, indent it as a whole.
  19947. (cond ((eq type 'plain-list)
  19948. (let ((offset (- ind (current-indentation))))
  19949. (unless (zerop offset)
  19950. (indent-rigidly (org-element-property :begin element)
  19951. (org-element-property :end element)
  19952. offset))
  19953. (goto-char cbeg)))
  19954. ((eq type 'item) (goto-char cbeg))
  19955. (t (funcall indent-to ind (min cbeg end))))
  19956. (when (< (point) end)
  19957. (cl-case type
  19958. ((example-block verse-block))
  19959. (src-block
  19960. ;; In a source block, indent source code
  19961. ;; according to language major mode, but only if
  19962. ;; `org-src-tab-acts-natively' is non-nil.
  19963. (when (and (< (point) end) org-src-tab-acts-natively)
  19964. (ignore-errors
  19965. (org-babel-do-in-edit-buffer
  19966. (indent-region (point-min) (point-max))))))
  19967. (t (org-indent-region (point) (min cend end))))
  19968. (goto-char (min cend end))
  19969. (when (< (point) end)
  19970. (funcall indent-to ind (min element-end end))))
  19971. (set-marker post nil)
  19972. (set-marker cbeg nil)
  19973. (set-marker cend nil))))
  19974. (set-marker element-end nil))))
  19975. (set-marker end nil))))
  19976. (defun org-indent-drawer ()
  19977. "Indent the drawer at point."
  19978. (interactive)
  19979. (unless (save-excursion
  19980. (beginning-of-line)
  19981. (looking-at-p org-drawer-regexp))
  19982. (user-error "Not at a drawer"))
  19983. (let ((element (org-element-at-point)))
  19984. (unless (memq (org-element-type element) '(drawer property-drawer))
  19985. (user-error "Not at a drawer"))
  19986. (org-with-wide-buffer
  19987. (org-indent-region (org-element-property :begin element)
  19988. (org-element-property :end element))))
  19989. (message "Drawer at point indented"))
  19990. (defun org-indent-block ()
  19991. "Indent the block at point."
  19992. (interactive)
  19993. (unless (save-excursion
  19994. (beginning-of-line)
  19995. (let ((case-fold-search t))
  19996. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19997. (user-error "Not at a block"))
  19998. (let ((element (org-element-at-point)))
  19999. (unless (memq (org-element-type element)
  20000. '(comment-block center-block dynamic-block example-block
  20001. export-block quote-block special-block
  20002. src-block verse-block))
  20003. (user-error "Not at a block"))
  20004. (org-with-wide-buffer
  20005. (org-indent-region (org-element-property :begin element)
  20006. (org-element-property :end element))))
  20007. (message "Block at point indented"))
  20008. ;;; Filling
  20009. ;; We use our own fill-paragraph and auto-fill functions.
  20010. ;; `org-fill-paragraph' relies on adaptive filling and context
  20011. ;; checking. Appropriate `fill-prefix' is computed with
  20012. ;; `org-adaptive-fill-function'.
  20013. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20014. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20015. ;; `org-adaptive-fill-function' value. Internally,
  20016. ;; `org-comment-line-break-function' breaks the line.
  20017. ;; `org-setup-filling' installs filling and auto-filling related
  20018. ;; variables during `org-mode' initialization.
  20019. (defun org-setup-filling ()
  20020. (require 'org-element)
  20021. ;; Prevent auto-fill from inserting unwanted new items.
  20022. (when (boundp 'fill-nobreak-predicate)
  20023. (setq-local
  20024. fill-nobreak-predicate
  20025. (org-uniquify
  20026. (append fill-nobreak-predicate
  20027. '(org-fill-line-break-nobreak-p
  20028. org-fill-n-macro-as-item-nobreak-p
  20029. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20030. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20031. (setq-local paragraph-start paragraph-ending)
  20032. (setq-local paragraph-separate paragraph-ending))
  20033. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20034. (setq-local auto-fill-inhibit-regexp nil)
  20035. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20036. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20037. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20038. (defun org-fill-line-break-nobreak-p ()
  20039. "Non-nil when a new line at point would create an Org line break."
  20040. (save-excursion
  20041. (skip-chars-backward "[ \t]")
  20042. (skip-chars-backward "\\\\")
  20043. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20044. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20045. "Non-nil when a new line at point would split a timestamp."
  20046. (and (org-at-timestamp-p 'lax)
  20047. (not (looking-at org-ts-regexp-both))))
  20048. (defun org-fill-n-macro-as-item-nobreak-p ()
  20049. "Non-nil when a new line at point would create a new list."
  20050. ;; During export, a "n" macro followed by a dot or a closing
  20051. ;; parenthesis can end up being parsed as a new list item.
  20052. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20053. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20054. (defun org-adaptive-fill-function ()
  20055. "Compute a fill prefix for the current line.
  20056. Return fill prefix, as a string, or nil if current line isn't
  20057. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20058. matches in paragraphs or comments, use it."
  20059. (org-with-wide-buffer
  20060. (unless (org-at-heading-p)
  20061. (let* ((p (line-beginning-position))
  20062. (element (save-excursion
  20063. (beginning-of-line)
  20064. (org-element-at-point)))
  20065. (type (org-element-type element))
  20066. (post-affiliated (org-element-property :post-affiliated element)))
  20067. (unless (< p post-affiliated)
  20068. (cl-case type
  20069. (comment
  20070. (save-excursion
  20071. (beginning-of-line)
  20072. (looking-at "[ \t]*")
  20073. (concat (match-string 0) "# ")))
  20074. (footnote-definition "")
  20075. ((item plain-list)
  20076. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20077. (paragraph
  20078. ;; Fill prefix is usually the same as the current line,
  20079. ;; unless the paragraph is at the beginning of an item.
  20080. (let ((parent (org-element-property :parent element)))
  20081. (save-excursion
  20082. (beginning-of-line)
  20083. (cond ((eq (org-element-type parent) 'item)
  20084. (make-string (org-list-item-body-column
  20085. (org-element-property :begin parent))
  20086. ?\s))
  20087. ((and adaptive-fill-regexp
  20088. ;; Locally disable
  20089. ;; `adaptive-fill-function' to let
  20090. ;; `fill-context-prefix' handle
  20091. ;; `adaptive-fill-regexp' variable.
  20092. (let (adaptive-fill-function)
  20093. (fill-context-prefix
  20094. post-affiliated
  20095. (org-element-property :end element)))))
  20096. ((looking-at "[ \t]+") (match-string 0))
  20097. (t "")))))
  20098. (comment-block
  20099. ;; Only fill contents if P is within block boundaries.
  20100. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20101. (forward-line)
  20102. (point)))
  20103. (cend (save-excursion
  20104. (goto-char (org-element-property :end element))
  20105. (skip-chars-backward " \r\t\n")
  20106. (line-beginning-position))))
  20107. (when (and (>= p cbeg) (< p cend))
  20108. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20109. (match-string 0)
  20110. ""))))))))))
  20111. (defun org-fill-element (&optional justify)
  20112. "Fill element at point, when applicable.
  20113. This function only applies to comment blocks, comments, example
  20114. blocks and paragraphs. Also, as a special case, re-align table
  20115. when point is at one.
  20116. If JUSTIFY is non-nil (interactively, with prefix argument),
  20117. justify as well. If `sentence-end-double-space' is non-nil, then
  20118. period followed by one space does not end a sentence, so don't
  20119. break a line there. The variable `fill-column' controls the
  20120. width for filling.
  20121. For convenience, when point is at a plain list, an item or
  20122. a footnote definition, try to fill the first paragraph within."
  20123. (with-syntax-table org-mode-transpose-word-syntax-table
  20124. ;; Move to end of line in order to get the first paragraph within
  20125. ;; a plain list or a footnote definition.
  20126. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20127. ;; First check if point is in a blank line at the beginning of
  20128. ;; the buffer. In that case, ignore filling.
  20129. (cl-case (org-element-type element)
  20130. ;; Use major mode filling function is src blocks.
  20131. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20132. ;; Align Org tables, leave table.el tables as-is.
  20133. (table-row (org-table-align) t)
  20134. (table
  20135. (when (eq (org-element-property :type element) 'org)
  20136. (save-excursion
  20137. (goto-char (org-element-property :post-affiliated element))
  20138. (org-table-align)))
  20139. t)
  20140. (paragraph
  20141. ;; Paragraphs may contain `line-break' type objects.
  20142. (let ((beg (max (point-min)
  20143. (org-element-property :contents-begin element)))
  20144. (end (min (point-max)
  20145. (org-element-property :contents-end element))))
  20146. ;; Do nothing if point is at an affiliated keyword.
  20147. (if (< (line-end-position) beg) t
  20148. ;; Fill paragraph, taking line breaks into account.
  20149. (save-excursion
  20150. (goto-char beg)
  20151. (let ((cuts (list beg)))
  20152. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20153. (when (eq 'line-break
  20154. (org-element-type
  20155. (save-excursion (backward-char)
  20156. (org-element-context))))
  20157. (push (point) cuts)))
  20158. (dolist (c (delq end cuts))
  20159. (fill-region-as-paragraph c end justify)
  20160. (setq end c))))
  20161. t)))
  20162. ;; Contents of `comment-block' type elements should be
  20163. ;; filled as plain text, but only if point is within block
  20164. ;; markers.
  20165. (comment-block
  20166. (let* ((case-fold-search t)
  20167. (beg (save-excursion
  20168. (goto-char (org-element-property :begin element))
  20169. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20170. (forward-line)
  20171. (point)))
  20172. (end (save-excursion
  20173. (goto-char (org-element-property :end element))
  20174. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20175. (line-beginning-position))))
  20176. (if (or (< (point) beg) (> (point) end)) t
  20177. (fill-region-as-paragraph
  20178. (save-excursion (end-of-line)
  20179. (re-search-backward "^[ \t]*$" beg 'move)
  20180. (line-beginning-position))
  20181. (save-excursion (beginning-of-line)
  20182. (re-search-forward "^[ \t]*$" end 'move)
  20183. (line-beginning-position))
  20184. justify))))
  20185. ;; Fill comments.
  20186. (comment
  20187. (let ((begin (org-element-property :post-affiliated element))
  20188. (end (org-element-property :end element)))
  20189. (when (and (>= (point) begin) (<= (point) end))
  20190. (let ((begin (save-excursion
  20191. (end-of-line)
  20192. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20193. (progn (forward-line) (point))
  20194. begin)))
  20195. (end (save-excursion
  20196. (end-of-line)
  20197. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20198. (1- (line-beginning-position))
  20199. (skip-chars-backward " \r\t\n")
  20200. (line-end-position)))))
  20201. ;; Do not fill comments when at a blank line.
  20202. (when (> end begin)
  20203. (let ((fill-prefix
  20204. (save-excursion
  20205. (beginning-of-line)
  20206. (looking-at "[ \t]*#")
  20207. (let ((comment-prefix (match-string 0)))
  20208. (goto-char (match-end 0))
  20209. (if (looking-at adaptive-fill-regexp)
  20210. (concat comment-prefix (match-string 0))
  20211. (concat comment-prefix " "))))))
  20212. (save-excursion
  20213. (fill-region-as-paragraph begin end justify))))))
  20214. t))
  20215. ;; Ignore every other element.
  20216. (otherwise t)))))
  20217. (defun org-fill-paragraph (&optional justify region)
  20218. "Fill element at point, when applicable.
  20219. This function only applies to comment blocks, comments, example
  20220. blocks and paragraphs. Also, as a special case, re-align table
  20221. when point is at one.
  20222. For convenience, when point is at a plain list, an item or
  20223. a footnote definition, try to fill the first paragraph within.
  20224. If JUSTIFY is non-nil (interactively, with prefix argument),
  20225. justify as well. If `sentence-end-double-space' is non-nil, then
  20226. period followed by one space does not end a sentence, so don't
  20227. break a line there. The variable `fill-column' controls the
  20228. width for filling.
  20229. The REGION argument is non-nil if called interactively; in that
  20230. case, if Transient Mark mode is enabled and the mark is active,
  20231. fill each of the elements in the active region, instead of just
  20232. filling the current element."
  20233. (interactive (progn
  20234. (barf-if-buffer-read-only)
  20235. (list (when current-prefix-arg 'full) t)))
  20236. (cond
  20237. ((and region transient-mark-mode mark-active
  20238. (not (eq (region-beginning) (region-end))))
  20239. (let ((origin (point-marker))
  20240. (start (region-beginning)))
  20241. (unwind-protect
  20242. (progn
  20243. (goto-char (region-end))
  20244. (while (> (point) start)
  20245. (org-backward-paragraph)
  20246. (org-fill-element justify)))
  20247. (goto-char origin)
  20248. (set-marker origin nil))))
  20249. (t (org-fill-element justify))))
  20250. (defun org-auto-fill-function ()
  20251. "Auto-fill function."
  20252. ;; Check if auto-filling is meaningful.
  20253. (let ((fc (current-fill-column)))
  20254. (when (and fc (> (current-column) fc))
  20255. (let* ((fill-prefix (org-adaptive-fill-function))
  20256. ;; Enforce empty fill prefix, if required. Otherwise, it
  20257. ;; will be computed again.
  20258. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20259. (when fill-prefix (do-auto-fill))))))
  20260. (defun org-comment-line-break-function (&optional soft)
  20261. "Break line at point and indent, continuing comment if within one.
  20262. The inserted newline is marked hard if variable
  20263. `use-hard-newlines' is true, unless optional argument SOFT is
  20264. non-nil."
  20265. (if soft (insert-and-inherit ?\n) (newline 1))
  20266. (save-excursion (forward-char -1) (delete-horizontal-space))
  20267. (delete-horizontal-space)
  20268. (indent-to-left-margin)
  20269. (insert-before-markers-and-inherit fill-prefix))
  20270. ;;; Fixed Width Areas
  20271. (defun org-toggle-fixed-width ()
  20272. "Toggle fixed-width markup.
  20273. Add or remove fixed-width markup on current line, whenever it
  20274. makes sense. Return an error otherwise.
  20275. If a region is active and if it contains only fixed-width areas
  20276. or blank lines, remove all fixed-width markup in it. If the
  20277. region contains anything else, convert all non-fixed-width lines
  20278. to fixed-width ones.
  20279. Blank lines at the end of the region are ignored unless the
  20280. region only contains such lines."
  20281. (interactive)
  20282. (if (not (org-region-active-p))
  20283. ;; No region:
  20284. ;;
  20285. ;; Remove fixed width marker only in a fixed-with element.
  20286. ;;
  20287. ;; Add fixed width maker in paragraphs, in blank lines after
  20288. ;; elements or at the beginning of a headline or an inlinetask,
  20289. ;; and before any one-line elements (e.g., a clock).
  20290. (progn
  20291. (beginning-of-line)
  20292. (let* ((element (org-element-at-point))
  20293. (type (org-element-type element)))
  20294. (cond
  20295. ((and (eq type 'fixed-width)
  20296. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20297. (replace-match
  20298. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20299. ((and (memq type '(babel-call clock comment diary-sexp headline
  20300. horizontal-rule keyword paragraph
  20301. planning))
  20302. (<= (org-element-property :post-affiliated element) (point)))
  20303. (skip-chars-forward " \t")
  20304. (insert ": "))
  20305. ((and (looking-at-p "[ \t]*$")
  20306. (or (eq type 'inlinetask)
  20307. (save-excursion
  20308. (skip-chars-forward " \r\t\n")
  20309. (<= (org-element-property :end element) (point)))))
  20310. (delete-region (point) (line-end-position))
  20311. (org-indent-line)
  20312. (insert ": "))
  20313. (t (user-error "Cannot insert a fixed-width line here")))))
  20314. ;; Region active.
  20315. (let* ((begin (save-excursion
  20316. (goto-char (region-beginning))
  20317. (line-beginning-position)))
  20318. (end (copy-marker
  20319. (save-excursion
  20320. (goto-char (region-end))
  20321. (unless (eolp) (beginning-of-line))
  20322. (if (save-excursion (re-search-backward "\\S-" begin t))
  20323. (progn (skip-chars-backward " \r\t\n") (point))
  20324. (point)))))
  20325. (all-fixed-width-p
  20326. (catch 'not-all-p
  20327. (save-excursion
  20328. (goto-char begin)
  20329. (skip-chars-forward " \r\t\n")
  20330. (when (eobp) (throw 'not-all-p nil))
  20331. (while (< (point) end)
  20332. (let ((element (org-element-at-point)))
  20333. (if (eq (org-element-type element) 'fixed-width)
  20334. (goto-char (org-element-property :end element))
  20335. (throw 'not-all-p nil))))
  20336. t))))
  20337. (if all-fixed-width-p
  20338. (save-excursion
  20339. (goto-char begin)
  20340. (while (< (point) end)
  20341. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20342. (replace-match
  20343. "" nil nil nil
  20344. (if (= (line-end-position) (match-end 0)) 0 1)))
  20345. (forward-line)))
  20346. (let ((min-ind (point-max)))
  20347. ;; Find minimum indentation across all lines.
  20348. (save-excursion
  20349. (goto-char begin)
  20350. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20351. (setq min-ind 0)
  20352. (catch 'zerop
  20353. (while (< (point) end)
  20354. (unless (looking-at-p "[ \t]*$")
  20355. (let ((ind (current-indentation)))
  20356. (setq min-ind (min min-ind ind))
  20357. (when (zerop ind) (throw 'zerop t))))
  20358. (forward-line)))))
  20359. ;; Loop over all lines and add fixed-width markup everywhere
  20360. ;; but in fixed-width lines.
  20361. (save-excursion
  20362. (goto-char begin)
  20363. (while (< (point) end)
  20364. (cond
  20365. ((org-at-heading-p)
  20366. (insert ": ")
  20367. (forward-line)
  20368. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20369. (insert ":")
  20370. (forward-line)))
  20371. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20372. (let* ((element (org-element-at-point))
  20373. (element-end (org-element-property :end element)))
  20374. (if (eq (org-element-type element) 'fixed-width)
  20375. (progn (goto-char element-end)
  20376. (skip-chars-backward " \r\t\n")
  20377. (forward-line))
  20378. (let ((limit (min end element-end)))
  20379. (while (< (point) limit)
  20380. (org-move-to-column min-ind t)
  20381. (insert ": ")
  20382. (forward-line))))))
  20383. (t
  20384. (org-move-to-column min-ind t)
  20385. (insert ": ")
  20386. (forward-line)))))))
  20387. (set-marker end nil))))
  20388. ;;; Blocks
  20389. (defun org-block-map (function &optional start end)
  20390. "Call FUNCTION at the head of all source blocks in the current buffer.
  20391. Optional arguments START and END can be used to limit the range."
  20392. (let ((start (or start (point-min)))
  20393. (end (or end (point-max))))
  20394. (save-excursion
  20395. (goto-char start)
  20396. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20397. (save-excursion
  20398. (save-match-data
  20399. (goto-char (match-beginning 0))
  20400. (funcall function)))))))
  20401. (defun org-next-block (arg &optional backward block-regexp)
  20402. "Jump to the next block.
  20403. With a prefix argument ARG, jump forward ARG many blocks.
  20404. When BACKWARD is non-nil, jump to the previous block.
  20405. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20406. Match data is set according to this regexp when the function
  20407. returns.
  20408. Return point at beginning of the opening line of found block.
  20409. Throw an error if no block is found."
  20410. (interactive "p")
  20411. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20412. (case-fold-search t)
  20413. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20414. (count (or arg 1))
  20415. (origin (point))
  20416. last-element)
  20417. (if backward (beginning-of-line) (end-of-line))
  20418. (while (and (> count 0) (funcall search-fn re nil t))
  20419. (let ((element (save-excursion
  20420. (goto-char (match-beginning 0))
  20421. (save-match-data (org-element-at-point)))))
  20422. (when (and (memq (org-element-type element)
  20423. '(center-block comment-block dynamic-block
  20424. example-block export-block quote-block
  20425. special-block src-block verse-block))
  20426. (<= (match-beginning 0)
  20427. (org-element-property :post-affiliated element)))
  20428. (setq last-element element)
  20429. (cl-decf count))))
  20430. (if (= count 0)
  20431. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20432. (save-match-data (org-show-context)))
  20433. (goto-char origin)
  20434. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20435. (defun org-previous-block (arg &optional block-regexp)
  20436. "Jump to the previous block.
  20437. With a prefix argument ARG, jump backward ARG many source blocks.
  20438. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20439. (interactive "p")
  20440. (org-next-block arg t block-regexp))
  20441. ;;; Comments
  20442. ;; Org comments syntax is quite complex. It requires the entire line
  20443. ;; to be just a comment. Also, even with the right syntax at the
  20444. ;; beginning of line, some elements (e.g., verse-block or
  20445. ;; example-block) don't accept comments. Usual Emacs comment commands
  20446. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20447. ;; Org still relies on `comment-dwim', but cannot trust
  20448. ;; `comment-only-p'. So, `comment-region-function' and
  20449. ;; `uncomment-region-function' both point
  20450. ;; to`org-comment-or-uncomment-region'. Eventually,
  20451. ;; `org-insert-comment' takes care of insertion of comments at the
  20452. ;; beginning of line.
  20453. ;; `org-setup-comments-handling' install comments related variables
  20454. ;; during `org-mode' initialization.
  20455. (defun org-setup-comments-handling ()
  20456. (interactive)
  20457. (setq-local comment-use-syntax nil)
  20458. (setq-local comment-start "# ")
  20459. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20460. (setq-local comment-insert-comment-function 'org-insert-comment)
  20461. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20462. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20463. (defun org-insert-comment ()
  20464. "Insert an empty comment above current line.
  20465. If the line is empty, insert comment at its beginning. When
  20466. point is within a source block, comment according to the related
  20467. major mode."
  20468. (if (let ((element (org-element-at-point)))
  20469. (and (eq (org-element-type element) 'src-block)
  20470. (< (save-excursion
  20471. (goto-char (org-element-property :post-affiliated element))
  20472. (line-end-position))
  20473. (point))
  20474. (> (save-excursion
  20475. (goto-char (org-element-property :end element))
  20476. (skip-chars-backward " \r\t\n")
  20477. (line-beginning-position))
  20478. (point))))
  20479. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20480. (beginning-of-line)
  20481. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20482. (open-line 1))
  20483. (org-indent-line)
  20484. (insert "# ")))
  20485. (defvar comment-empty-lines) ; From newcomment.el.
  20486. (defun org-comment-or-uncomment-region (beg end &rest _)
  20487. "Comment or uncomment each non-blank line in the region.
  20488. Uncomment each non-blank line between BEG and END if it only
  20489. contains commented lines. Otherwise, comment them. If region is
  20490. strictly within a source block, use appropriate comment syntax."
  20491. (if (let ((element (org-element-at-point)))
  20492. (and (eq (org-element-type element) 'src-block)
  20493. (< (save-excursion
  20494. (goto-char (org-element-property :post-affiliated element))
  20495. (line-end-position))
  20496. beg)
  20497. (>= (save-excursion
  20498. (goto-char (org-element-property :end element))
  20499. (skip-chars-backward " \r\t\n")
  20500. (line-beginning-position))
  20501. end)))
  20502. ;; Translate region boundaries for the Org buffer to the source
  20503. ;; buffer.
  20504. (let ((offset (- end beg)))
  20505. (save-excursion
  20506. (goto-char beg)
  20507. (org-babel-do-in-edit-buffer
  20508. (comment-or-uncomment-region (point) (+ offset (point))))))
  20509. (save-restriction
  20510. ;; Restrict region
  20511. (narrow-to-region (save-excursion (goto-char beg)
  20512. (skip-chars-forward " \r\t\n" end)
  20513. (line-beginning-position))
  20514. (save-excursion (goto-char end)
  20515. (skip-chars-backward " \r\t\n" beg)
  20516. (line-end-position)))
  20517. (let ((uncommentp
  20518. ;; UNCOMMENTP is non-nil when every non blank line between
  20519. ;; BEG and END is a comment.
  20520. (save-excursion
  20521. (goto-char (point-min))
  20522. (while (and (not (eobp))
  20523. (let ((element (org-element-at-point)))
  20524. (and (eq (org-element-type element) 'comment)
  20525. (goto-char (min (point-max)
  20526. (org-element-property
  20527. :end element)))))))
  20528. (eobp))))
  20529. (if uncommentp
  20530. ;; Only blank lines and comments in region: uncomment it.
  20531. (save-excursion
  20532. (goto-char (point-min))
  20533. (while (not (eobp))
  20534. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20535. (replace-match "" nil nil nil 1))
  20536. (forward-line)))
  20537. ;; Comment each line in region.
  20538. (let ((min-indent (point-max)))
  20539. ;; First find the minimum indentation across all lines.
  20540. (save-excursion
  20541. (goto-char (point-min))
  20542. (while (and (not (eobp)) (not (zerop min-indent)))
  20543. (unless (looking-at "[ \t]*$")
  20544. (setq min-indent (min min-indent (current-indentation))))
  20545. (forward-line)))
  20546. ;; Then loop over all lines.
  20547. (save-excursion
  20548. (goto-char (point-min))
  20549. (while (not (eobp))
  20550. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20551. ;; Don't get fooled by invisible text (e.g. link path)
  20552. ;; when moving to column MIN-INDENT.
  20553. (let ((buffer-invisibility-spec nil))
  20554. (org-move-to-column min-indent t))
  20555. (insert comment-start))
  20556. (forward-line)))))))))
  20557. (defun org-comment-dwim (_arg)
  20558. "Call the comment command you mean.
  20559. Call `org-toggle-comment' if on a heading, otherwise call
  20560. `comment-dwim', within a source edit buffer if needed."
  20561. (interactive "*P")
  20562. (cond ((org-at-heading-p)
  20563. (call-interactively #'org-toggle-comment))
  20564. ((org-in-src-block-p)
  20565. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20566. (t (call-interactively #'comment-dwim))))
  20567. ;;; Timestamps API
  20568. ;; This section contains tools to operate on, or create, timestamp
  20569. ;; objects, as returned by, e.g. `org-element-context'.
  20570. (defun org-timestamp-from-string (s)
  20571. "Convert Org timestamp S, as a string, into a timestamp object.
  20572. Return nil if S is not a valid timestamp string."
  20573. (when (org-string-nw-p s)
  20574. (with-temp-buffer
  20575. (save-excursion (insert s))
  20576. (org-element-timestamp-parser))))
  20577. (defun org-timestamp-from-time (time &optional with-time inactive)
  20578. "Convert a time value into a timestamp object.
  20579. TIME is an Emacs internal time representation, as returned, e.g.,
  20580. by `current-time'.
  20581. When optional argument WITH-TIME is non-nil, return a timestamp
  20582. object with a time part, i.e., with hours and minutes.
  20583. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20584. return an active timestamp."
  20585. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20586. (org-element-create 'timestamp
  20587. (list :type (if inactive 'inactive 'active)
  20588. :year-start year
  20589. :month-start month
  20590. :day-start day
  20591. :hour-start (and with-time hour)
  20592. :minute-start (and with-time minute)))))
  20593. (defun org-timestamp-to-time (timestamp &optional end)
  20594. "Convert TIMESTAMP object into an Emacs internal time value.
  20595. Use end of date range or time range when END is non-nil.
  20596. Otherwise, use its start."
  20597. (apply #'encode-time
  20598. (cons 0
  20599. (mapcar
  20600. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20601. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20602. '(:minute-start :hour-start :day-start :month-start
  20603. :year-start))))))
  20604. (defun org-timestamp-has-time-p (timestamp)
  20605. "Non-nil when TIMESTAMP has a time specified."
  20606. (org-element-property :hour-start timestamp))
  20607. (defun org-timestamp-format (timestamp format &optional end utc)
  20608. "Format a TIMESTAMP object into a string.
  20609. FORMAT is a format specifier to be passed to
  20610. `format-time-string'.
  20611. When optional argument END is non-nil, use end of date-range or
  20612. time-range, if possible.
  20613. When optional argument UTC is non-nil, time is be expressed as
  20614. Universal Time."
  20615. (format-time-string format (org-timestamp-to-time timestamp end)
  20616. (and utc t)))
  20617. (defun org-timestamp-split-range (timestamp &optional end)
  20618. "Extract a TIMESTAMP object from a date or time range.
  20619. END, when non-nil, means extract the end of the range.
  20620. Otherwise, extract its start.
  20621. Return a new timestamp object."
  20622. (let ((type (org-element-property :type timestamp)))
  20623. (if (memq type '(active inactive diary)) timestamp
  20624. (let ((split-ts (org-element-copy timestamp)))
  20625. ;; Set new type.
  20626. (org-element-put-property
  20627. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20628. ;; Copy start properties over end properties if END is
  20629. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20630. (let ((p-alist '((:minute-start . :minute-end)
  20631. (:hour-start . :hour-end)
  20632. (:day-start . :day-end)
  20633. (:month-start . :month-end)
  20634. (:year-start . :year-end))))
  20635. (dolist (p-cell p-alist)
  20636. (org-element-put-property
  20637. split-ts
  20638. (funcall (if end #'car #'cdr) p-cell)
  20639. (org-element-property
  20640. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20641. ;; Eventually refresh `:raw-value'.
  20642. (org-element-put-property split-ts :raw-value nil)
  20643. (org-element-put-property
  20644. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20645. (defun org-timestamp-translate (timestamp &optional boundary)
  20646. "Translate TIMESTAMP object to custom format.
  20647. Format string is defined in `org-time-stamp-custom-formats',
  20648. which see.
  20649. When optional argument BOUNDARY is non-nil, it is either the
  20650. symbol `start' or `end'. In this case, only translate the
  20651. starting or ending part of TIMESTAMP if it is a date or time
  20652. range. Otherwise, translate both parts.
  20653. Return timestamp as-is if `org-display-custom-times' is nil or if
  20654. it has a `diary' type."
  20655. (let ((type (org-element-property :type timestamp)))
  20656. (if (or (not org-display-custom-times) (eq type 'diary))
  20657. (org-element-interpret-data timestamp)
  20658. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20659. org-time-stamp-custom-formats)))
  20660. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20661. (concat (org-timestamp-format timestamp fmt)
  20662. "--"
  20663. (org-timestamp-format timestamp fmt t))
  20664. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20665. ;;; Other stuff
  20666. (defvar reftex-docstruct-symbol)
  20667. (defvar org--rds)
  20668. (defun org-reftex-citation ()
  20669. "Use reftex-citation to insert a citation into the buffer.
  20670. This looks for a line like
  20671. #+BIBLIOGRAPHY: foo plain option:-d
  20672. and derives from it that foo.bib is the bibliography file relevant
  20673. for this document. It then installs the necessary environment for RefTeX
  20674. to work in this buffer and calls `reftex-citation' to insert a citation
  20675. into the buffer.
  20676. Export of such citations to both LaTeX and HTML is handled by the contributed
  20677. package ox-bibtex by Taru Karttunen."
  20678. (interactive)
  20679. (let ((reftex-docstruct-symbol 'org--rds)
  20680. org--rds bib)
  20681. (org-with-wide-buffer
  20682. (let ((case-fold-search t)
  20683. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20684. (if (not (save-excursion
  20685. (or (re-search-forward re nil t)
  20686. (re-search-backward re nil t))))
  20687. (user-error "No bibliography defined in file")
  20688. (setq bib (concat (match-string 1) ".bib")
  20689. org--rds (list (list 'bib bib))))))
  20690. (call-interactively 'reftex-citation)))
  20691. ;;;; Functions extending outline functionality
  20692. (defun org-beginning-of-line (&optional n)
  20693. "Go to the beginning of the current visible line.
  20694. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20695. symbol `reversed', on the first attempt move to where the
  20696. headline text starts, and only move to beginning of line when the
  20697. cursor is already before the start of the text of the headline.
  20698. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20699. start of the text on the second attempt.
  20700. With argument N not nil or 1, move forward N - 1 lines first."
  20701. (interactive "^p")
  20702. (let ((origin (point))
  20703. (special (pcase org-special-ctrl-a/e
  20704. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20705. deactivate-mark)
  20706. ;; First move to a visible line.
  20707. (if (bound-and-true-p visual-line-mode)
  20708. (beginning-of-visual-line n)
  20709. (move-beginning-of-line n)
  20710. ;; `move-beginning-of-line' may leave point after invisible
  20711. ;; characters if line starts with such of these (e.g., with
  20712. ;; a link at column 0). Really move to the beginning of the
  20713. ;; current visible line.
  20714. (beginning-of-line))
  20715. (cond
  20716. ;; No special behavior. Point is already at the beginning of
  20717. ;; a line, logical or visual.
  20718. ((not special))
  20719. ;; `beginning-of-visual-line' left point before logical beginning
  20720. ;; of line: point is at the beginning of a visual line. Bail
  20721. ;; out.
  20722. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20723. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20724. ;; At a headline, special position is before the title, but
  20725. ;; after any TODO keyword or priority cookie.
  20726. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20727. (line-end-position)))
  20728. (bol (point)))
  20729. (if (eq special 'reversed)
  20730. (when (and (= origin bol) (eq last-command this-command))
  20731. (goto-char refpos))
  20732. (when (or (> origin refpos) (= origin bol))
  20733. (goto-char refpos)))))
  20734. ((and (looking-at org-list-full-item-re)
  20735. (memq (org-element-type (save-match-data (org-element-at-point)))
  20736. '(item plain-list)))
  20737. ;; Set special position at first white space character after
  20738. ;; bullet, and check-box, if any.
  20739. (let ((after-bullet
  20740. (let ((box (match-end 3)))
  20741. (cond ((not box) (match-end 1))
  20742. ((eq (char-after box) ?\s) (1+ box))
  20743. (t box)))))
  20744. (if (eq special 'reversed)
  20745. (when (and (= (point) origin) (eq last-command this-command))
  20746. (goto-char after-bullet))
  20747. (when (or (> origin after-bullet) (= (point) origin))
  20748. (goto-char after-bullet)))))
  20749. ;; No special context. Point is already at beginning of line.
  20750. (t nil))))
  20751. (defun org-end-of-line (&optional n)
  20752. "Go to the end of the line, but before ellipsis, if any.
  20753. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20754. symbol `reversed', ignore tags on the first attempt, and only
  20755. move to after the tags when the cursor is already beyond the end
  20756. of the headline.
  20757. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20758. on the second attempt.
  20759. With argument N not nil or 1, move forward N - 1 lines first."
  20760. (interactive "^p")
  20761. (let ((origin (point))
  20762. (special (pcase org-special-ctrl-a/e
  20763. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20764. deactivate-mark)
  20765. ;; First move to a visible line.
  20766. (if (bound-and-true-p visual-line-mode)
  20767. (beginning-of-visual-line n)
  20768. (move-beginning-of-line n))
  20769. (cond
  20770. ;; At a headline, with tags.
  20771. ((and special
  20772. (save-excursion
  20773. (beginning-of-line)
  20774. (let ((case-fold-search nil))
  20775. (looking-at org-complex-heading-regexp)))
  20776. (match-end 5))
  20777. (let ((tags (save-excursion
  20778. (goto-char (match-beginning 5))
  20779. (skip-chars-backward " \t")
  20780. (point)))
  20781. (visual-end (and (bound-and-true-p visual-line-mode)
  20782. (save-excursion
  20783. (end-of-visual-line)
  20784. (point)))))
  20785. ;; If `end-of-visual-line' brings us before end of line or
  20786. ;; even tags, i.e., the headline spans over multiple visual
  20787. ;; lines, move there.
  20788. (cond ((and visual-end
  20789. (< visual-end tags)
  20790. (<= origin visual-end))
  20791. (goto-char visual-end))
  20792. ((eq special 'reversed)
  20793. (if (and (= origin (line-end-position))
  20794. (eq this-command last-command))
  20795. (goto-char tags)
  20796. (end-of-line)))
  20797. (t
  20798. (if (or (< origin tags) (= origin (line-end-position)))
  20799. (goto-char tags)
  20800. (end-of-line))))))
  20801. ((bound-and-true-p visual-line-mode)
  20802. (let ((bol (line-beginning-position)))
  20803. (end-of-visual-line)
  20804. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20805. ;; end of a line, backtrack and use `end-of-line' instead.
  20806. (when (/= bol (line-beginning-position))
  20807. (goto-char bol)
  20808. (end-of-line))))
  20809. (t (end-of-line)))))
  20810. (defun org-backward-sentence (&optional _arg)
  20811. "Go to beginning of sentence, or beginning of table field.
  20812. This will call `backward-sentence' or `org-table-beginning-of-field',
  20813. depending on context."
  20814. (interactive)
  20815. (let* ((element (org-element-at-point))
  20816. (contents-begin (org-element-property :contents-begin element))
  20817. (table (org-element-lineage element '(table) t)))
  20818. (if (and table
  20819. (> (point) contents-begin)
  20820. (<= (point) (org-element-property :contents-end table)))
  20821. (call-interactively #'org-table-beginning-of-field)
  20822. (save-restriction
  20823. (when (and contents-begin
  20824. (< (point-min) contents-begin)
  20825. (> (point) contents-begin))
  20826. (narrow-to-region contents-begin
  20827. (org-element-property :contents-end element)))
  20828. (call-interactively #'backward-sentence)))))
  20829. (defun org-forward-sentence (&optional _arg)
  20830. "Go to end of sentence, or end of table field.
  20831. This will call `forward-sentence' or `org-table-end-of-field',
  20832. depending on context."
  20833. (interactive)
  20834. (if (and (org-at-heading-p)
  20835. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20836. (save-restriction
  20837. (narrow-to-region (line-beginning-position) (line-end-position))
  20838. (call-interactively #'forward-sentence))
  20839. (let* ((element (org-element-at-point))
  20840. (contents-end (org-element-property :contents-end element))
  20841. (table (org-element-lineage element '(table) t)))
  20842. (if (and table
  20843. (>= (point) (org-element-property :contents-begin table))
  20844. (< (point) contents-end))
  20845. (call-interactively #'org-table-end-of-field)
  20846. (save-restriction
  20847. (when (and contents-end
  20848. (> (point-max) contents-end)
  20849. ;; Skip blank lines between elements.
  20850. (< (org-element-property :end element)
  20851. (save-excursion (goto-char contents-end)
  20852. (skip-chars-forward " \r\t\n"))))
  20853. (narrow-to-region (org-element-property :contents-begin element)
  20854. contents-end))
  20855. ;; End of heading is considered as the end of a sentence.
  20856. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20857. (call-interactively #'forward-sentence)))))))
  20858. (defun org-kill-line (&optional _arg)
  20859. "Kill line, to tags or end of line."
  20860. (interactive)
  20861. (cond
  20862. ((or (not org-special-ctrl-k)
  20863. (bolp)
  20864. (not (org-at-heading-p)))
  20865. (when (and (get-char-property (line-end-position) 'invisible)
  20866. org-ctrl-k-protect-subtree
  20867. (or (eq org-ctrl-k-protect-subtree 'error)
  20868. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20869. (user-error
  20870. (substitute-command-keys
  20871. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20872. (call-interactively
  20873. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20874. ((org-match-line org-tag-line-re)
  20875. (let ((end (save-excursion
  20876. (goto-char (match-beginning 1))
  20877. (skip-chars-backward " \t")
  20878. (point))))
  20879. (if (<= end (point)) ;on tags part
  20880. (kill-region (point) (line-end-position))
  20881. (kill-region (point) end)))
  20882. (org-align-tags))
  20883. (t (kill-region (point) (line-end-position)))))
  20884. (defun org-yank (&optional arg)
  20885. "Yank. If the kill is a subtree, treat it specially.
  20886. This command will look at the current kill and check if is a single
  20887. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20888. cursor is at the beginning of a line or after the stars of a currently
  20889. empty headline, then the yank is handled specially. How exactly depends
  20890. on the value of the following variables.
  20891. `org-yank-folded-subtrees'
  20892. By default, this variable is non-nil, which results in
  20893. subtree(s) being folded after insertion, except if doing so
  20894. would swallow text after the yanked text.
  20895. `org-yank-adjusted-subtrees'
  20896. When non-nil (the default value is nil), the subtree will be
  20897. promoted or demoted in order to fit into the local outline tree
  20898. structure, which means that the level will be adjusted so that it
  20899. becomes the smaller one of the two *visible* surrounding headings.
  20900. Any prefix to this command will cause `yank' to be called directly with
  20901. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20902. will just
  20903. plainly yank the text as it is.
  20904. \[1] The test checks if the first non-white line is a heading
  20905. and if there are no other headings with fewer stars."
  20906. (interactive "P")
  20907. (org-yank-generic 'yank arg))
  20908. (defun org-yank-generic (command arg)
  20909. "Perform some yank-like command.
  20910. This function implements the behavior described in the `org-yank'
  20911. documentation. However, it has been generalized to work for any
  20912. interactive command with similar behavior."
  20913. ;; pretend to be command COMMAND
  20914. (setq this-command command)
  20915. (if arg
  20916. (call-interactively command)
  20917. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20918. (and (org-kill-is-subtree-p)
  20919. (or (bolp)
  20920. (and (looking-at "[ \t]*$")
  20921. (string-match
  20922. "\\`\\*+\\'"
  20923. (buffer-substring (point-at-bol) (point)))))))
  20924. swallowp)
  20925. (cond
  20926. ((and subtreep org-yank-folded-subtrees)
  20927. (let ((beg (point))
  20928. end)
  20929. (if (and subtreep org-yank-adjusted-subtrees)
  20930. (org-paste-subtree nil nil 'for-yank)
  20931. (call-interactively command))
  20932. (setq end (point))
  20933. (goto-char beg)
  20934. (when (and (bolp) subtreep
  20935. (not (setq swallowp
  20936. (org-yank-folding-would-swallow-text beg end))))
  20937. (org-with-limited-levels
  20938. (or (looking-at org-outline-regexp)
  20939. (re-search-forward org-outline-regexp-bol end t))
  20940. (while (and (< (point) end) (looking-at org-outline-regexp))
  20941. (outline-hide-subtree)
  20942. (org-cycle-show-empty-lines 'folded)
  20943. (condition-case nil
  20944. (outline-forward-same-level 1)
  20945. (error (goto-char end))))))
  20946. (when swallowp
  20947. (message
  20948. "Inserted text not folded because that would swallow text"))
  20949. (goto-char end)
  20950. (skip-chars-forward " \t\n\r")
  20951. (beginning-of-line 1)
  20952. (push-mark beg 'nomsg)))
  20953. ((and subtreep org-yank-adjusted-subtrees)
  20954. (let ((beg (point-at-bol)))
  20955. (org-paste-subtree nil nil 'for-yank)
  20956. (push-mark beg 'nomsg)))
  20957. (t
  20958. (call-interactively command))))))
  20959. (defun org-yank-folding-would-swallow-text (beg end)
  20960. "Would hide-subtree at BEG swallow any text after END?"
  20961. (let (level)
  20962. (org-with-limited-levels
  20963. (save-excursion
  20964. (goto-char beg)
  20965. (when (or (looking-at org-outline-regexp)
  20966. (re-search-forward org-outline-regexp-bol end t))
  20967. (setq level (org-outline-level)))
  20968. (goto-char end)
  20969. (skip-chars-forward " \t\r\n\v\f")
  20970. (not (or (eobp)
  20971. (and (bolp) (looking-at-p org-outline-regexp)
  20972. (<= (org-outline-level) level))))))))
  20973. (defun org-back-to-heading (&optional invisible-ok)
  20974. "Call `outline-back-to-heading', but provide a better error message."
  20975. (condition-case nil
  20976. (outline-back-to-heading invisible-ok)
  20977. (error (error "Before first headline at position %d in buffer %s"
  20978. (point) (current-buffer)))))
  20979. (defun org-before-first-heading-p ()
  20980. "Before first heading?"
  20981. (org-with-limited-levels
  20982. (save-excursion
  20983. (end-of-line)
  20984. (null (re-search-backward org-outline-regexp-bol nil t)))))
  20985. (defun org-at-heading-p (&optional ignored)
  20986. (outline-on-heading-p t))
  20987. (defun org-in-commented-heading-p (&optional no-inheritance)
  20988. "Non-nil if point is under a commented heading.
  20989. This function also checks ancestors of the current headline,
  20990. unless optional argument NO-INHERITANCE is non-nil."
  20991. (cond
  20992. ((org-before-first-heading-p) nil)
  20993. ((let ((headline (nth 4 (org-heading-components))))
  20994. (and headline
  20995. (let ((case-fold-search nil))
  20996. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  20997. headline)))))
  20998. (no-inheritance nil)
  20999. (t
  21000. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21001. (defun org-at-comment-p nil
  21002. "Is cursor in a commented line?"
  21003. (save-excursion
  21004. (save-match-data
  21005. (beginning-of-line)
  21006. (looking-at "^[ \t]*# "))))
  21007. (defun org-at-drawer-p nil
  21008. "Is cursor at a drawer keyword?"
  21009. (save-excursion
  21010. (move-beginning-of-line 1)
  21011. (looking-at org-drawer-regexp)))
  21012. (defun org-at-block-p nil
  21013. "Is cursor at a block keyword?"
  21014. (save-excursion
  21015. (move-beginning-of-line 1)
  21016. (looking-at org-block-regexp)))
  21017. (defun org-point-at-end-of-empty-headline ()
  21018. "If point is at the end of an empty headline, return t, else nil.
  21019. If the heading only contains a TODO keyword, it is still still considered
  21020. empty."
  21021. (let ((case-fold-search nil))
  21022. (and (looking-at "[ \t]*$")
  21023. org-todo-line-regexp
  21024. (save-excursion
  21025. (beginning-of-line)
  21026. (looking-at org-todo-line-regexp)
  21027. (string= (match-string 3) "")))))
  21028. (defun org-at-heading-or-item-p ()
  21029. (or (org-at-heading-p) (org-at-item-p)))
  21030. (defun org-at-target-p ()
  21031. (or (org-in-regexp org-radio-target-regexp)
  21032. (org-in-regexp org-target-regexp)))
  21033. (defun org-up-heading-all (arg)
  21034. "Move to the heading line of which the present line is a subheading.
  21035. This function considers both visible and invisible heading lines.
  21036. With argument, move up ARG levels."
  21037. (outline-up-heading arg t))
  21038. (defun org-up-heading-safe ()
  21039. "Move to the heading line of which the present line is a subheading.
  21040. This version will not throw an error. It will return the level of the
  21041. headline found, or nil if no higher level is found.
  21042. Also, this function will be a lot faster than `outline-up-heading',
  21043. because it relies on stars being the outline starters. This can really
  21044. make a significant difference in outlines with very many siblings."
  21045. (when (ignore-errors (org-back-to-heading t))
  21046. (let ((level-up (1- (funcall outline-level))))
  21047. (and (> level-up 0)
  21048. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21049. (funcall outline-level)))))
  21050. (defun org-first-sibling-p ()
  21051. "Is this heading the first child of its parents?"
  21052. (interactive)
  21053. (let ((re org-outline-regexp-bol)
  21054. level l)
  21055. (unless (org-at-heading-p t)
  21056. (user-error "Not at a heading"))
  21057. (setq level (funcall outline-level))
  21058. (save-excursion
  21059. (if (not (re-search-backward re nil t))
  21060. t
  21061. (setq l (funcall outline-level))
  21062. (< l level)))))
  21063. (defun org-goto-sibling (&optional previous)
  21064. "Goto the next sibling, even if it is invisible.
  21065. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21066. when a sibling was found. When none is found, return nil and don't
  21067. move point."
  21068. (let ((fun (if previous 're-search-backward 're-search-forward))
  21069. (pos (point))
  21070. (re org-outline-regexp-bol)
  21071. level l)
  21072. (when (ignore-errors (org-back-to-heading t))
  21073. (setq level (funcall outline-level))
  21074. (catch 'exit
  21075. (or previous (forward-char 1))
  21076. (while (funcall fun re nil t)
  21077. (setq l (funcall outline-level))
  21078. (when (< l level) (goto-char pos) (throw 'exit nil))
  21079. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21080. (goto-char pos)
  21081. nil))))
  21082. (defun org-show-siblings ()
  21083. "Show all siblings of the current headline."
  21084. (save-excursion
  21085. (while (org-goto-sibling) (org-flag-heading nil)))
  21086. (save-excursion
  21087. (while (org-goto-sibling 'previous)
  21088. (org-flag-heading nil))))
  21089. (defun org-goto-first-child ()
  21090. "Goto the first child, even if it is invisible.
  21091. Return t when a child was found. Otherwise don't move point and
  21092. return nil."
  21093. (let (level (pos (point)) (re org-outline-regexp-bol))
  21094. (when (ignore-errors (org-back-to-heading t))
  21095. (setq level (outline-level))
  21096. (forward-char 1)
  21097. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21098. (progn (goto-char (match-beginning 0)) t)
  21099. (goto-char pos) nil))))
  21100. (defun org-show-hidden-entry ()
  21101. "Show an entry where even the heading is hidden."
  21102. (save-excursion
  21103. (org-show-entry)))
  21104. (defun org-flag-heading (flag &optional entry)
  21105. "Flag the current heading. FLAG non-nil means make invisible.
  21106. When ENTRY is non-nil, show the entire entry."
  21107. (save-excursion
  21108. (org-back-to-heading t)
  21109. ;; Check if we should show the entire entry
  21110. (if (not entry)
  21111. (org-flag-region
  21112. (line-end-position 0) (line-end-position) flag 'outline)
  21113. (org-show-entry)
  21114. (save-excursion
  21115. (and (outline-next-heading)
  21116. (org-flag-heading nil))))))
  21117. (defun org-get-next-sibling ()
  21118. "Move to next heading of the same level, and return point.
  21119. If there is no such heading, return nil.
  21120. This is like outline-next-sibling, but invisible headings are ok."
  21121. (let ((level (funcall outline-level)))
  21122. (outline-next-heading)
  21123. (while (and (not (eobp)) (> (funcall outline-level) level))
  21124. (outline-next-heading))
  21125. (unless (or (eobp) (< (funcall outline-level) level))
  21126. (point))))
  21127. (defun org-get-last-sibling ()
  21128. "Move to previous heading of the same level, and return point.
  21129. If there is no such heading, return nil."
  21130. (let ((opoint (point))
  21131. (level (funcall outline-level)))
  21132. (outline-previous-heading)
  21133. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21134. (while (and (> (funcall outline-level) level)
  21135. (not (bobp)))
  21136. (outline-previous-heading))
  21137. (unless (< (funcall outline-level) level)
  21138. (point)))))
  21139. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21140. "Goto to the end of a subtree."
  21141. ;; This contains an exact copy of the original function, but it uses
  21142. ;; `org-back-to-heading', to make it work also in invisible
  21143. ;; trees. And is uses an invisible-ok argument.
  21144. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21145. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21146. ;; with many children and grandchildren etc, this can be much faster
  21147. ;; than the outline version.
  21148. (org-back-to-heading invisible-ok)
  21149. (let ((first t)
  21150. (level (funcall outline-level)))
  21151. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21152. ;; A true heading (not a plain list item), in Org
  21153. ;; This means we can easily find the end by looking
  21154. ;; only for the right number of stars. Using a regexp to do
  21155. ;; this is so much faster than using a Lisp loop.
  21156. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21157. (forward-char 1)
  21158. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21159. ;; something else, do it the slow way
  21160. (while (and (not (eobp))
  21161. (or first (> (funcall outline-level) level)))
  21162. (setq first nil)
  21163. (outline-next-heading)))
  21164. (unless to-heading
  21165. (when (memq (preceding-char) '(?\n ?\^M))
  21166. ;; Go to end of line before heading
  21167. (forward-char -1)
  21168. (when (memq (preceding-char) '(?\n ?\^M))
  21169. ;; leave blank line before heading
  21170. (forward-char -1)))))
  21171. (point))
  21172. (defun org-end-of-meta-data (&optional full)
  21173. "Skip planning line and properties drawer in current entry.
  21174. When optional argument FULL is non-nil, also skip empty lines,
  21175. clocking lines and regular drawers at the beginning of the
  21176. entry."
  21177. (org-back-to-heading t)
  21178. (forward-line)
  21179. (when (looking-at-p org-planning-line-re) (forward-line))
  21180. (when (looking-at org-property-drawer-re)
  21181. (goto-char (match-end 0))
  21182. (forward-line))
  21183. (when (and full (not (org-at-heading-p)))
  21184. (catch 'exit
  21185. (let ((end (save-excursion (outline-next-heading) (point)))
  21186. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21187. (while (not (eobp))
  21188. (cond ((looking-at-p org-drawer-regexp)
  21189. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21190. (forward-line)
  21191. (throw 'exit t)))
  21192. ((looking-at-p re) (forward-line))
  21193. (t (throw 'exit t))))))))
  21194. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21195. "Move forward to the ARG'th subheading at same level as this one.
  21196. Stop at the first and last subheadings of a superior heading.
  21197. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21198. non-nil it will also look at invisible ones."
  21199. (interactive "p")
  21200. (let ((backward? (and arg (< arg 0))))
  21201. (if (org-before-first-heading-p)
  21202. (if backward? (goto-char (point-min)) (outline-next-heading))
  21203. (org-back-to-heading invisible-ok)
  21204. (unless backward? (end-of-line)) ;do not match current headline
  21205. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21206. (f (if backward? #'re-search-backward #'re-search-forward))
  21207. (count (if arg (abs arg) 1))
  21208. (result (point)))
  21209. (while (and (> count 0)
  21210. (funcall f org-outline-regexp-bol nil 'move))
  21211. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21212. (cond ((< l level) (setq count 0))
  21213. ((and (= l level)
  21214. (or invisible-ok
  21215. (not (org-invisible-p
  21216. (line-beginning-position)))))
  21217. (cl-decf count)
  21218. (when (= l level) (setq result (point)))))))
  21219. (goto-char result))
  21220. (beginning-of-line))))
  21221. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21222. "Move backward to the ARG'th subheading at same level as this one.
  21223. Stop at the first and last subheadings of a superior heading."
  21224. (interactive "p")
  21225. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21226. (defun org-next-visible-heading (arg)
  21227. "Move to the next visible heading.
  21228. This function wraps `outline-next-visible-heading' with
  21229. `org-with-limited-levels' in order to skip over inline tasks and
  21230. respect customization of `org-odd-levels-only'."
  21231. (interactive "p")
  21232. (org-with-limited-levels
  21233. (outline-next-visible-heading arg)))
  21234. (defun org-previous-visible-heading (arg)
  21235. "Move to the previous visible heading.
  21236. This function wraps `outline-previous-visible-heading' with
  21237. `org-with-limited-levels' in order to skip over inline tasks and
  21238. respect customization of `org-odd-levels-only'."
  21239. (interactive "p")
  21240. (org-with-limited-levels
  21241. (outline-previous-visible-heading arg)))
  21242. (defun org-forward-paragraph ()
  21243. "Move forward to beginning of next paragraph or equivalent.
  21244. The function moves point to the beginning of the next visible
  21245. structural element, which can be a paragraph, a table, a list
  21246. item, etc. It also provides some special moves for convenience:
  21247. - On an affiliated keyword, jump to the beginning of the
  21248. relative element.
  21249. - On an item or a footnote definition, move to the second
  21250. element inside, if any.
  21251. - On a table or a property drawer, jump after it.
  21252. - On a verse or source block, stop after blank lines."
  21253. (interactive)
  21254. (unless (eobp)
  21255. (let* ((deactivate-mark nil)
  21256. (element (org-element-at-point))
  21257. (type (org-element-type element))
  21258. (post-affiliated (org-element-property :post-affiliated element))
  21259. (contents-begin (org-element-property :contents-begin element))
  21260. (contents-end (org-element-property :contents-end element))
  21261. (end (let ((end (org-element-property :end element)) (parent element))
  21262. (while (and (setq parent (org-element-property :parent parent))
  21263. (= (org-element-property :contents-end parent) end))
  21264. (setq end (org-element-property :end parent)))
  21265. end)))
  21266. (cond ((not element)
  21267. (skip-chars-forward " \r\t\n")
  21268. (or (eobp) (beginning-of-line)))
  21269. ;; On affiliated keywords, move to element's beginning.
  21270. ((< (point) post-affiliated)
  21271. (goto-char post-affiliated))
  21272. ;; At a table row, move to the end of the table. Similarly,
  21273. ;; at a node property, move to the end of the property
  21274. ;; drawer.
  21275. ((memq type '(node-property table-row))
  21276. (goto-char (org-element-property
  21277. :end (org-element-property :parent element))))
  21278. ((memq type '(property-drawer table)) (goto-char end))
  21279. ;; Consider blank lines as separators in verse and source
  21280. ;; blocks to ease editing.
  21281. ((memq type '(src-block verse-block))
  21282. (when (eq type 'src-block)
  21283. (setq contents-end
  21284. (save-excursion (goto-char end)
  21285. (skip-chars-backward " \r\t\n")
  21286. (line-beginning-position))))
  21287. (beginning-of-line)
  21288. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21289. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21290. (goto-char end)
  21291. (skip-chars-forward " \r\t\n")
  21292. (if (= (point) contents-end) (goto-char end)
  21293. (beginning-of-line))))
  21294. ;; With no contents, just skip element.
  21295. ((not contents-begin) (goto-char end))
  21296. ;; If contents are invisible, skip the element altogether.
  21297. ((org-invisible-p (line-end-position))
  21298. (cl-case type
  21299. (headline
  21300. (org-with-limited-levels (outline-next-visible-heading 1)))
  21301. ;; At a plain list, make sure we move to the next item
  21302. ;; instead of skipping the whole list.
  21303. (plain-list (forward-char)
  21304. (org-forward-paragraph))
  21305. (otherwise (goto-char end))))
  21306. ((>= (point) contents-end) (goto-char end))
  21307. ((>= (point) contents-begin)
  21308. ;; This can only happen on paragraphs and plain lists.
  21309. (cl-case type
  21310. (paragraph (goto-char end))
  21311. ;; At a plain list, try to move to second element in
  21312. ;; first item, if possible.
  21313. (plain-list (end-of-line)
  21314. (org-forward-paragraph))))
  21315. ;; When contents start on the middle of a line (e.g. in
  21316. ;; items and footnote definitions), try to reach first
  21317. ;; element starting after current line.
  21318. ((> (line-end-position) contents-begin)
  21319. (end-of-line)
  21320. (org-forward-paragraph))
  21321. (t (goto-char contents-begin))))))
  21322. (defun org-backward-paragraph ()
  21323. "Move backward to start of previous paragraph or equivalent.
  21324. The function moves point to the beginning of the current
  21325. structural element, which can be a paragraph, a table, a list
  21326. item, etc., or to the beginning of the previous visible one if
  21327. point is already there. It also provides some special moves for
  21328. convenience:
  21329. - On an affiliated keyword, jump to the first one.
  21330. - On a table or a property drawer, move to its beginning.
  21331. - On comment, example, export, src and verse blocks, stop
  21332. before blank lines."
  21333. (interactive)
  21334. (unless (bobp)
  21335. (let* ((deactivate-mark nil)
  21336. (element (org-element-at-point))
  21337. (type (org-element-type element))
  21338. (contents-end (org-element-property :contents-end element))
  21339. (post-affiliated (org-element-property :post-affiliated element))
  21340. (begin (org-element-property :begin element))
  21341. (special? ;blocks handled specially
  21342. (memq type '(comment-block example-block export-block src-block
  21343. verse-block)))
  21344. (contents-begin
  21345. (if special?
  21346. ;; These types have no proper contents. Fake line
  21347. ;; below the block opening line as contents beginning.
  21348. (save-excursion (goto-char begin) (line-beginning-position 2))
  21349. (org-element-property :contents-begin element))))
  21350. (cond
  21351. ((not element) (goto-char (point-min)))
  21352. ((= (point) begin)
  21353. (backward-char)
  21354. (org-backward-paragraph))
  21355. ((<= (point) post-affiliated) (goto-char begin))
  21356. ;; Special behavior: on a table or a property drawer, move to
  21357. ;; its beginning.
  21358. ((memq type '(node-property table-row))
  21359. (goto-char (org-element-property
  21360. :post-affiliated (org-element-property :parent element))))
  21361. (special?
  21362. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21363. ;; Inside a verse block, see blank lines as paragraph
  21364. ;; separators.
  21365. (let ((origin (point)))
  21366. (skip-chars-backward " \r\t\n" contents-begin)
  21367. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21368. (skip-chars-forward " \r\t\n" origin)
  21369. (if (= (point) origin) (goto-char contents-begin)
  21370. (beginning-of-line))))))
  21371. ((eq type 'paragraph) (goto-char contents-begin)
  21372. ;; When at first paragraph in an item or a footnote definition,
  21373. ;; move directly to beginning of line.
  21374. (let ((parent-contents
  21375. (org-element-property
  21376. :contents-begin (org-element-property :parent element))))
  21377. (when (and parent-contents (= parent-contents contents-begin))
  21378. (beginning-of-line))))
  21379. ;; At the end of a greater element, move to the beginning of
  21380. ;; the last element within.
  21381. ((and contents-end (>= (point) contents-end))
  21382. (goto-char (1- contents-end))
  21383. (org-backward-paragraph))
  21384. (t (goto-char (or post-affiliated begin))))
  21385. ;; Ensure we never leave point invisible.
  21386. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21387. (defun org-forward-element ()
  21388. "Move forward by one element.
  21389. Move to the next element at the same level, when possible."
  21390. (interactive)
  21391. (cond ((eobp) (user-error "Cannot move further down"))
  21392. ((org-with-limited-levels (org-at-heading-p))
  21393. (let ((origin (point)))
  21394. (goto-char (org-end-of-subtree nil t))
  21395. (unless (org-with-limited-levels (org-at-heading-p))
  21396. (goto-char origin)
  21397. (user-error "Cannot move further down"))))
  21398. (t
  21399. (let* ((elem (org-element-at-point))
  21400. (end (org-element-property :end elem))
  21401. (parent (org-element-property :parent elem)))
  21402. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21403. (goto-char (org-element-property :end parent)))
  21404. ((integer-or-marker-p end) (goto-char end))
  21405. (t (message "No element at point")))))))
  21406. (defun org-backward-element ()
  21407. "Move backward by one element.
  21408. Move to the previous element at the same level, when possible."
  21409. (interactive)
  21410. (cond ((bobp) (user-error "Cannot move further up"))
  21411. ((org-with-limited-levels (org-at-heading-p))
  21412. ;; At a headline, move to the previous one, if any, or stay
  21413. ;; here.
  21414. (let ((origin (point)))
  21415. (org-with-limited-levels (org-backward-heading-same-level 1))
  21416. ;; When current headline has no sibling above, move to its
  21417. ;; parent.
  21418. (when (= (point) origin)
  21419. (or (org-with-limited-levels (org-up-heading-safe))
  21420. (progn (goto-char origin)
  21421. (user-error "Cannot move further up"))))))
  21422. (t
  21423. (let* ((elem (org-element-at-point))
  21424. (beg (org-element-property :begin elem)))
  21425. (cond
  21426. ;; Move to beginning of current element if point isn't
  21427. ;; there already.
  21428. ((null beg) (message "No element at point"))
  21429. ((/= (point) beg) (goto-char beg))
  21430. (t (goto-char beg)
  21431. (skip-chars-backward " \r\t\n")
  21432. (unless (bobp)
  21433. (let ((prev (org-element-at-point)))
  21434. (goto-char (org-element-property :begin prev))
  21435. (while (and (setq prev (org-element-property :parent prev))
  21436. (<= (org-element-property :end prev) beg))
  21437. (goto-char (org-element-property :begin prev)))))))))))
  21438. (defun org-up-element ()
  21439. "Move to upper element."
  21440. (interactive)
  21441. (if (org-with-limited-levels (org-at-heading-p))
  21442. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21443. (let* ((elem (org-element-at-point))
  21444. (parent (org-element-property :parent elem)))
  21445. (if parent (goto-char (org-element-property :begin parent))
  21446. (if (org-with-limited-levels (org-before-first-heading-p))
  21447. (user-error "No surrounding element")
  21448. (org-with-limited-levels (org-back-to-heading)))))))
  21449. (defun org-down-element ()
  21450. "Move to inner element."
  21451. (interactive)
  21452. (let ((element (org-element-at-point)))
  21453. (cond
  21454. ((memq (org-element-type element) '(plain-list table))
  21455. (goto-char (org-element-property :contents-begin element))
  21456. (forward-char))
  21457. ((memq (org-element-type element) org-element-greater-elements)
  21458. ;; If contents are hidden, first disclose them.
  21459. (when (org-invisible-p (line-end-position)) (org-cycle))
  21460. (goto-char (or (org-element-property :contents-begin element)
  21461. (user-error "No content for this element"))))
  21462. (t (user-error "No inner element")))))
  21463. (defun org-drag-element-backward ()
  21464. "Move backward element at point."
  21465. (interactive)
  21466. (let ((elem (or (org-element-at-point)
  21467. (user-error "No element at point"))))
  21468. (if (eq (org-element-type elem) 'headline)
  21469. ;; Preserve point when moving a whole tree, even if point was
  21470. ;; on blank lines below the headline.
  21471. (let ((offset (skip-chars-backward " \t\n")))
  21472. (unwind-protect (org-move-subtree-up)
  21473. (forward-char (- offset))))
  21474. (let ((prev-elem
  21475. (save-excursion
  21476. (goto-char (org-element-property :begin elem))
  21477. (skip-chars-backward " \r\t\n")
  21478. (unless (bobp)
  21479. (let* ((beg (org-element-property :begin elem))
  21480. (prev (org-element-at-point))
  21481. (up prev))
  21482. (while (and (setq up (org-element-property :parent up))
  21483. (<= (org-element-property :end up) beg))
  21484. (setq prev up))
  21485. prev)))))
  21486. ;; Error out if no previous element or previous element is
  21487. ;; a parent of the current one.
  21488. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21489. (user-error "Cannot drag element backward")
  21490. (let ((pos (point)))
  21491. (org-element-swap-A-B prev-elem elem)
  21492. (goto-char (+ (org-element-property :begin prev-elem)
  21493. (- pos (org-element-property :begin elem))))))))))
  21494. (defun org-drag-element-forward ()
  21495. "Move forward element at point."
  21496. (interactive)
  21497. (let* ((pos (point))
  21498. (elem (or (org-element-at-point)
  21499. (user-error "No element at point"))))
  21500. (when (= (point-max) (org-element-property :end elem))
  21501. (user-error "Cannot drag element forward"))
  21502. (goto-char (org-element-property :end elem))
  21503. (let ((next-elem (org-element-at-point)))
  21504. (when (or (org-element-nested-p elem next-elem)
  21505. (and (eq (org-element-type next-elem) 'headline)
  21506. (not (eq (org-element-type elem) 'headline))))
  21507. (goto-char pos)
  21508. (user-error "Cannot drag element forward"))
  21509. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21510. ;; body's length (without final blanks) and by the length of
  21511. ;; blanks between ELEM and NEXT-ELEM.
  21512. (let ((size-next (- (save-excursion
  21513. (goto-char (org-element-property :end next-elem))
  21514. (skip-chars-backward " \r\t\n")
  21515. (forward-line)
  21516. ;; Small correction if buffer doesn't end
  21517. ;; with a newline character.
  21518. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21519. (org-element-property :begin next-elem)))
  21520. (size-blank (- (org-element-property :end elem)
  21521. (save-excursion
  21522. (goto-char (org-element-property :end elem))
  21523. (skip-chars-backward " \r\t\n")
  21524. (forward-line)
  21525. (point)))))
  21526. (org-element-swap-A-B elem next-elem)
  21527. (goto-char (+ pos size-next size-blank))))))
  21528. (defun org-drag-line-forward (arg)
  21529. "Drag the line at point ARG lines forward."
  21530. (interactive "p")
  21531. (dotimes (_ (abs arg))
  21532. (let ((c (current-column)))
  21533. (if (< 0 arg)
  21534. (progn
  21535. (beginning-of-line 2)
  21536. (transpose-lines 1)
  21537. (beginning-of-line 0))
  21538. (transpose-lines 1)
  21539. (beginning-of-line -1))
  21540. (org-move-to-column c))))
  21541. (defun org-drag-line-backward (arg)
  21542. "Drag the line at point ARG lines backward."
  21543. (interactive "p")
  21544. (org-drag-line-forward (- arg)))
  21545. (defun org-mark-element ()
  21546. "Put point at beginning of this element, mark at end.
  21547. Interactively, if this command is repeated or (in Transient Mark
  21548. mode) if the mark is active, it marks the next element after the
  21549. ones already marked."
  21550. (interactive)
  21551. (let (deactivate-mark)
  21552. (if (and (called-interactively-p 'any)
  21553. (or (and (eq last-command this-command) (mark t))
  21554. (and transient-mark-mode mark-active)))
  21555. (set-mark
  21556. (save-excursion
  21557. (goto-char (mark))
  21558. (goto-char (org-element-property :end (org-element-at-point)))))
  21559. (let ((element (org-element-at-point)))
  21560. (end-of-line)
  21561. (push-mark (org-element-property :end element) t t)
  21562. (goto-char (org-element-property :begin element))))))
  21563. (defun org-narrow-to-element ()
  21564. "Narrow buffer to current element."
  21565. (interactive)
  21566. (let ((elem (org-element-at-point)))
  21567. (cond
  21568. ((eq (car elem) 'headline)
  21569. (narrow-to-region
  21570. (org-element-property :begin elem)
  21571. (org-element-property :end elem)))
  21572. ((memq (car elem) org-element-greater-elements)
  21573. (narrow-to-region
  21574. (org-element-property :contents-begin elem)
  21575. (org-element-property :contents-end elem)))
  21576. (t
  21577. (narrow-to-region
  21578. (org-element-property :begin elem)
  21579. (org-element-property :end elem))))))
  21580. (defun org-transpose-element ()
  21581. "Transpose current and previous elements, keeping blank lines between.
  21582. Point is moved after both elements."
  21583. (interactive)
  21584. (org-skip-whitespace)
  21585. (let ((end (org-element-property :end (org-element-at-point))))
  21586. (org-drag-element-backward)
  21587. (goto-char end)))
  21588. (defun org-unindent-buffer ()
  21589. "Un-indent the visible part of the buffer.
  21590. Relative indentation (between items, inside blocks, etc.) isn't
  21591. modified."
  21592. (interactive)
  21593. (unless (eq major-mode 'org-mode)
  21594. (user-error "Cannot un-indent a buffer not in Org mode"))
  21595. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21596. (unindent-tree
  21597. (lambda (contents)
  21598. (dolist (element (reverse contents))
  21599. (if (memq (org-element-type element) '(headline section))
  21600. (funcall unindent-tree (org-element-contents element))
  21601. (save-excursion
  21602. (save-restriction
  21603. (narrow-to-region
  21604. (org-element-property :begin element)
  21605. (org-element-property :end element))
  21606. (org-do-remove-indentation))))))))
  21607. (funcall unindent-tree (org-element-contents parse-tree))))
  21608. (defun org-make-options-regexp (kwds &optional extra)
  21609. "Make a regular expression for keyword lines.
  21610. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21611. when non-nil, is a regexp matching keywords names."
  21612. (concat "^[ \t]*#\\+\\("
  21613. (regexp-opt kwds)
  21614. (and extra (concat (and kwds "\\|") extra))
  21615. "\\):[ \t]*\\(.*\\)"))
  21616. ;;; Finish up
  21617. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21618. (lambda () (add-hook 'change-major-mode-hook
  21619. 'org-show-all 'append 'local)))
  21620. (provide 'org)
  21621. (run-hooks 'org-load-hook)
  21622. ;;; org.el ends here