org.el 943 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938
  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-2017 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: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocktable-shift "org-clock" (dir n))
  118. (declare-function org-element-at-point "org-element" ())
  119. (declare-function org-element-cache-refresh "org-element" (pos))
  120. (declare-function org-element-cache-reset "org-element" (&optional all))
  121. (declare-function org-element-contents "org-element" (element))
  122. (declare-function org-element-context "org-element" (&optional element))
  123. (declare-function org-element-copy "org-element" (datum))
  124. (declare-function org-element-interpret-data "org-element" (data))
  125. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  126. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  127. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  128. (declare-function org-element-property "org-element" (property element))
  129. (declare-function org-element-put-property "org-element" (element property value))
  130. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  131. (declare-function org-element-type "org-element" (element))
  132. (declare-function org-element-update-syntax "org-element" ())
  133. (declare-function org-id-find-id-file "org-id" (id))
  134. (declare-function org-id-get-create "org-id" (&optional force))
  135. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  136. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  137. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  138. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  139. (declare-function org-table-align "org-table" ())
  140. (declare-function org-table-begin "org-table" (&optional table-type))
  141. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  142. (declare-function org-table-blank-field "org-table" ())
  143. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  144. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  145. (declare-function org-table-cut-region "org-table" (beg end))
  146. (declare-function org-table-edit-field "org-table" (arg))
  147. (declare-function org-table-end "org-table" (&optional table-type))
  148. (declare-function org-table-end-of-field "org-table" (&optional n))
  149. (declare-function org-table-insert-row "org-table" (&optional arg))
  150. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  151. (declare-function org-table-maybe-eval-formula "org-table" ())
  152. (declare-function org-table-maybe-recalculate-line "org-table" ())
  153. (declare-function org-table-next-row "org-table" ())
  154. (declare-function org-table-paste-rectangle "org-table" ())
  155. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  156. (declare-function org-table-wrap-region "org-table" (arg))
  157. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  158. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  159. (declare-function orgtbl-mode "org-table" (&optional arg))
  160. (declare-function org-export-get-backend "ox" (name))
  161. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  162. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  163. (defsubst org-uniquify (list)
  164. "Non-destructively remove duplicate elements from LIST."
  165. (let ((res (copy-sequence list))) (delete-dups res)))
  166. (defsubst org-get-at-bol (property)
  167. "Get text property PROPERTY at the beginning of line."
  168. (get-text-property (point-at-bol) property))
  169. (defsubst org-trim (s &optional keep-lead)
  170. "Remove whitespace at the beginning and the end of string S.
  171. When optional argument KEEP-LEAD is non-nil, removing blank lines
  172. at the beginning of the string does not affect leading indentation."
  173. (replace-regexp-in-string
  174. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  175. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  176. ;; load languages based on value of `org-babel-load-languages'
  177. (defvar org-babel-load-languages)
  178. ;;;###autoload
  179. (defun org-babel-do-load-languages (sym value)
  180. "Load the languages defined in `org-babel-load-languages'."
  181. (set-default sym value)
  182. (dolist (pair org-babel-load-languages)
  183. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  184. (if active
  185. (require (intern (concat "ob-" lang)))
  186. (funcall 'fmakunbound
  187. (intern (concat "org-babel-execute:" lang)))
  188. (funcall 'fmakunbound
  189. (intern (concat "org-babel-expand-body:" lang)))))))
  190. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  191. ;;;###autoload
  192. (defun org-babel-load-file (file &optional compile)
  193. "Load Emacs Lisp source code blocks in the Org FILE.
  194. This function exports the source code using `org-babel-tangle'
  195. and then loads the resulting file using `load-file'. With prefix
  196. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  197. file to byte-code before it is loaded."
  198. (interactive "fFile to load: \nP")
  199. (let* ((age (lambda (file)
  200. (float-time
  201. (time-subtract (current-time)
  202. (nth 5 (or (file-attributes (file-truename file))
  203. (file-attributes file)))))))
  204. (base-name (file-name-sans-extension file))
  205. (exported-file (concat base-name ".el")))
  206. ;; tangle if the Org file is newer than the elisp file
  207. (unless (and (file-exists-p exported-file)
  208. (> (funcall age file) (funcall age exported-file)))
  209. ;; Tangle-file traversal returns reversed list of tangled files
  210. ;; and we want to evaluate the first target.
  211. (setq exported-file
  212. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  213. (message "%s %s"
  214. (if compile
  215. (progn (byte-compile-file exported-file 'load)
  216. "Compiled and loaded")
  217. (progn (load-file exported-file) "Loaded"))
  218. exported-file)))
  219. (defcustom org-babel-load-languages '((emacs-lisp . t))
  220. "Languages which can be evaluated in Org buffers.
  221. This list can be used to load support for any of the languages
  222. below, note that each language will depend on a different set of
  223. system executables and/or Emacs modes. When a language is
  224. \"loaded\", then code blocks in that language can be evaluated
  225. with `org-babel-execute-src-block' bound by default to C-c
  226. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  227. be set to remove code block evaluation from the C-c C-c
  228. keybinding. By default only Emacs Lisp (which has no
  229. requirements) is loaded."
  230. :group 'org-babel
  231. :set 'org-babel-do-load-languages
  232. :version "24.1"
  233. :type '(alist :tag "Babel Languages"
  234. :key-type
  235. (choice
  236. (const :tag "Awk" awk)
  237. (const :tag "C" C)
  238. (const :tag "R" R)
  239. (const :tag "Asymptote" asymptote)
  240. (const :tag "Calc" calc)
  241. (const :tag "Clojure" clojure)
  242. (const :tag "CSS" css)
  243. (const :tag "Ditaa" ditaa)
  244. (const :tag "Dot" dot)
  245. (const :tag "Emacs Lisp" emacs-lisp)
  246. (const :tag "Forth" forth)
  247. (const :tag "Fortran" fortran)
  248. (const :tag "Gnuplot" gnuplot)
  249. (const :tag "Haskell" haskell)
  250. (const :tag "hledger" hledger)
  251. (const :tag "IO" io)
  252. (const :tag "J" J)
  253. (const :tag "Java" java)
  254. (const :tag "Javascript" js)
  255. (const :tag "LaTeX" latex)
  256. (const :tag "Ledger" ledger)
  257. (const :tag "Lilypond" lilypond)
  258. (const :tag "Lisp" lisp)
  259. (const :tag "Makefile" makefile)
  260. (const :tag "Maxima" maxima)
  261. (const :tag "Matlab" matlab)
  262. (const :tag "Mscgen" mscgen)
  263. (const :tag "Ocaml" ocaml)
  264. (const :tag "Octave" octave)
  265. (const :tag "Org" org)
  266. (const :tag "Perl" perl)
  267. (const :tag "Pico Lisp" picolisp)
  268. (const :tag "PlantUML" plantuml)
  269. (const :tag "Python" python)
  270. (const :tag "Ruby" ruby)
  271. (const :tag "Sass" sass)
  272. (const :tag "Scala" scala)
  273. (const :tag "Scheme" scheme)
  274. (const :tag "Screen" screen)
  275. (const :tag "Shell Script" shell)
  276. (const :tag "Shen" shen)
  277. (const :tag "Sql" sql)
  278. (const :tag "Sqlite" sqlite)
  279. (const :tag "Stan" stan)
  280. (const :tag "ebnf2ps" ebnf2ps))
  281. :value-type (boolean :tag "Activate" :value t)))
  282. ;;;; Customization variables
  283. (defcustom org-clone-delete-id nil
  284. "Remove ID property of clones of a subtree.
  285. When non-nil, clones of a subtree don't inherit the ID property.
  286. Otherwise they inherit the ID property with a new unique
  287. identifier."
  288. :type 'boolean
  289. :version "24.1"
  290. :group 'org-id)
  291. ;;; Version
  292. (org-check-version)
  293. ;;;###autoload
  294. (defun org-version (&optional here full message)
  295. "Show the Org version.
  296. Interactively, or when MESSAGE is non-nil, show it in echo area.
  297. With prefix argument, or when HERE is non-nil, insert it at point.
  298. In non-interactive uses, a reduced version string is output unless
  299. FULL is given."
  300. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  301. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  302. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  303. (load-suffixes (list ".el"))
  304. (org-install-dir
  305. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  306. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  307. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  308. (let* ((load-suffixes save-load-suffixes)
  309. (release (org-release))
  310. (git-version (org-git-version))
  311. (version (format "Org mode version %s (%s @ %s)"
  312. release
  313. git-version
  314. (if org-install-dir
  315. (if (string= org-dir org-install-dir)
  316. org-install-dir
  317. (concat "mixed installation! "
  318. org-install-dir
  319. " and "
  320. org-dir))
  321. "org-loaddefs.el can not be found!")))
  322. (version1 (if full version release)))
  323. (when here (insert version1))
  324. (when message (message "%s" version1))
  325. version1)))
  326. (defconst org-version (org-version))
  327. ;;; Syntax Constants
  328. ;;;; Block
  329. (defconst org-block-regexp
  330. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  331. "Regular expression for hiding blocks.")
  332. (defconst org-dblock-start-re
  333. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  334. "Matches the start line of a dynamic block, with parameters.")
  335. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  336. "Matches the end of a dynamic block.")
  337. ;;;; Clock and Planning
  338. (defconst org-clock-string "CLOCK:"
  339. "String used as prefix for timestamps clocking work hours on an item.")
  340. (defvar org-closed-string "CLOSED:"
  341. "String used as the prefix for timestamps logging closing a TODO entry.")
  342. (defvar org-deadline-string "DEADLINE:"
  343. "String to mark deadline entries.
  344. \\<org-mode-map>
  345. A deadline is this string, followed by a time stamp. It must be
  346. a word, terminated by a colon. You can insert a schedule keyword
  347. and a timestamp with `\\[org-deadline]'.")
  348. (defvar org-scheduled-string "SCHEDULED:"
  349. "String to mark scheduled TODO entries.
  350. \\<org-mode-map>
  351. A schedule is this string, followed by a time stamp. It must be
  352. a word, terminated by a colon. You can insert a schedule keyword
  353. and a timestamp with `\\[org-schedule]'.")
  354. (defconst org-ds-keyword-length
  355. (+ 2
  356. (apply #'max
  357. (mapcar #'length
  358. (list org-deadline-string org-scheduled-string
  359. org-clock-string org-closed-string))))
  360. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  361. (defconst org-planning-line-re
  362. (concat "^[ \t]*"
  363. (regexp-opt
  364. (list org-closed-string org-deadline-string org-scheduled-string)
  365. t))
  366. "Matches a line with planning info.
  367. Matched keyword is in group 1.")
  368. (defconst org-clock-line-re
  369. (concat "^[ \t]*" org-clock-string)
  370. "Matches a line with clock info.")
  371. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  372. "Matches the DEADLINE keyword.")
  373. (defconst org-deadline-time-regexp
  374. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  375. "Matches the DEADLINE keyword together with a time stamp.")
  376. (defconst org-deadline-time-hour-regexp
  377. (concat "\\<" org-deadline-string
  378. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  379. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  380. (defconst org-deadline-line-regexp
  381. (concat "\\<\\(" org-deadline-string "\\).*")
  382. "Matches the DEADLINE keyword and the rest of the line.")
  383. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  384. "Matches the SCHEDULED keyword.")
  385. (defconst org-scheduled-time-regexp
  386. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  387. "Matches the SCHEDULED keyword together with a time stamp.")
  388. (defconst org-scheduled-time-hour-regexp
  389. (concat "\\<" org-scheduled-string
  390. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  391. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  392. (defconst org-closed-time-regexp
  393. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  394. "Matches the CLOSED keyword together with a time stamp.")
  395. (defconst org-keyword-time-regexp
  396. (concat "\\<"
  397. (regexp-opt
  398. (list org-scheduled-string org-deadline-string org-closed-string
  399. org-clock-string)
  400. t)
  401. " *[[<]\\([^]>]+\\)[]>]")
  402. "Matches any of the 4 keywords, together with the time stamp.")
  403. (defconst org-keyword-time-not-clock-regexp
  404. (concat
  405. "\\<"
  406. (regexp-opt
  407. (list org-scheduled-string org-deadline-string org-closed-string) t)
  408. " *[[<]\\([^]>]+\\)[]>]")
  409. "Matches any of the 3 keywords, together with the time stamp.")
  410. (defconst org-maybe-keyword-time-regexp
  411. (concat "\\(\\<"
  412. (regexp-opt
  413. (list org-scheduled-string org-deadline-string org-closed-string
  414. org-clock-string)
  415. t)
  416. "\\)?"
  417. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  418. "\\|"
  419. "<%%([^\r\n>]*>\\)")
  420. "Matches a timestamp, possibly preceded by a keyword.")
  421. (defconst org-all-time-keywords
  422. (mapcar (lambda (w) (substring w 0 -1))
  423. (list org-scheduled-string org-deadline-string
  424. org-clock-string org-closed-string))
  425. "List of time keywords.")
  426. ;;;; Drawer
  427. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  428. "Matches first or last line of a hidden block.
  429. Group 1 contains drawer's name or \"END\".")
  430. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  431. "Regular expression matching the first line of a property drawer.")
  432. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  433. "Regular expression matching the last line of a property drawer.")
  434. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  435. "Regular expression matching the first line of a clock drawer.")
  436. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  437. "Regular expression matching the last line of a clock drawer.")
  438. (defconst org-property-drawer-re
  439. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  440. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  441. "[ \t]*:END:[ \t]*$")
  442. "Matches an entire property drawer.")
  443. (defconst org-clock-drawer-re
  444. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  445. org-clock-drawer-end-re "\\)\n?")
  446. "Matches an entire clock drawer.")
  447. ;;;; Headline
  448. (defconst org-heading-keyword-regexp-format
  449. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  450. "Printf format for a regexp matching a headline with some keyword.
  451. This regexp will match the headline of any node which has the
  452. exact keyword that is put into the format. The keyword isn't in
  453. any group by default, but the stars and the body are.")
  454. (defconst org-heading-keyword-maybe-regexp-format
  455. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  456. "Printf format for a regexp matching a headline, possibly with some keyword.
  457. This regexp can match any headline with the specified keyword, or
  458. without a keyword. The keyword isn't in any group by default,
  459. but the stars and the body are.")
  460. (defconst org-archive-tag "ARCHIVE"
  461. "The tag that marks a subtree as archived.
  462. An archived subtree does not open during visibility cycling, and does
  463. not contribute to the agenda listings.")
  464. (defconst org-comment-string "COMMENT"
  465. "Entries starting with this keyword will never be exported.
  466. \\<org-mode-map>
  467. An entry can be toggled between COMMENT and normal with
  468. `\\[org-toggle-comment]'.")
  469. ;;;; LaTeX Environments and Fragments
  470. (defconst org-latex-regexps
  471. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  472. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  473. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  474. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  475. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  476. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  477. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  478. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  479. "Regular expressions for matching embedded LaTeX.")
  480. ;;;; Node Property
  481. (defconst org-effort-property "Effort"
  482. "The property that is being used to keep track of effort estimates.
  483. Effort estimates given in this property need to have the format H:MM.")
  484. ;;;; Table
  485. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  486. "Detect an org-type or table-type table.")
  487. (defconst org-table-line-regexp "^[ \t]*|"
  488. "Detect an org-type table line.")
  489. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  490. "Detect an org-type table line.")
  491. (defconst org-table-hline-regexp "^[ \t]*|-"
  492. "Detect an org-type table hline.")
  493. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  494. "Detect a table-type table hline.")
  495. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  496. "Detect the first line outside a table when searching from within it.
  497. This works for both table types.")
  498. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  499. "Detect a #+TBLFM line.")
  500. ;;;; Timestamp
  501. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  502. "Regular expression for fast time stamp matching.")
  503. (defconst org-ts-regexp-inactive
  504. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  505. "Regular expression for fast inactive time stamp matching.")
  506. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  507. "Regular expression for fast time stamp matching.")
  508. (defconst org-ts-regexp0
  509. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  510. "Regular expression matching time strings for analysis.
  511. This one does not require the space after the date, so it can be used
  512. on a string that terminates immediately after the date.")
  513. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  514. "Regular expression matching time strings for analysis.")
  515. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  516. "Regular expression matching time stamps, with groups.")
  517. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  518. "Regular expression matching time stamps (also [..]), with groups.")
  519. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  520. "Regular expression matching a time stamp range.")
  521. (defconst org-tr-regexp-both
  522. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  523. "Regular expression matching a time stamp range.")
  524. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  525. org-ts-regexp "\\)?")
  526. "Regular expression matching a time stamp or time stamp range.")
  527. (defconst org-tsr-regexp-both
  528. (concat org-ts-regexp-both "\\(--?-?"
  529. org-ts-regexp-both "\\)?")
  530. "Regular expression matching a time stamp or time stamp range.
  531. The time stamps may be either active or inactive.")
  532. (defconst org-repeat-re
  533. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  534. "Regular expression for specifying repeated events.
  535. After a match, group 1 contains the repeat expression.")
  536. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  537. "Formats for `format-time-string' which are used for time stamps.")
  538. ;;; The custom variables
  539. (defgroup org nil
  540. "Outline-based notes management and organizer."
  541. :tag "Org"
  542. :group 'outlines
  543. :group 'calendar)
  544. (defcustom org-mode-hook nil
  545. "Mode hook for Org mode, run after the mode was turned on."
  546. :group 'org
  547. :type 'hook)
  548. (defcustom org-load-hook nil
  549. "Hook that is run after org.el has been loaded."
  550. :group 'org
  551. :type 'hook)
  552. (defcustom org-log-buffer-setup-hook nil
  553. "Hook that is run after an Org log buffer is created."
  554. :group 'org
  555. :version "24.1"
  556. :type 'hook)
  557. (defvar org-modules) ; defined below
  558. (defvar org-modules-loaded nil
  559. "Have the modules been loaded already?")
  560. (defun org-load-modules-maybe (&optional force)
  561. "Load all extensions listed in `org-modules'."
  562. (when (or force (not org-modules-loaded))
  563. (dolist (ext org-modules)
  564. (condition-case nil (require ext)
  565. (error (message "Problems while trying to load feature `%s'" ext))))
  566. (setq org-modules-loaded t)))
  567. (defun org-set-modules (var value)
  568. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  569. (set var value)
  570. (when (featurep 'org)
  571. (org-load-modules-maybe 'force)
  572. (org-element-cache-reset 'all)))
  573. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  574. "Modules that should always be loaded together with org.el.
  575. If a description starts with <C>, the file is not part of Emacs
  576. and loading it will require that you have downloaded and properly
  577. installed the Org mode distribution.
  578. You can also use this system to load external packages (i.e. neither Org
  579. core modules, nor modules from the CONTRIB directory). Just add symbols
  580. to the end of the list. If the package is called org-xyz.el, then you need
  581. to add the symbol `xyz', and the package must have a call to:
  582. (provide \\='org-xyz)
  583. For export specific modules, see also `org-export-backends'."
  584. :group 'org
  585. :set 'org-set-modules
  586. :version "24.4"
  587. :package-version '(Org . "8.0")
  588. :type
  589. '(set :greedy t
  590. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  591. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  592. (const :tag " crypt: Encryption of subtrees" org-crypt)
  593. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  594. (const :tag " docview: Links to doc-view buffers" org-docview)
  595. (const :tag " eww: Store link to url of eww" org-eww)
  596. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  597. (const :tag " habit: Track your consistency with habits" org-habit)
  598. (const :tag " id: Global IDs for identifying entries" org-id)
  599. (const :tag " info: Links to Info nodes" org-info)
  600. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  601. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  602. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  603. (const :tag " mouse: Additional mouse support" org-mouse)
  604. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  605. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  606. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  607. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  608. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  609. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  610. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  611. (const :tag "C collector: Collect properties into tables" org-collector)
  612. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  613. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  614. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  615. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  616. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  617. (const :tag "C eval: Include command output as text" org-eval)
  618. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  619. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  620. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  621. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  622. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  623. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  624. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  625. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  626. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  627. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  628. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  629. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  630. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  631. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  632. (const :tag "C registry: A registry for Org links" org-registry)
  633. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  634. (const :tag "C secretary: Team management with org-mode" org-secretary)
  635. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  636. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  637. (const :tag "C track: Keep up with Org mode development" org-track)
  638. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  639. (const :tag "C vm: Links to VM folders/messages" org-vm)
  640. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  641. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  642. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  643. (defvar org-export-registered-backends) ; From ox.el.
  644. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  645. (declare-function org-export-backend-name "ox" (backend) t)
  646. (defcustom org-export-backends '(ascii html icalendar latex odt)
  647. "List of export back-ends that should be always available.
  648. If a description starts with <C>, the file is not part of Emacs
  649. and loading it will require that you have downloaded and properly
  650. installed the Org mode distribution.
  651. Unlike to `org-modules', libraries in this list will not be
  652. loaded along with Org, but only once the export framework is
  653. needed.
  654. This variable needs to be set before org.el is loaded. If you
  655. need to make a change while Emacs is running, use the customize
  656. interface or run the following code, where VAL stands for the new
  657. value of the variable, after updating it:
  658. (progn
  659. (setq org-export-registered-backends
  660. (cl-remove-if-not
  661. (lambda (backend)
  662. (let ((name (org-export-backend-name backend)))
  663. (or (memq name val)
  664. (catch \\='parentp
  665. (dolist (b val)
  666. (and (org-export-derived-backend-p b name)
  667. (throw \\='parentp t)))))))
  668. org-export-registered-backends))
  669. (let ((new-list (mapcar #\\='org-export-backend-name
  670. org-export-registered-backends)))
  671. (dolist (backend val)
  672. (cond
  673. ((not (load (format \"ox-%s\" backend) t t))
  674. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  675. backend))
  676. ((not (memq backend new-list)) (push backend new-list))))
  677. (set-default \\='org-export-backends new-list)))
  678. Adding a back-end to this list will also pull the back-end it
  679. depends on, if any."
  680. :group 'org
  681. :group 'org-export
  682. :version "26.1"
  683. :package-version '(Org . "9.0")
  684. :initialize 'custom-initialize-set
  685. :set (lambda (var val)
  686. (if (not (featurep 'ox)) (set-default var val)
  687. ;; Any back-end not required anymore (not present in VAL and not
  688. ;; a parent of any back-end in the new value) is removed from the
  689. ;; list of registered back-ends.
  690. (setq org-export-registered-backends
  691. (cl-remove-if-not
  692. (lambda (backend)
  693. (let ((name (org-export-backend-name backend)))
  694. (or (memq name val)
  695. (catch 'parentp
  696. (dolist (b val)
  697. (and (org-export-derived-backend-p b name)
  698. (throw 'parentp t)))))))
  699. org-export-registered-backends))
  700. ;; Now build NEW-LIST of both new back-ends and required
  701. ;; parents.
  702. (let ((new-list (mapcar #'org-export-backend-name
  703. org-export-registered-backends)))
  704. (dolist (backend val)
  705. (cond
  706. ((not (load (format "ox-%s" backend) t t))
  707. (message "Problems while trying to load export back-end `%s'"
  708. backend))
  709. ((not (memq backend new-list)) (push backend new-list))))
  710. ;; Set VAR to that list with fixed dependencies.
  711. (set-default var new-list))))
  712. :type '(set :greedy t
  713. (const :tag " ascii Export buffer to ASCII format" ascii)
  714. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  715. (const :tag " html Export buffer to HTML format" html)
  716. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  717. (const :tag " latex Export buffer to LaTeX format" latex)
  718. (const :tag " man Export buffer to MAN format" man)
  719. (const :tag " md Export buffer to Markdown format" md)
  720. (const :tag " odt Export buffer to ODT format" odt)
  721. (const :tag " org Export buffer to Org format" org)
  722. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  723. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  724. (const :tag "C deck Export buffer to deck.js presentations" deck)
  725. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  726. (const :tag "C groff Export buffer to Groff format" groff)
  727. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  728. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  729. (const :tag "C s5 Export buffer to s5 presentations" s5)
  730. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  731. (eval-after-load 'ox
  732. '(dolist (backend org-export-backends)
  733. (condition-case nil (require (intern (format "ox-%s" backend)))
  734. (error (message "Problems while trying to load export back-end `%s'"
  735. backend)))))
  736. (defcustom org-support-shift-select nil
  737. "Non-nil means make shift-cursor commands select text when possible.
  738. \\<org-mode-map>\
  739. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  740. start selecting a region, or enlarge regions started in this way.
  741. In Org mode, in special contexts, these same keys are used for
  742. other purposes, important enough to compete with shift selection.
  743. Org tries to balance these needs by supporting `shift-select-mode'
  744. outside these special contexts, under control of this variable.
  745. The default of this variable is nil, to avoid confusing behavior. Shifted
  746. cursor keys will then execute Org commands in the following contexts:
  747. - on a headline, changing TODO state (left/right) and priority (up/down)
  748. - on a time stamp, changing the time
  749. - in a plain list item, changing the bullet type
  750. - in a property definition line, switching between allowed values
  751. - in the BEGIN line of a clock table (changing the time block).
  752. Outside these contexts, the commands will throw an error.
  753. When this variable is t and the cursor is not in a special
  754. context, Org mode will support shift-selection for making and
  755. enlarging regions. To make this more effective, the bullet
  756. cycling will no longer happen anywhere in an item line, but only
  757. if the cursor is exactly on the bullet.
  758. If you set this variable to the symbol `always', then the keys
  759. will not be special in headlines, property lines, and item lines,
  760. to make shift selection work there as well. If this is what you
  761. want, you can use the following alternative commands:
  762. `\\[org-todo]' and `\\[org-priority]' \
  763. to change TODO state and priority,
  764. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  765. can be used to switch TODO sets,
  766. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  767. and properties can be edited by hand or in column view.
  768. However, when the cursor is on a timestamp, shift-cursor commands
  769. will still edit the time stamp - this is just too good to give up."
  770. :group 'org
  771. :type '(choice
  772. (const :tag "Never" nil)
  773. (const :tag "When outside special context" t)
  774. (const :tag "Everywhere except timestamps" always)))
  775. (defcustom org-loop-over-headlines-in-active-region nil
  776. "Shall some commands act upon headlines in the active region?
  777. When set to t, some commands will be performed in all headlines
  778. within the active region.
  779. When set to `start-level', some commands will be performed in all
  780. headlines within the active region, provided that these headlines
  781. are of the same level than the first one.
  782. When set to a string, those commands will be performed on the
  783. matching headlines within the active region. Such string must be
  784. a tags/property/todo match as it is used in the agenda tags view.
  785. The list of commands is: `org-schedule', `org-deadline',
  786. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  787. `org-archive-to-archive-sibling'. The archiving commands skip
  788. already archived entries."
  789. :type '(choice (const :tag "Don't loop" nil)
  790. (const :tag "All headlines in active region" t)
  791. (const :tag "In active region, headlines at the same level than the first one" start-level)
  792. (string :tag "Tags/Property/Todo matcher"))
  793. :version "24.1"
  794. :group 'org-todo
  795. :group 'org-archive)
  796. (defgroup org-startup nil
  797. "Options concerning startup of Org mode."
  798. :tag "Org Startup"
  799. :group 'org)
  800. (defcustom org-startup-folded t
  801. "Non-nil means entering Org mode will switch to OVERVIEW.
  802. This can also be configured on a per-file basis by adding one of
  803. the following lines anywhere in the buffer:
  804. #+STARTUP: fold (or `overview', this is equivalent)
  805. #+STARTUP: nofold (or `showall', this is equivalent)
  806. #+STARTUP: content
  807. #+STARTUP: showeverything
  808. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  809. to ignore this option when Org opens agenda files for the first
  810. time."
  811. :group 'org-startup
  812. :type '(choice
  813. (const :tag "nofold: show all" nil)
  814. (const :tag "fold: overview" t)
  815. (const :tag "content: all headlines" content)
  816. (const :tag "show everything, even drawers" showeverything)))
  817. (defcustom org-startup-truncated t
  818. "Non-nil means entering Org mode will set `truncate-lines'.
  819. This is useful since some lines containing links can be very long and
  820. uninteresting. Also tables look terrible when wrapped.
  821. The variable `org-startup-truncated' allows to configure
  822. truncation for Org mode different to the other modes that use the
  823. variable `truncate-lines' and as a shortcut instead of putting
  824. the variable `truncate-lines' into the `org-mode-hook'. If one
  825. wants to configure truncation for Org mode not statically but
  826. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  827. the variable `truncate-lines' has to be used because in such a
  828. case it is too late to set the variable `org-startup-truncated'."
  829. :group 'org-startup
  830. :type 'boolean)
  831. (defcustom org-startup-indented nil
  832. "Non-nil means turn on `org-indent-mode' on startup.
  833. This can also be configured on a per-file basis by adding one of
  834. the following lines anywhere in the buffer:
  835. #+STARTUP: indent
  836. #+STARTUP: noindent"
  837. :group 'org-structure
  838. :type '(choice
  839. (const :tag "Not" nil)
  840. (const :tag "Globally (slow on startup in large files)" t)))
  841. (defcustom org-use-sub-superscripts t
  842. "Non-nil means interpret \"_\" and \"^\" for display.
  843. If you want to control how Org exports those characters, see
  844. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  845. used to be an alias for `org-export-with-sub-superscripts' in
  846. Org <8.0, it is not anymore.
  847. When this option is turned on, you can use TeX-like syntax for
  848. sub- and superscripts within the buffer. Several characters after
  849. \"_\" or \"^\" will be considered as a single item - so grouping
  850. with {} is normally not needed. For example, the following things
  851. will be parsed as single sub- or superscripts:
  852. 10^24 or 10^tau several digits will be considered 1 item.
  853. 10^-12 or 10^-tau a leading sign with digits or a word
  854. x^2-y^3 will be read as x^2 - y^3, because items are
  855. terminated by almost any nonword/nondigit char.
  856. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  857. Still, ambiguity is possible. So when in doubt, use {} to enclose
  858. the sub/superscript. If you set this variable to the symbol `{}',
  859. the braces are *required* in order to trigger interpretations as
  860. sub/superscript. This can be helpful in documents that need \"_\"
  861. frequently in plain text."
  862. :group 'org-startup
  863. :version "24.4"
  864. :package-version '(Org . "8.0")
  865. :type '(choice
  866. (const :tag "Always interpret" t)
  867. (const :tag "Only with braces" {})
  868. (const :tag "Never interpret" nil)))
  869. (defcustom org-startup-with-beamer-mode nil
  870. "Non-nil means turn on `org-beamer-mode' on startup.
  871. This can also be configured on a per-file basis by adding one of
  872. the following lines anywhere in the buffer:
  873. #+STARTUP: beamer"
  874. :group 'org-startup
  875. :version "24.1"
  876. :type 'boolean)
  877. (defcustom org-startup-align-all-tables nil
  878. "Non-nil means align all tables when visiting a file.
  879. This is useful when the column width in tables is forced with <N> cookies
  880. in table fields. Such tables will look correct only after the first re-align.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: align
  884. #+STARTUP: noalign"
  885. :group 'org-startup
  886. :type 'boolean)
  887. (defcustom org-startup-with-inline-images nil
  888. "Non-nil means show inline images when loading a new Org file.
  889. This can also be configured on a per-file basis by adding one of
  890. the following lines anywhere in the buffer:
  891. #+STARTUP: inlineimages
  892. #+STARTUP: noinlineimages"
  893. :group 'org-startup
  894. :version "24.1"
  895. :type 'boolean)
  896. (defcustom org-startup-with-latex-preview nil
  897. "Non-nil means preview LaTeX fragments when loading a new Org file.
  898. This can also be configured on a per-file basis by adding one of
  899. the following lines anywhere in the buffer:
  900. #+STARTUP: latexpreview
  901. #+STARTUP: nolatexpreview"
  902. :group 'org-startup
  903. :version "24.4"
  904. :package-version '(Org . "8.0")
  905. :type 'boolean)
  906. (defcustom org-insert-mode-line-in-empty-file nil
  907. "Non-nil means insert the first line setting Org mode in empty files.
  908. When the function `org-mode' is called interactively in an empty file, this
  909. normally means that the file name does not automatically trigger Org mode.
  910. To ensure that the file will always be in Org mode in the future, a
  911. line enforcing Org mode will be inserted into the buffer, if this option
  912. has been set."
  913. :group 'org-startup
  914. :type 'boolean)
  915. (defcustom org-replace-disputed-keys nil
  916. "Non-nil means use alternative key bindings for some keys.
  917. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  918. These keys are also used by other packages like shift-selection-mode'
  919. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  920. If you want to use Org mode together with one of these other modes,
  921. or more generally if you would like to move some Org mode commands to
  922. other keys, set this variable and configure the keys with the variable
  923. `org-disputed-keys'.
  924. This option is only relevant at load-time of Org mode, and must be set
  925. *before* org.el is loaded. Changing it requires a restart of Emacs to
  926. become effective."
  927. :group 'org-startup
  928. :type 'boolean)
  929. (defcustom org-use-extra-keys nil
  930. "Non-nil means use extra key sequence definitions for certain commands.
  931. This happens automatically if `window-system' is nil. This
  932. variable lets you do the same manually. You must set it before
  933. loading Org."
  934. :group 'org-startup
  935. :type 'boolean)
  936. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  937. (defcustom org-disputed-keys
  938. '(([(shift up)] . [(meta p)])
  939. ([(shift down)] . [(meta n)])
  940. ([(shift left)] . [(meta -)])
  941. ([(shift right)] . [(meta +)])
  942. ([(control shift right)] . [(meta shift +)])
  943. ([(control shift left)] . [(meta shift -)]))
  944. "Keys for which Org mode and other modes compete.
  945. This is an alist, cars are the default keys, second element specifies
  946. the alternative to use when `org-replace-disputed-keys' is t.
  947. Keys can be specified in any syntax supported by `define-key'.
  948. The value of this option takes effect only at Org mode startup,
  949. therefore you'll have to restart Emacs to apply it after changing."
  950. :group 'org-startup
  951. :type 'alist)
  952. (defun org-key (key)
  953. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  954. Or return the original if not disputed."
  955. (when org-replace-disputed-keys
  956. (let* ((nkey (key-description key))
  957. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  958. org-disputed-keys)))
  959. (setq key (if x (cdr x) key))))
  960. key)
  961. (defun org-defkey (keymap key def)
  962. "Define a key, possibly translated, as returned by `org-key'."
  963. (define-key keymap (org-key key) def))
  964. (defcustom org-ellipsis nil
  965. "The ellipsis to use in the Org mode outline.
  966. When nil, just use the standard three dots.
  967. When a string, use that string instead.
  968. The change affects only Org mode (which will then use its own display table).
  969. Changing this requires executing `\\[org-mode]' in a buffer to become
  970. effective."
  971. :group 'org-startup
  972. :type '(choice (const :tag "Default" nil)
  973. (string :tag "String" :value "...#"))
  974. :safe #'string-or-null-p)
  975. (defvar org-display-table nil
  976. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  977. (defgroup org-keywords nil
  978. "Keywords in Org mode."
  979. :tag "Org Keywords"
  980. :group 'org)
  981. (defcustom org-closed-keep-when-no-todo nil
  982. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  983. :group 'org-todo
  984. :group 'org-keywords
  985. :version "24.4"
  986. :package-version '(Org . "8.0")
  987. :type 'boolean)
  988. (defgroup org-structure nil
  989. "Options concerning the general structure of Org files."
  990. :tag "Org Structure"
  991. :group 'org)
  992. (defgroup org-reveal-location nil
  993. "Options about how to make context of a location visible."
  994. :tag "Org Reveal Location"
  995. :group 'org-structure)
  996. (defcustom org-show-context-detail '((agenda . local)
  997. (bookmark-jump . lineage)
  998. (isearch . lineage)
  999. (default . ancestors))
  1000. "Alist between context and visibility span when revealing a location.
  1001. \\<org-mode-map>Some actions may move point into invisible
  1002. locations. As a consequence, Org always expose a neighborhood
  1003. around point. How much is shown depends on the initial action,
  1004. or context. Valid contexts are
  1005. agenda when exposing an entry from the agenda
  1006. org-goto when using the command `org-goto' (`\\[org-goto]')
  1007. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1008. tags-tree when constructing a sparse tree based on tags matches
  1009. link-search when exposing search matches associated with a link
  1010. mark-goto when exposing the jump goal of a mark
  1011. bookmark-jump when exposing a bookmark location
  1012. isearch when exiting from an incremental search
  1013. default default for all contexts not set explicitly
  1014. Allowed visibility spans are
  1015. minimal show current headline; if point is not on headline,
  1016. also show entry
  1017. local show current headline, entry and next headline
  1018. ancestors show current headline and its direct ancestors; if
  1019. point is not on headline, also show entry
  1020. lineage show current headline, its direct ancestors and all
  1021. their children; if point is not on headline, also show
  1022. entry and first child
  1023. tree show current headline, its direct ancestors and all
  1024. their children; if point is not on headline, also show
  1025. entry and all children
  1026. canonical show current headline, its direct ancestors along with
  1027. their entries and children; if point is not located on
  1028. the headline, also show current entry and all children
  1029. As special cases, a nil or t value means show all contexts in
  1030. `minimal' or `canonical' view, respectively.
  1031. Some views can make displayed information very compact, but also
  1032. make it harder to edit the location of the match. In such
  1033. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1034. more context."
  1035. :group 'org-reveal-location
  1036. :version "26.1"
  1037. :package-version '(Org . "9.0")
  1038. :type '(choice
  1039. (const :tag "Canonical" t)
  1040. (const :tag "Minimal" nil)
  1041. (repeat :greedy t :tag "Individual contexts"
  1042. (cons
  1043. (choice :tag "Context"
  1044. (const agenda)
  1045. (const org-goto)
  1046. (const occur-tree)
  1047. (const tags-tree)
  1048. (const link-search)
  1049. (const mark-goto)
  1050. (const bookmark-jump)
  1051. (const isearch)
  1052. (const default))
  1053. (choice :tag "Detail level"
  1054. (const minimal)
  1055. (const local)
  1056. (const ancestors)
  1057. (const lineage)
  1058. (const tree)
  1059. (const canonical))))))
  1060. (defcustom org-indirect-buffer-display 'other-window
  1061. "How should indirect tree buffers be displayed?
  1062. This applies to indirect buffers created with the commands
  1063. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1064. Valid values are:
  1065. current-window Display in the current window
  1066. other-window Just display in another window.
  1067. dedicated-frame Create one new frame, and re-use it each time.
  1068. new-frame Make a new frame each time. Note that in this case
  1069. previously-made indirect buffers are kept, and you need to
  1070. kill these buffers yourself."
  1071. :group 'org-structure
  1072. :group 'org-agenda-windows
  1073. :type '(choice
  1074. (const :tag "In current window" current-window)
  1075. (const :tag "In current frame, other window" other-window)
  1076. (const :tag "Each time a new frame" new-frame)
  1077. (const :tag "One dedicated frame" dedicated-frame)))
  1078. (defcustom org-use-speed-commands nil
  1079. "Non-nil means activate single letter commands at beginning of a headline.
  1080. This may also be a function to test for appropriate locations where speed
  1081. commands should be active.
  1082. For example, to activate speed commands when the point is on any
  1083. star at the beginning of the headline, you can do this:
  1084. (setq org-use-speed-commands
  1085. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1086. :group 'org-structure
  1087. :type '(choice
  1088. (const :tag "Never" nil)
  1089. (const :tag "At beginning of headline stars" t)
  1090. (function)))
  1091. (defcustom org-speed-commands-user nil
  1092. "Alist of additional speed commands.
  1093. This list will be checked before `org-speed-commands-default'
  1094. when the variable `org-use-speed-commands' is non-nil
  1095. and when the cursor is at the beginning of a headline.
  1096. The car if each entry is a string with a single letter, which must
  1097. be assigned to `self-insert-command' in the global map.
  1098. The cdr is either a command to be called interactively, a function
  1099. to be called, or a form to be evaluated.
  1100. An entry that is just a list with a single string will be interpreted
  1101. as a descriptive headline that will be added when listing the speed
  1102. commands in the Help buffer using the `?' speed command."
  1103. :group 'org-structure
  1104. :type '(repeat :value ("k" . ignore)
  1105. (choice :value ("k" . ignore)
  1106. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1107. (cons :tag "Letter and Command"
  1108. (string :tag "Command letter")
  1109. (choice
  1110. (function)
  1111. (sexp))))))
  1112. (defcustom org-bookmark-names-plist
  1113. '(:last-capture "org-capture-last-stored"
  1114. :last-refile "org-refile-last-stored"
  1115. :last-capture-marker "org-capture-last-stored-marker")
  1116. "Names for bookmarks automatically set by some Org commands.
  1117. This can provide strings as names for a number of bookmarks Org sets
  1118. automatically. The following keys are currently implemented:
  1119. :last-capture
  1120. :last-capture-marker
  1121. :last-refile
  1122. When a key does not show up in the property list, the corresponding bookmark
  1123. is not set."
  1124. :group 'org-structure
  1125. :type 'plist)
  1126. (defgroup org-cycle nil
  1127. "Options concerning visibility cycling in Org mode."
  1128. :tag "Org Cycle"
  1129. :group 'org-structure)
  1130. (defcustom org-cycle-skip-children-state-if-no-children t
  1131. "Non-nil means skip CHILDREN state in entries that don't have any."
  1132. :group 'org-cycle
  1133. :type 'boolean)
  1134. (defcustom org-cycle-max-level nil
  1135. "Maximum level which should still be subject to visibility cycling.
  1136. Levels higher than this will, for cycling, be treated as text, not a headline.
  1137. When `org-odd-levels-only' is set, a value of N in this variable actually
  1138. means 2N-1 stars as the limiting headline.
  1139. When nil, cycle all levels.
  1140. Note that the limiting level of cycling is also influenced by
  1141. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1142. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1143. than its value."
  1144. :group 'org-cycle
  1145. :type '(choice
  1146. (const :tag "No limit" nil)
  1147. (integer :tag "Maximum level")))
  1148. (defcustom org-hide-block-startup nil
  1149. "Non-nil means entering Org mode will fold all blocks.
  1150. This can also be set in on a per-file basis with
  1151. #+STARTUP: hideblocks
  1152. #+STARTUP: showblocks"
  1153. :group 'org-startup
  1154. :group 'org-cycle
  1155. :type 'boolean)
  1156. (defcustom org-cycle-global-at-bob nil
  1157. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1158. This makes it possible to do global cycling without having to use `S-TAB'
  1159. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1160. line of the buffer
  1161. must not be a headline -- it may be empty or some other text.
  1162. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1163. sure the cursor stays at the beginning of the buffer.
  1164. When this option is nil, don't do anything special at the beginning of
  1165. the buffer."
  1166. :group 'org-cycle
  1167. :type 'boolean)
  1168. (defcustom org-cycle-level-after-item/entry-creation t
  1169. "Non-nil means cycle entry level or item indentation in new empty entries.
  1170. When the cursor is at the end of an empty headline, i.e., with only stars
  1171. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1172. and then all possible ancestor states, before returning to the original state.
  1173. This makes data entry extremely fast: M-RET to create a new headline,
  1174. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1175. When the cursor is at the end of an empty plain list item, one TAB will
  1176. make it a subitem, two or more tabs will back up to make this an item
  1177. higher up in the item hierarchy."
  1178. :group 'org-cycle
  1179. :type 'boolean)
  1180. (defcustom org-cycle-emulate-tab t
  1181. "Where should `org-cycle' emulate TAB.
  1182. nil Never
  1183. white Only in completely white lines
  1184. whitestart Only at the beginning of lines, before the first non-white char
  1185. t Everywhere except in headlines
  1186. exc-hl-bol Everywhere except at the start of a headline
  1187. If TAB is used in a place where it does not emulate TAB, the current subtree
  1188. visibility is cycled."
  1189. :group 'org-cycle
  1190. :type '(choice (const :tag "Never" nil)
  1191. (const :tag "Only in completely white lines" white)
  1192. (const :tag "Before first char in a line" whitestart)
  1193. (const :tag "Everywhere except in headlines" t)
  1194. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1195. (defcustom org-cycle-separator-lines 2
  1196. "Number of empty lines needed to keep an empty line between collapsed trees.
  1197. If you leave an empty line between the end of a subtree and the following
  1198. headline, this empty line is hidden when the subtree is folded.
  1199. Org mode will leave (exactly) one empty line visible if the number of
  1200. empty lines is equal or larger to the number given in this variable.
  1201. So the default 2 means at least 2 empty lines after the end of a subtree
  1202. are needed to produce free space between a collapsed subtree and the
  1203. following headline.
  1204. If the number is negative, and the number of empty lines is at least -N,
  1205. all empty lines are shown.
  1206. Special case: when 0, never leave empty lines in collapsed view."
  1207. :group 'org-cycle
  1208. :type 'integer)
  1209. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1210. (defcustom org-pre-cycle-hook nil
  1211. "Hook that is run before visibility cycling is happening.
  1212. The function(s) in this hook must accept a single argument which indicates
  1213. the new state that will be set right after running this hook. The
  1214. argument is a symbol. Before a global state change, it can have the values
  1215. `overview', `content', or `all'. Before a local state change, it can have
  1216. the values `folded', `children', or `subtree'."
  1217. :group 'org-cycle
  1218. :type 'hook)
  1219. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1220. org-cycle-hide-drawers
  1221. org-cycle-show-empty-lines
  1222. org-optimize-window-after-visibility-change)
  1223. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1224. The function(s) in this hook must accept a single argument which indicates
  1225. the new state that was set by the most recent `org-cycle' command. The
  1226. argument is a symbol. After a global state change, it can have the values
  1227. `overview', `contents', or `all'. After a local state change, it can have
  1228. the values `folded', `children', or `subtree'."
  1229. :group 'org-cycle
  1230. :type 'hook
  1231. :version "26.1"
  1232. :package-version '(Org . "8.3"))
  1233. (defgroup org-edit-structure nil
  1234. "Options concerning structure editing in Org mode."
  1235. :tag "Org Edit Structure"
  1236. :group 'org-structure)
  1237. (defcustom org-odd-levels-only nil
  1238. "Non-nil means skip even levels and only use odd levels for the outline.
  1239. This has the effect that two stars are being added/taken away in
  1240. promotion/demotion commands. It also influences how levels are
  1241. handled by the exporters.
  1242. Changing it requires restart of `font-lock-mode' to become effective
  1243. for fontification also in regions already fontified.
  1244. You may also set this on a per-file basis by adding one of the following
  1245. lines to the buffer:
  1246. #+STARTUP: odd
  1247. #+STARTUP: oddeven"
  1248. :group 'org-edit-structure
  1249. :group 'org-appearance
  1250. :type 'boolean)
  1251. (defcustom org-adapt-indentation t
  1252. "Non-nil means adapt indentation to outline node level.
  1253. When this variable is set, Org assumes that you write outlines by
  1254. indenting text in each node to align with the headline (after the
  1255. stars). The following issues are influenced by this variable:
  1256. - The indentation is increased by one space in a demotion
  1257. command, and decreased by one in a promotion command. However,
  1258. in the latter case, if shifting some line in the entry body
  1259. would alter document structure (e.g., insert a new headline),
  1260. indentation is not changed at all.
  1261. - Property drawers and planning information is inserted indented
  1262. when this variable is set. When nil, they will not be indented.
  1263. - TAB indents a line relative to current level. The lines below
  1264. a headline will be indented when this variable is set.
  1265. Note that this is all about true indentation, by adding and
  1266. removing space characters. See also `org-indent.el' which does
  1267. level-dependent indentation in a virtual way, i.e. at display
  1268. time in Emacs."
  1269. :group 'org-edit-structure
  1270. :type 'boolean)
  1271. (defcustom org-special-ctrl-a/e nil
  1272. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1273. When t, `C-a' will bring back the cursor to the beginning of the
  1274. headline text, i.e. after the stars and after a possible TODO
  1275. keyword. In an item, this will be the position after bullet and
  1276. check-box, if any. When the cursor is already at that position,
  1277. another `C-a' will bring it to the beginning of the line.
  1278. `C-e' will jump to the end of the headline, ignoring the presence
  1279. of tags in the headline. A second `C-e' will then jump to the
  1280. true end of the line, after any tags. This also means that, when
  1281. this variable is non-nil, `C-e' also will never jump beyond the
  1282. end of the heading of a folded section, i.e. not after the
  1283. ellipses.
  1284. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1285. normally, going to the true line boundary first. Only a directly
  1286. following, identical keypress will bring the cursor to the
  1287. special positions.
  1288. This may also be a cons cell where the behavior for `C-a' and
  1289. `C-e' is set separately."
  1290. :group 'org-edit-structure
  1291. :type '(choice
  1292. (const :tag "off" nil)
  1293. (const :tag "on: after stars/bullet and before tags first" t)
  1294. (const :tag "reversed: true line boundary first" reversed)
  1295. (cons :tag "Set C-a and C-e separately"
  1296. (choice :tag "Special C-a"
  1297. (const :tag "off" nil)
  1298. (const :tag "on: after stars/bullet first" t)
  1299. (const :tag "reversed: before stars/bullet first" reversed))
  1300. (choice :tag "Special C-e"
  1301. (const :tag "off" nil)
  1302. (const :tag "on: before tags first" t)
  1303. (const :tag "reversed: after tags first" reversed)))))
  1304. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1305. (defcustom org-special-ctrl-k nil
  1306. "Non-nil means `C-k' will behave specially in headlines.
  1307. When nil, `C-k' will call the default `kill-line' command.
  1308. When t, the following will happen while the cursor is in the headline:
  1309. - When the cursor is at the beginning of a headline, kill the entire
  1310. line and possible the folded subtree below the line.
  1311. - When in the middle of the headline text, kill the headline up to the tags.
  1312. - When after the headline text, kill the tags."
  1313. :group 'org-edit-structure
  1314. :type 'boolean)
  1315. (defcustom org-ctrl-k-protect-subtree nil
  1316. "Non-nil means, do not delete a hidden subtree with C-k.
  1317. When set to the symbol `error', simply throw an error when C-k is
  1318. used to kill (part-of) a headline that has hidden text behind it.
  1319. Any other non-nil value will result in a query to the user, if it is
  1320. OK to kill that hidden subtree. When nil, kill without remorse."
  1321. :group 'org-edit-structure
  1322. :version "24.1"
  1323. :type '(choice
  1324. (const :tag "Do not protect hidden subtrees" nil)
  1325. (const :tag "Protect hidden subtrees with a security query" t)
  1326. (const :tag "Never kill a hidden subtree with C-k" error)))
  1327. (defcustom org-special-ctrl-o t
  1328. "Non-nil means, make `C-o' insert a row in tables."
  1329. :group 'org-edit-structure
  1330. :type 'boolean)
  1331. (defcustom org-catch-invisible-edits nil
  1332. "Check if in invisible region before inserting or deleting a character.
  1333. Valid values are:
  1334. nil Do not check, so just do invisible edits.
  1335. error Throw an error and do nothing.
  1336. show Make point visible, and do the requested edit.
  1337. show-and-error Make point visible, then throw an error and abort the edit.
  1338. smart Make point visible, and do insertion/deletion if it is
  1339. adjacent to visible text and the change feels predictable.
  1340. Never delete a previously invisible character or add in the
  1341. middle or right after an invisible region. Basically, this
  1342. allows insertion and backward-delete right before ellipses.
  1343. FIXME: maybe in this case we should not even show?"
  1344. :group 'org-edit-structure
  1345. :version "24.1"
  1346. :type '(choice
  1347. (const :tag "Do not check" nil)
  1348. (const :tag "Throw error when trying to edit" error)
  1349. (const :tag "Unhide, but do not do the edit" show-and-error)
  1350. (const :tag "Show invisible part and do the edit" show)
  1351. (const :tag "Be smart and do the right thing" smart)))
  1352. (defcustom org-yank-folded-subtrees t
  1353. "Non-nil means when yanking subtrees, fold them.
  1354. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1355. it starts with a heading and all other headings in it are either children
  1356. or siblings, then fold all the subtrees. However, do this only if no
  1357. text after the yank would be swallowed into a folded tree by this action."
  1358. :group 'org-edit-structure
  1359. :type 'boolean)
  1360. (defcustom org-yank-adjusted-subtrees nil
  1361. "Non-nil means when yanking subtrees, adjust the level.
  1362. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1363. this function for details."
  1364. :group 'org-edit-structure
  1365. :type 'boolean)
  1366. (defcustom org-M-RET-may-split-line '((default . t))
  1367. "Non-nil means M-RET will split the line at the cursor position.
  1368. When nil, it will go to the end of the line before making a
  1369. new line.
  1370. You may also set this option in a different way for different
  1371. contexts. Valid contexts are:
  1372. headline when creating a new headline
  1373. item when creating a new item
  1374. table in a table field
  1375. default the value to be used for all contexts not explicitly
  1376. customized"
  1377. :group 'org-structure
  1378. :group 'org-table
  1379. :type '(choice
  1380. (const :tag "Always" t)
  1381. (const :tag "Never" nil)
  1382. (repeat :greedy t :tag "Individual contexts"
  1383. (cons
  1384. (choice :tag "Context"
  1385. (const headline)
  1386. (const item)
  1387. (const table)
  1388. (const default))
  1389. (boolean)))))
  1390. (defcustom org-insert-heading-respect-content nil
  1391. "Non-nil means insert new headings after the current subtree.
  1392. \\<org-mode-map>
  1393. When nil, the new heading is created directly after the current line.
  1394. The commands `\\[org-insert-heading-respect-content]' and \
  1395. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1396. for the duration of the command."
  1397. :group 'org-structure
  1398. :type 'boolean)
  1399. (defcustom org-blank-before-new-entry '((heading . auto)
  1400. (plain-list-item . auto))
  1401. "Should `org-insert-heading' leave a blank line before new heading/item?
  1402. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1403. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1404. which case Org will look at the surrounding headings/items and try to
  1405. make an intelligent decision whether to insert a blank line or not."
  1406. :group 'org-edit-structure
  1407. :type '(list
  1408. (cons (const heading)
  1409. (choice (const :tag "Never" nil)
  1410. (const :tag "Always" t)
  1411. (const :tag "Auto" auto)))
  1412. (cons (const plain-list-item)
  1413. (choice (const :tag "Never" nil)
  1414. (const :tag "Always" t)
  1415. (const :tag "Auto" auto)))))
  1416. (defcustom org-insert-heading-hook nil
  1417. "Hook being run after inserting a new heading."
  1418. :group 'org-edit-structure
  1419. :type 'hook)
  1420. (defcustom org-enable-fixed-width-editor t
  1421. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1422. This currently only means they are never auto-wrapped.
  1423. When nil, such lines will be treated like ordinary lines."
  1424. :group 'org-edit-structure
  1425. :type 'boolean)
  1426. (defcustom org-goto-auto-isearch t
  1427. "Non-nil means typing characters in `org-goto' starts incremental search.
  1428. When nil, you can use these keybindings to navigate the buffer:
  1429. q Quit the org-goto interface
  1430. n Go to the next visible heading
  1431. p Go to the previous visible heading
  1432. f Go one heading forward on same level
  1433. b Go one heading backward on same level
  1434. u Go one heading up"
  1435. :group 'org-edit-structure
  1436. :type 'boolean)
  1437. (defgroup org-sparse-trees nil
  1438. "Options concerning sparse trees in Org mode."
  1439. :tag "Org Sparse Trees"
  1440. :group 'org-structure)
  1441. (defcustom org-highlight-sparse-tree-matches t
  1442. "Non-nil means highlight all matches that define a sparse tree.
  1443. The highlights will automatically disappear the next time the buffer is
  1444. changed by an edit command."
  1445. :group 'org-sparse-trees
  1446. :type 'boolean)
  1447. (defcustom org-remove-highlights-with-change t
  1448. "Non-nil means any change to the buffer will remove temporary highlights.
  1449. \\<org-mode-map>\
  1450. Such highlights are created by `org-occur' and `org-clock-display'.
  1451. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1452. to get rid of the highlights.
  1453. The highlights created by `org-toggle-latex-fragment' always need
  1454. `\\[org-toggle-latex-fragment]' to be removed."
  1455. :group 'org-sparse-trees
  1456. :group 'org-time
  1457. :type 'boolean)
  1458. (defcustom org-occur-case-fold-search t
  1459. "Non-nil means `org-occur' should be case-insensitive.
  1460. If set to `smart' the search will be case-insensitive only if it
  1461. doesn't specify any upper case character."
  1462. :group 'org-sparse-trees
  1463. :version "26.1"
  1464. :type '(choice
  1465. (const :tag "Case-sensitive" nil)
  1466. (const :tag "Case-insensitive" t)
  1467. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1468. (defcustom org-occur-hook '(org-first-headline-recenter)
  1469. "Hook that is run after `org-occur' has constructed a sparse tree.
  1470. This can be used to recenter the window to show as much of the structure
  1471. as possible."
  1472. :group 'org-sparse-trees
  1473. :type 'hook)
  1474. (defgroup org-imenu-and-speedbar nil
  1475. "Options concerning imenu and speedbar in Org mode."
  1476. :tag "Org Imenu and Speedbar"
  1477. :group 'org-structure)
  1478. (defcustom org-imenu-depth 2
  1479. "The maximum level for Imenu access to Org headlines.
  1480. This also applied for speedbar access."
  1481. :group 'org-imenu-and-speedbar
  1482. :type 'integer)
  1483. (defgroup org-table nil
  1484. "Options concerning tables in Org mode."
  1485. :tag "Org Table"
  1486. :group 'org)
  1487. (defcustom org-enable-table-editor 'optimized
  1488. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1489. When nil, such lines will be treated like ordinary lines.
  1490. When equal to the symbol `optimized', the table editor will be optimized to
  1491. do the following:
  1492. - Automatic overwrite mode in front of whitespace in table fields.
  1493. This makes the structure of the table stay in tact as long as the edited
  1494. field does not exceed the column width.
  1495. - Minimize the number of realigns. Normally, the table is aligned each time
  1496. TAB or RET are pressed to move to another field. With optimization this
  1497. happens only if changes to a field might have changed the column width.
  1498. Optimization requires replacing the functions `self-insert-command',
  1499. `delete-char', and `backward-delete-char' in Org buffers, with a
  1500. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1501. good at guessing when a re-align will be necessary, but you can always
  1502. force one with `\\[org-ctrl-c-ctrl-c]'.
  1503. If you would like to use the optimized version in Org mode, but the
  1504. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1505. This variable can be used to turn on and off the table editor during a session,
  1506. but in order to toggle optimization, a restart is required.
  1507. See also the variable `org-table-auto-blank-field'."
  1508. :group 'org-table
  1509. :type '(choice
  1510. (const :tag "off" nil)
  1511. (const :tag "on" t)
  1512. (const :tag "on, optimized" optimized)))
  1513. (defcustom org-self-insert-cluster-for-undo nil
  1514. "Non-nil means cluster self-insert commands for undo when possible.
  1515. If this is set, then, like in the Emacs command loop, 20 consecutive
  1516. characters will be undone together.
  1517. This is configurable, because there is some impact on typing performance."
  1518. :group 'org-table
  1519. :type 'boolean)
  1520. (defcustom org-table-tab-recognizes-table.el t
  1521. "Non-nil means TAB will automatically notice a table.el table.
  1522. When it sees such a table, it moves point into it and - if necessary -
  1523. calls `table-recognize-table'."
  1524. :group 'org-table-editing
  1525. :type 'boolean)
  1526. (defgroup org-link nil
  1527. "Options concerning links in Org mode."
  1528. :tag "Org Link"
  1529. :group 'org)
  1530. (defvar-local org-link-abbrev-alist-local nil
  1531. "Buffer-local version of `org-link-abbrev-alist', which see.
  1532. The value of this is taken from the #+LINK lines.")
  1533. (defcustom org-link-parameters
  1534. '(("doi" :follow org--open-doi-link)
  1535. ("elisp" :follow org--open-elisp-link)
  1536. ("file" :complete org-file-complete-link)
  1537. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1538. ("help" :follow org--open-help-link)
  1539. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1540. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1541. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1542. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1543. ("shell" :follow org--open-shell-link))
  1544. "An alist of properties that defines all the links in Org mode.
  1545. The key in each association is a string of the link type.
  1546. Subsequent optional elements make up a p-list of link properties.
  1547. :follow - A function that takes the link path as an argument.
  1548. :export - A function that takes the link path, description and
  1549. export-backend as arguments.
  1550. :store - A function responsible for storing the link. See the
  1551. function `org-store-link-functions'.
  1552. :complete - A function that inserts a link with completion. The
  1553. function takes one optional prefix arg.
  1554. :face - A face for the link, or a function that returns a face.
  1555. The function takes one argument which is the link path. The
  1556. default face is `org-link'.
  1557. :mouse-face - The mouse-face. The default is `highlight'.
  1558. :display - `full' will not fold the link in descriptive
  1559. display. Default is `org-link'.
  1560. :help-echo - A string or function that takes (window object position)
  1561. as arguments and returns a string.
  1562. :keymap - A keymap that is active on the link. The default is
  1563. `org-mouse-map'.
  1564. :htmlize-link - A function for the htmlize-link. Defaults
  1565. to (list :uri \"type:path\")
  1566. :activate-func - A function to run at the end of font-lock
  1567. activation. The function must accept (link-start link-end path bracketp)
  1568. as arguments."
  1569. :group 'org-link
  1570. :type '(alist :tag "Link display parameters"
  1571. :value-type plist)
  1572. :version "26.1"
  1573. :package-version '(Org . "9.1"))
  1574. (defun org-link-get-parameter (type key)
  1575. "Get TYPE link property for KEY.
  1576. TYPE is a string and KEY is a plist keyword."
  1577. (plist-get
  1578. (cdr (assoc type org-link-parameters))
  1579. key))
  1580. (defun org-link-set-parameters (type &rest parameters)
  1581. "Set link TYPE properties to PARAMETERS.
  1582. PARAMETERS should be :key val pairs."
  1583. (let ((data (assoc type org-link-parameters)))
  1584. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1585. (push (cons type parameters) org-link-parameters)
  1586. (org-make-link-regexps)
  1587. (org-element-update-syntax))))
  1588. (defun org-link-types ()
  1589. "Return a list of known link types."
  1590. (mapcar #'car org-link-parameters))
  1591. (defcustom org-link-abbrev-alist nil
  1592. "Alist of link abbreviations.
  1593. The car of each element is a string, to be replaced at the start of a link.
  1594. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1595. links in Org buffers can have an optional tag after a double colon, e.g.,
  1596. [[linkkey:tag][description]]
  1597. The `linkkey' must be a single word, starting with a letter, followed
  1598. by letters, numbers, `-' or `_'.
  1599. If REPLACE is a string, the tag will simply be appended to create the link.
  1600. If the string contains \"%s\", the tag will be inserted there. If the string
  1601. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1602. at that point (see the function `url-hexify-string'). If the string contains
  1603. the specifier \"%(my-function)\", then the custom function `my-function' will
  1604. be invoked: this function takes the tag as its only argument and must return
  1605. a string.
  1606. REPLACE may also be a function that will be called with the tag as the
  1607. only argument to create the link, which should be returned as a string.
  1608. See the manual for examples."
  1609. :group 'org-link
  1610. :type '(repeat
  1611. (cons
  1612. (string :tag "Protocol")
  1613. (choice
  1614. (string :tag "Format")
  1615. (function)))))
  1616. (defcustom org-descriptive-links t
  1617. "Non-nil means Org will display descriptive links.
  1618. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1619. \"Org Website\", hiding the link itself and just displaying its
  1620. description. When set to nil, Org will display the full links
  1621. literally.
  1622. You can interactively set the value of this variable by calling
  1623. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1624. :group 'org-link
  1625. :type 'boolean)
  1626. (defcustom org-link-file-path-type 'adaptive
  1627. "How the path name in file links should be stored.
  1628. Valid values are:
  1629. relative Relative to the current directory, i.e. the directory of the file
  1630. into which the link is being inserted.
  1631. absolute Absolute path, if possible with ~ for home directory.
  1632. noabbrev Absolute path, no abbreviation of home directory.
  1633. adaptive Use relative path for files in the current directory and sub-
  1634. directories of it. For other files, use an absolute path."
  1635. :group 'org-link
  1636. :type '(choice
  1637. (const relative)
  1638. (const absolute)
  1639. (const noabbrev)
  1640. (const adaptive)))
  1641. (defvaralias 'org-activate-links 'org-highlight-links)
  1642. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1643. "Types of links that should be highlighted in Org files.
  1644. This is a list of symbols, each one of them leading to the
  1645. highlighting of a certain link type.
  1646. You can still open links that are not highlighted.
  1647. In principle, it does not hurt to turn on highlighting for all
  1648. link types. There may be a small gain when turning off unused
  1649. link types. The types are:
  1650. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1651. angle Links in angular brackets that may contain whitespace like
  1652. <bbdb:Carsten Dominik>.
  1653. plain Plain links in normal text, no whitespace, like http://google.com.
  1654. radio Text that is matched by a radio target, see manual for details.
  1655. tag Tag settings in a headline (link to tag search).
  1656. date Time stamps (link to calendar).
  1657. footnote Footnote labels.
  1658. If you set this variable during an Emacs session, use `org-mode-restart'
  1659. in the Org buffer so that the change takes effect."
  1660. :group 'org-link
  1661. :group 'org-appearance
  1662. :type '(set :greedy t
  1663. (const :tag "Double bracket links" bracket)
  1664. (const :tag "Angular bracket links" angle)
  1665. (const :tag "Plain text links" plain)
  1666. (const :tag "Radio target matches" radio)
  1667. (const :tag "Tags" tag)
  1668. (const :tag "Timestamps" date)
  1669. (const :tag "Footnotes" footnote)))
  1670. (defcustom org-make-link-description-function nil
  1671. "Function to use for generating link descriptions from links.
  1672. When nil, the link location will be used. This function must take
  1673. two parameters: the first one is the link, the second one is the
  1674. description generated by `org-insert-link'. The function should
  1675. return the description to use."
  1676. :group 'org-link
  1677. :type '(choice (const nil) (function)))
  1678. (defgroup org-link-store nil
  1679. "Options concerning storing links in Org mode."
  1680. :tag "Org Store Link"
  1681. :group 'org-link)
  1682. (defcustom org-url-hexify-p t
  1683. "When non-nil, hexify URL when creating a link."
  1684. :type 'boolean
  1685. :version "24.3"
  1686. :group 'org-link-store)
  1687. (defcustom org-email-link-description-format "Email %c: %.30s"
  1688. "Format of the description part of a link to an email or usenet message.
  1689. The following %-escapes will be replaced by corresponding information:
  1690. %F full \"From\" field
  1691. %f name, taken from \"From\" field, address if no name
  1692. %T full \"To\" field
  1693. %t first name in \"To\" field, address if no name
  1694. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1695. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1696. %s subject
  1697. %d date
  1698. %m message-id.
  1699. You may use normal field width specification between the % and the letter.
  1700. This is for example useful to limit the length of the subject.
  1701. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1702. :group 'org-link-store
  1703. :type 'string)
  1704. (defcustom org-from-is-user-regexp
  1705. (let (r1 r2)
  1706. (when (and user-mail-address (not (string= user-mail-address "")))
  1707. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1708. (when (and user-full-name (not (string= user-full-name "")))
  1709. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1710. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1711. "Regexp matched against the \"From:\" header of an email or usenet message.
  1712. It should match if the message is from the user him/herself."
  1713. :group 'org-link-store
  1714. :type 'regexp)
  1715. (defcustom org-context-in-file-links t
  1716. "Non-nil means file links from `org-store-link' contain context.
  1717. \\<org-mode-map>
  1718. A search string will be added to the file name with :: as separator
  1719. and used to find the context when the link is activated by the command
  1720. `org-open-at-point'. When this option is t, the entire active region
  1721. will be placed in the search string of the file link. If set to a
  1722. positive integer, only the first n lines of context will be stored.
  1723. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1724. \\[org-store-link]')
  1725. negates this setting for the duration of the command."
  1726. :group 'org-link-store
  1727. :type '(choice boolean integer))
  1728. (defcustom org-keep-stored-link-after-insertion nil
  1729. "Non-nil means keep link in list for entire session.
  1730. \\<org-mode-map>
  1731. The command `org-store-link' adds a link pointing to the current
  1732. location to an internal list. These links accumulate during a session.
  1733. The command `org-insert-link' can be used to insert links into any
  1734. Org file (offering completion for all stored links).
  1735. When this option is nil, every link which has been inserted once using
  1736. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1737. unused
  1738. links more efficient."
  1739. :group 'org-link-store
  1740. :type 'boolean)
  1741. (defgroup org-link-follow nil
  1742. "Options concerning following links in Org mode."
  1743. :tag "Org Follow Link"
  1744. :group 'org-link)
  1745. (defcustom org-link-translation-function nil
  1746. "Function to translate links with different syntax to Org syntax.
  1747. This can be used to translate links created for example by the Planner
  1748. or emacs-wiki packages to Org syntax.
  1749. The function must accept two parameters, a TYPE containing the link
  1750. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1751. which is everything after the link protocol. It should return a cons
  1752. with possibly modified values of type and path.
  1753. Org contains a function for this, so if you set this variable to
  1754. `org-translate-link-from-planner', you should be able follow many
  1755. links created by planner."
  1756. :group 'org-link-follow
  1757. :type '(choice (const nil) (function)))
  1758. (defcustom org-follow-link-hook nil
  1759. "Hook that is run after a link has been followed."
  1760. :group 'org-link-follow
  1761. :type 'hook)
  1762. (defcustom org-tab-follows-link nil
  1763. "Non-nil means on links TAB will follow the link.
  1764. Needs to be set before org.el is loaded.
  1765. This really should not be used, it does not make sense, and the
  1766. implementation is bad."
  1767. :group 'org-link-follow
  1768. :type 'boolean)
  1769. (defcustom org-return-follows-link nil
  1770. "Non-nil means on links RET will follow the link.
  1771. In tables, the special behavior of RET has precedence."
  1772. :group 'org-link-follow
  1773. :type 'boolean)
  1774. (defcustom org-mouse-1-follows-link
  1775. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1776. "Non-nil means mouse-1 on a link will follow the link.
  1777. A longer mouse click will still set point. Needs to be set
  1778. before org.el is loaded."
  1779. :group 'org-link-follow
  1780. :version "24.4"
  1781. :package-version '(Org . "8.3")
  1782. :type '(choice
  1783. (const :tag "A double click follows the link" double)
  1784. (const :tag "Unconditionally follow the link with mouse-1" t)
  1785. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1786. (defcustom org-mark-ring-length 4
  1787. "Number of different positions to be recorded in the ring.
  1788. Changing this requires a restart of Emacs to work correctly."
  1789. :group 'org-link-follow
  1790. :type 'integer)
  1791. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1792. "Non-nil means internal fuzzy links can only match headlines.
  1793. When nil, the a fuzzy link may point to a target or a named
  1794. construct in the document. When set to the special value
  1795. `query-to-create', offer to create a new headline when none
  1796. matched.
  1797. Spaces and statistics cookies are ignored during heading searches."
  1798. :group 'org-link-follow
  1799. :version "24.1"
  1800. :type '(choice
  1801. (const :tag "Use fuzzy text search" nil)
  1802. (const :tag "Match only exact headline" t)
  1803. (const :tag "Match exact headline or query to create it"
  1804. query-to-create))
  1805. :safe #'symbolp)
  1806. (defcustom org-link-frame-setup
  1807. '((vm . vm-visit-folder-other-frame)
  1808. (vm-imap . vm-visit-imap-folder-other-frame)
  1809. (gnus . org-gnus-no-new-news)
  1810. (file . find-file-other-window)
  1811. (wl . wl-other-frame))
  1812. "Setup the frame configuration for following links.
  1813. When following a link with Emacs, it may often be useful to display
  1814. this link in another window or frame. This variable can be used to
  1815. set this up for the different types of links.
  1816. For VM, use any of
  1817. `vm-visit-folder'
  1818. `vm-visit-folder-other-window'
  1819. `vm-visit-folder-other-frame'
  1820. For Gnus, use any of
  1821. `gnus'
  1822. `gnus-other-frame'
  1823. `org-gnus-no-new-news'
  1824. For FILE, use any of
  1825. `find-file'
  1826. `find-file-other-window'
  1827. `find-file-other-frame'
  1828. For Wanderlust use any of
  1829. `wl'
  1830. `wl-other-frame'
  1831. For the calendar, use the variable `calendar-setup'.
  1832. For BBDB, it is currently only possible to display the matches in
  1833. another window."
  1834. :group 'org-link-follow
  1835. :type '(list
  1836. (cons (const vm)
  1837. (choice
  1838. (const vm-visit-folder)
  1839. (const vm-visit-folder-other-window)
  1840. (const vm-visit-folder-other-frame)))
  1841. (cons (const vm-imap)
  1842. (choice
  1843. (const vm-visit-imap-folder)
  1844. (const vm-visit-imap-folder-other-window)
  1845. (const vm-visit-imap-folder-other-frame)))
  1846. (cons (const gnus)
  1847. (choice
  1848. (const gnus)
  1849. (const gnus-other-frame)
  1850. (const org-gnus-no-new-news)))
  1851. (cons (const file)
  1852. (choice
  1853. (const find-file)
  1854. (const find-file-other-window)
  1855. (const find-file-other-frame)))
  1856. (cons (const wl)
  1857. (choice
  1858. (const wl)
  1859. (const wl-other-frame)))))
  1860. (defcustom org-display-internal-link-with-indirect-buffer nil
  1861. "Non-nil means use indirect buffer to display infile links.
  1862. Activating internal links (from one location in a file to another location
  1863. in the same file) normally just jumps to the location. When the link is
  1864. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1865. is displayed in
  1866. another window. When this option is set, the other window actually displays
  1867. an indirect buffer clone of the current buffer, to avoid any visibility
  1868. changes to the current buffer."
  1869. :group 'org-link-follow
  1870. :type 'boolean)
  1871. (defcustom org-open-non-existing-files nil
  1872. "Non-nil means `org-open-file' will open non-existing files.
  1873. When nil, an error will be generated.
  1874. This variable applies only to external applications because they
  1875. might choke on non-existing files. If the link is to a file that
  1876. will be opened in Emacs, the variable is ignored."
  1877. :group 'org-link-follow
  1878. :type 'boolean)
  1879. (defcustom org-open-directory-means-index-dot-org nil
  1880. "Non-nil means a link to a directory really means to index.org.
  1881. When nil, following a directory link will run dired or open a finder/explorer
  1882. window on that directory."
  1883. :group 'org-link-follow
  1884. :type 'boolean)
  1885. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1886. "Non-nil means ask for confirmation before executing shell links.
  1887. Shell links can be dangerous: just think about a link
  1888. [[shell:rm -rf ~/*][Google Search]]
  1889. This link would show up in your Org document as \"Google Search\",
  1890. but really it would remove your entire home directory.
  1891. Therefore we advise against setting this variable to nil.
  1892. Just change it to `y-or-n-p' if you want to confirm with a
  1893. single keystroke rather than having to type \"yes\"."
  1894. :group 'org-link-follow
  1895. :type '(choice
  1896. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1897. (const :tag "with y-or-n (faster)" y-or-n-p)
  1898. (const :tag "no confirmation (dangerous)" nil)))
  1899. (put 'org-confirm-shell-link-function
  1900. 'safe-local-variable
  1901. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1902. (defcustom org-confirm-shell-link-not-regexp ""
  1903. "A regexp to skip confirmation for shell links."
  1904. :group 'org-link-follow
  1905. :version "24.1"
  1906. :type 'regexp)
  1907. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1908. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1909. Elisp links can be dangerous: just think about a link
  1910. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1911. This link would show up in your Org document as \"Google Search\",
  1912. but really it would remove your entire home directory.
  1913. Therefore we advise against setting this variable to nil.
  1914. Just change it to `y-or-n-p' if you want to confirm with a
  1915. single keystroke rather than having to type \"yes\"."
  1916. :group 'org-link-follow
  1917. :type '(choice
  1918. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1919. (const :tag "with y-or-n (faster)" y-or-n-p)
  1920. (const :tag "no confirmation (dangerous)" nil)))
  1921. (put 'org-confirm-shell-link-function
  1922. 'safe-local-variable
  1923. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1924. (defcustom org-confirm-elisp-link-not-regexp ""
  1925. "A regexp to skip confirmation for Elisp links."
  1926. :group 'org-link-follow
  1927. :version "24.1"
  1928. :type 'regexp)
  1929. (defconst org-file-apps-defaults-gnu
  1930. '((remote . emacs)
  1931. (system . mailcap)
  1932. (t . mailcap))
  1933. "Default file applications on a UNIX or GNU/Linux system.
  1934. See `org-file-apps'.")
  1935. (defconst org-file-apps-defaults-macosx
  1936. '((remote . emacs)
  1937. (system . "open %s")
  1938. ("ps.gz" . "gv %s")
  1939. ("eps.gz" . "gv %s")
  1940. ("dvi" . "xdvi %s")
  1941. ("fig" . "xfig %s")
  1942. (t . "open %s"))
  1943. "Default file applications on a macOS system.
  1944. The system \"open\" is known as a default, but we use X11 applications
  1945. for some files for which the OS does not have a good default.
  1946. See `org-file-apps'.")
  1947. (defconst org-file-apps-defaults-windowsnt
  1948. (list '(remote . emacs)
  1949. (cons 'system (lambda (file _path)
  1950. (with-no-warnings (w32-shell-execute "open" file))))
  1951. (cons t (lambda (file _path)
  1952. (with-no-warnings (w32-shell-execute "open" file)))))
  1953. "Default file applications on a Windows NT system.
  1954. The system \"open\" is used for most files.
  1955. See `org-file-apps'.")
  1956. (defcustom org-file-apps
  1957. '((auto-mode . emacs)
  1958. ("\\.mm\\'" . default)
  1959. ("\\.x?html?\\'" . default)
  1960. ("\\.pdf\\'" . default))
  1961. "External applications for opening `file:path' items in a document.
  1962. \\<org-mode-map>\
  1963. Org mode uses system defaults for different file types, but
  1964. you can use this variable to set the application for a given file
  1965. extension. The entries in this list are cons cells where the car identifies
  1966. files and the cdr the corresponding command.
  1967. Possible values for the file identifier are:
  1968. \"string\" A string as a file identifier can be interpreted in different
  1969. ways, depending on its contents:
  1970. - Alphanumeric characters only:
  1971. Match links with this file extension.
  1972. Example: (\"pdf\" . \"evince %s\")
  1973. to open PDFs with evince.
  1974. - Regular expression: Match links where the
  1975. filename matches the regexp. If you want to
  1976. use groups here, use shy groups.
  1977. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1978. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1979. to open *.html and *.xhtml with firefox.
  1980. - Regular expression which contains (non-shy) groups:
  1981. Match links where the whole link, including \"::\", and
  1982. anything after that, matches the regexp.
  1983. In a custom command string, %1, %2, etc. are replaced with
  1984. the parts of the link that were matched by the groups.
  1985. For backwards compatibility, if a command string is given
  1986. that does not use any of the group matches, this case is
  1987. handled identically to the second one (i.e. match against
  1988. file name only).
  1989. In a custom function, you can access the group matches with
  1990. (match-string n link).
  1991. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1992. \"evince -p %1 %s\")
  1993. to open [[file:document.pdf::5]] with evince at page 5.
  1994. `directory' Matches a directory
  1995. `remote' Matches a remote file, accessible through tramp or efs.
  1996. Remote files most likely should be visited through Emacs
  1997. because external applications cannot handle such paths.
  1998. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1999. so all files Emacs knows how to handle. Using this with
  2000. command `emacs' will open most files in Emacs. Beware that this
  2001. will also open html files inside Emacs, unless you add
  2002. (\"html\" . default) to the list as well.
  2003. `system' The system command to open files, like `open' on Windows
  2004. and macOS, and mailcap under GNU/Linux. This is the command
  2005. that will be selected if you call `org-open-at-point' with a
  2006. double prefix argument (`\\[universal-argument] \
  2007. \\[universal-argument] \\[org-open-at-point]').
  2008. t Default for files not matched by any of the other options.
  2009. Possible values for the command are:
  2010. `emacs' The file will be visited by the current Emacs process.
  2011. `default' Use the default application for this file type, which is the
  2012. association for t in the list, most likely in the system-specific
  2013. part. This can be used to overrule an unwanted setting in the
  2014. system-specific variable.
  2015. `system' Use the system command for opening files, like \"open\".
  2016. This command is specified by the entry whose car is `system'.
  2017. Most likely, the system-specific version of this variable
  2018. does define this command, but you can overrule/replace it
  2019. here.
  2020. `mailcap' Use command specified in the mailcaps.
  2021. string A command to be executed by a shell; %s will be replaced
  2022. by the path to the file.
  2023. function A Lisp function, which will be called with two arguments:
  2024. the file path and the original link string, without the
  2025. \"file:\" prefix.
  2026. For more examples, see the system specific constants
  2027. `org-file-apps-defaults-macosx'
  2028. `org-file-apps-defaults-windowsnt'
  2029. `org-file-apps-defaults-gnu'."
  2030. :group 'org-link-follow
  2031. :type '(repeat
  2032. (cons (choice :value ""
  2033. (string :tag "Extension")
  2034. (const :tag "System command to open files" system)
  2035. (const :tag "Default for unrecognized files" t)
  2036. (const :tag "Remote file" remote)
  2037. (const :tag "Links to a directory" directory)
  2038. (const :tag "Any files that have Emacs modes"
  2039. auto-mode))
  2040. (choice :value ""
  2041. (const :tag "Visit with Emacs" emacs)
  2042. (const :tag "Use default" default)
  2043. (const :tag "Use the system command" system)
  2044. (string :tag "Command")
  2045. (function :tag "Function")))))
  2046. (defcustom org-doi-server-url "http://dx.doi.org/"
  2047. "The URL of the DOI server."
  2048. :type 'string
  2049. :version "24.3"
  2050. :group 'org-link-follow)
  2051. (defgroup org-refile nil
  2052. "Options concerning refiling entries in Org mode."
  2053. :tag "Org Refile"
  2054. :group 'org)
  2055. (defcustom org-directory "~/org"
  2056. "Directory with Org files.
  2057. This is just a default location to look for Org files. There is no need
  2058. at all to put your files into this directory. It is used in the
  2059. following situations:
  2060. 1. When a capture template specifies a target file that is not an
  2061. absolute path. The path will then be interpreted relative to
  2062. `org-directory'
  2063. 2. When the value of variable `org-agenda-files' is a single file, any
  2064. relative paths in this file will be taken as relative to
  2065. `org-directory'."
  2066. :group 'org-refile
  2067. :group 'org-capture
  2068. :type 'directory)
  2069. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2070. "Default target for storing notes.
  2071. Used as a fall back file for org-capture.el, for templates that
  2072. do not specify a target file."
  2073. :group 'org-refile
  2074. :group 'org-capture
  2075. :type 'file)
  2076. (defcustom org-goto-interface 'outline
  2077. "The default interface to be used for `org-goto'.
  2078. Allowed values are:
  2079. outline The interface shows an outline of the relevant file
  2080. and the correct heading is found by moving through
  2081. the outline or by searching with incremental search.
  2082. outline-path-completion Headlines in the current buffer are offered via
  2083. completion. This is the interface also used by
  2084. the refile command."
  2085. :group 'org-refile
  2086. :type '(choice
  2087. (const :tag "Outline" outline)
  2088. (const :tag "Outline-path-completion" outline-path-completion)))
  2089. (defcustom org-goto-max-level 5
  2090. "Maximum target level when running `org-goto' with refile interface."
  2091. :group 'org-refile
  2092. :type 'integer)
  2093. (defcustom org-reverse-note-order nil
  2094. "Non-nil means store new notes at the beginning of a file or entry.
  2095. When nil, new notes will be filed to the end of a file or entry.
  2096. This can also be a list with cons cells of regular expressions that
  2097. are matched against file names, and values."
  2098. :group 'org-capture
  2099. :group 'org-refile
  2100. :type '(choice
  2101. (const :tag "Reverse always" t)
  2102. (const :tag "Reverse never" nil)
  2103. (repeat :tag "By file name regexp"
  2104. (cons regexp boolean))))
  2105. (defcustom org-log-refile nil
  2106. "Information to record when a task is refiled.
  2107. Possible values are:
  2108. nil Don't add anything
  2109. time Add a time stamp to the task
  2110. note Prompt for a note and add it with template `org-log-note-headings'
  2111. This option can also be set with on a per-file-basis with
  2112. #+STARTUP: nologrefile
  2113. #+STARTUP: logrefile
  2114. #+STARTUP: lognoterefile
  2115. You can have local logging settings for a subtree by setting the LOGGING
  2116. property to one or more of these keywords.
  2117. When bulk-refiling from the agenda, the value `note' is forbidden and
  2118. will temporarily be changed to `time'."
  2119. :group 'org-refile
  2120. :group 'org-progress
  2121. :version "24.1"
  2122. :type '(choice
  2123. (const :tag "No logging" nil)
  2124. (const :tag "Record timestamp" time)
  2125. (const :tag "Record timestamp with note." note)))
  2126. (defcustom org-refile-targets nil
  2127. "Targets for refiling entries with `\\[org-refile]'.
  2128. This is a list of cons cells. Each cell contains:
  2129. - a specification of the files to be considered, either a list of files,
  2130. or a symbol whose function or variable value will be used to retrieve
  2131. a file name or a list of file names. If you use `org-agenda-files' for
  2132. that, all agenda files will be scanned for targets. Nil means consider
  2133. headings in the current buffer.
  2134. - A specification of how to find candidate refile targets. This may be
  2135. any of:
  2136. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2137. This tag has to be present in all target headlines, inheritance will
  2138. not be considered.
  2139. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2140. todo keyword.
  2141. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2142. headlines that are refiling targets.
  2143. - a cons cell (:level . N). Any headline of level N is considered a target.
  2144. Note that, when `org-odd-levels-only' is set, level corresponds to
  2145. order in hierarchy, not to the number of stars.
  2146. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2147. Note that, when `org-odd-levels-only' is set, level corresponds to
  2148. order in hierarchy, not to the number of stars.
  2149. Each element of this list generates a set of possible targets.
  2150. The union of these sets is presented (with completion) to
  2151. the user by `org-refile'.
  2152. You can set the variable `org-refile-target-verify-function' to a function
  2153. to verify each headline found by the simple criteria above.
  2154. When this variable is nil, all top-level headlines in the current buffer
  2155. are used, equivalent to the value `((nil . (:level . 1))'."
  2156. :group 'org-refile
  2157. :type '(repeat
  2158. (cons
  2159. (choice :value org-agenda-files
  2160. (const :tag "All agenda files" org-agenda-files)
  2161. (const :tag "Current buffer" nil)
  2162. (function) (variable) (file))
  2163. (choice :tag "Identify target headline by"
  2164. (cons :tag "Specific tag" (const :value :tag) (string))
  2165. (cons :tag "TODO keyword" (const :value :todo) (string))
  2166. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2167. (cons :tag "Level number" (const :value :level) (integer))
  2168. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2169. (defcustom org-refile-target-verify-function nil
  2170. "Function to verify if the headline at point should be a refile target.
  2171. The function will be called without arguments, with point at the
  2172. beginning of the headline. It should return t and leave point
  2173. where it is if the headline is a valid target for refiling.
  2174. If the target should not be selected, the function must return nil.
  2175. In addition to this, it may move point to a place from where the search
  2176. should be continued. For example, the function may decide that the entire
  2177. subtree of the current entry should be excluded and move point to the end
  2178. of the subtree."
  2179. :group 'org-refile
  2180. :type '(choice
  2181. (const nil)
  2182. (function)))
  2183. (defcustom org-refile-use-cache nil
  2184. "Non-nil means cache refile targets to speed up the process.
  2185. \\<org-mode-map>\
  2186. The cache for a particular file will be updated automatically when
  2187. the buffer has been killed, or when any of the marker used for flagging
  2188. refile targets no longer points at a live buffer.
  2189. If you have added new entries to a buffer that might themselves be targets,
  2190. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2191. if you find that easier, \
  2192. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2193. \\[org-refile]'."
  2194. :group 'org-refile
  2195. :version "24.1"
  2196. :type 'boolean)
  2197. (defcustom org-refile-use-outline-path nil
  2198. "Non-nil means provide refile targets as paths.
  2199. So a level 3 headline will be available as level1/level2/level3.
  2200. When the value is `file', also include the file name (without directory)
  2201. into the path. In this case, you can also stop the completion after
  2202. the file name, to get entries inserted as top level in the file.
  2203. When `full-file-path', include the full file path.
  2204. When `buffer-name', use the buffer name."
  2205. :group 'org-refile
  2206. :type '(choice
  2207. (const :tag "Not" nil)
  2208. (const :tag "Yes" t)
  2209. (const :tag "Start with file name" file)
  2210. (const :tag "Start with full file path" full-file-path)
  2211. (const :tag "Start with buffer name" buffer-name)))
  2212. (defcustom org-outline-path-complete-in-steps t
  2213. "Non-nil means complete the outline path in hierarchical steps.
  2214. When Org uses the refile interface to select an outline path (see
  2215. `org-refile-use-outline-path'), the completion of the path can be
  2216. done in a single go, or it can be done in steps down the headline
  2217. hierarchy. Going in steps is probably the best if you do not use
  2218. a special completion package like `ido' or `icicles'. However,
  2219. when using these packages, going in one step can be very fast,
  2220. while still showing the whole path to the entry."
  2221. :group 'org-refile
  2222. :type 'boolean)
  2223. (defcustom org-refile-allow-creating-parent-nodes nil
  2224. "Non-nil means allow the creation of new nodes as refile targets.
  2225. New nodes are then created by adding \"/new node name\" to the completion
  2226. of an existing node. When the value of this variable is `confirm',
  2227. new node creation must be confirmed by the user (recommended).
  2228. When nil, the completion must match an existing entry.
  2229. Note that, if the new heading is not seen by the criteria
  2230. listed in `org-refile-targets', multiple instances of the same
  2231. heading would be created by trying again to file under the new
  2232. heading."
  2233. :group 'org-refile
  2234. :type '(choice
  2235. (const :tag "Never" nil)
  2236. (const :tag "Always" t)
  2237. (const :tag "Prompt for confirmation" confirm)))
  2238. (defcustom org-refile-active-region-within-subtree nil
  2239. "Non-nil means also refile active region within a subtree.
  2240. By default `org-refile' doesn't allow refiling regions if they
  2241. don't contain a set of subtrees, but it might be convenient to
  2242. do so sometimes: in that case, the first line of the region is
  2243. converted to a headline before refiling."
  2244. :group 'org-refile
  2245. :version "24.1"
  2246. :type 'boolean)
  2247. (defgroup org-todo nil
  2248. "Options concerning TODO items in Org mode."
  2249. :tag "Org TODO"
  2250. :group 'org)
  2251. (defgroup org-progress nil
  2252. "Options concerning Progress logging in Org mode."
  2253. :tag "Org Progress"
  2254. :group 'org-time)
  2255. (defvar org-todo-interpretation-widgets
  2256. '((:tag "Sequence (cycling hits every state)" sequence)
  2257. (:tag "Type (cycling directly to DONE)" type))
  2258. "The available interpretation symbols for customizing `org-todo-keywords'.
  2259. Interested libraries should add to this list.")
  2260. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2261. "List of TODO entry keyword sequences and their interpretation.
  2262. \\<org-mode-map>This is a list of sequences.
  2263. Each sequence starts with a symbol, either `sequence' or `type',
  2264. indicating if the keywords should be interpreted as a sequence of
  2265. action steps, or as different types of TODO items. The first
  2266. keywords are states requiring action - these states will select a headline
  2267. for inclusion into the global TODO list Org produces. If one of the
  2268. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2269. signify that no further action is necessary. If \"|\" is not found,
  2270. the last keyword is treated as the only DONE state of the sequence.
  2271. The command `\\[org-todo]' cycles an entry through these states, and one
  2272. additional state where no keyword is present. For details about this
  2273. cycling, see the manual.
  2274. TODO keywords and interpretation can also be set on a per-file basis with
  2275. the special #+SEQ_TODO and #+TYP_TODO lines.
  2276. Each keyword can optionally specify a character for fast state selection
  2277. \(in combination with the variable `org-use-fast-todo-selection')
  2278. and specifiers for state change logging, using the same syntax that
  2279. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2280. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2281. indicates to record a time stamp each time this state is selected.
  2282. Each keyword may also specify if a timestamp or a note should be
  2283. recorded when entering or leaving the state, by adding additional
  2284. characters in the parenthesis after the keyword. This looks like this:
  2285. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2286. record only the time of the state change. With X and Y being either
  2287. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2288. Y when leaving the state if and only if the *target* state does not
  2289. define X. You may omit any of the fast-selection key or X or /Y,
  2290. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2291. For backward compatibility, this variable may also be just a list
  2292. of keywords. In this case the interpretation (sequence or type) will be
  2293. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2294. :group 'org-todo
  2295. :group 'org-keywords
  2296. :type '(choice
  2297. (repeat :tag "Old syntax, just keywords"
  2298. (string :tag "Keyword"))
  2299. (repeat :tag "New syntax"
  2300. (cons
  2301. (choice
  2302. :tag "Interpretation"
  2303. ;;Quick and dirty way to see
  2304. ;;`org-todo-interpretations'. This takes the
  2305. ;;place of item arguments
  2306. :convert-widget
  2307. (lambda (widget)
  2308. (widget-put widget
  2309. :args (mapcar
  2310. (lambda (x)
  2311. (widget-convert
  2312. (cons 'const x)))
  2313. org-todo-interpretation-widgets))
  2314. widget))
  2315. (repeat
  2316. (string :tag "Keyword"))))))
  2317. (defvar-local org-todo-keywords-1 nil
  2318. "All TODO and DONE keywords active in a buffer.")
  2319. (defvar org-todo-keywords-for-agenda nil)
  2320. (defvar org-done-keywords-for-agenda nil)
  2321. (defvar org-todo-keyword-alist-for-agenda nil)
  2322. (defvar org-tag-alist-for-agenda nil
  2323. "Alist of all tags from all agenda files.")
  2324. (defvar org-tag-groups-alist-for-agenda nil
  2325. "Alist of all groups tags from all current agenda files.")
  2326. (defvar-local org-tag-groups-alist nil)
  2327. (defvar org-agenda-contributing-files nil)
  2328. (defvar-local org-current-tag-alist nil
  2329. "Alist of all tag groups in current buffer.
  2330. This variable takes into consideration `org-tag-alist',
  2331. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2332. (defvar-local org-not-done-keywords nil)
  2333. (defvar-local org-done-keywords nil)
  2334. (defvar-local org-todo-heads nil)
  2335. (defvar-local org-todo-sets nil)
  2336. (defvar-local org-todo-log-states nil)
  2337. (defvar-local org-todo-kwd-alist nil)
  2338. (defvar-local org-todo-key-alist nil)
  2339. (defvar-local org-todo-key-trigger nil)
  2340. (defcustom org-todo-interpretation 'sequence
  2341. "Controls how TODO keywords are interpreted.
  2342. This variable is in principle obsolete and is only used for
  2343. backward compatibility, if the interpretation of todo keywords is
  2344. not given already in `org-todo-keywords'. See that variable for
  2345. more information."
  2346. :group 'org-todo
  2347. :group 'org-keywords
  2348. :type '(choice (const sequence)
  2349. (const type)))
  2350. (defcustom org-use-fast-todo-selection t
  2351. "\\<org-mode-map>\
  2352. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2353. This variable describes if and under what circumstances the cycling
  2354. mechanism for TODO keywords will be replaced by a single-key, direct
  2355. selection scheme.
  2356. When nil, fast selection is never used.
  2357. When the symbol `prefix', it will be used when `org-todo' is called
  2358. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2359. in an Org buffer, and
  2360. `\\[universal-argument] t' in an agenda buffer.
  2361. When t, fast selection is used by default. In this case, the prefix
  2362. argument forces cycling instead.
  2363. In all cases, the special interface is only used if access keys have
  2364. actually been assigned by the user, i.e. if keywords in the configuration
  2365. are followed by a letter in parenthesis, like TODO(t)."
  2366. :group 'org-todo
  2367. :type '(choice
  2368. (const :tag "Never" nil)
  2369. (const :tag "By default" t)
  2370. (const :tag "Only with C-u C-c C-t" prefix)))
  2371. (defcustom org-provide-todo-statistics t
  2372. "Non-nil means update todo statistics after insert and toggle.
  2373. ALL-HEADLINES means update todo statistics by including headlines
  2374. with no TODO keyword as well, counting them as not done.
  2375. A list of TODO keywords means the same, but skip keywords that are
  2376. not in this list.
  2377. When set to a list of two lists, the first list contains keywords
  2378. to consider as TODO keywords, the second list contains keywords
  2379. to consider as DONE keywords.
  2380. When this is set, todo statistics is updated in the parent of the
  2381. current entry each time a todo state is changed."
  2382. :group 'org-todo
  2383. :type '(choice
  2384. (const :tag "Yes, only for TODO entries" t)
  2385. (const :tag "Yes, including all entries" all-headlines)
  2386. (repeat :tag "Yes, for TODOs in this list"
  2387. (string :tag "TODO keyword"))
  2388. (list :tag "Yes, for TODOs and DONEs in these lists"
  2389. (repeat (string :tag "TODO keyword"))
  2390. (repeat (string :tag "DONE keyword")))
  2391. (other :tag "No TODO statistics" nil)))
  2392. (defcustom org-hierarchical-todo-statistics t
  2393. "Non-nil means TODO statistics covers just direct children.
  2394. When nil, all entries in the subtree are considered.
  2395. This has only an effect if `org-provide-todo-statistics' is set.
  2396. To set this to nil for only a single subtree, use a COOKIE_DATA
  2397. property and include the word \"recursive\" into the value."
  2398. :group 'org-todo
  2399. :type 'boolean)
  2400. (defcustom org-after-todo-state-change-hook nil
  2401. "Hook which is run after the state of a TODO item was changed.
  2402. The new state (a string with a TODO keyword, or nil) is available in the
  2403. Lisp variable `org-state'."
  2404. :group 'org-todo
  2405. :type 'hook)
  2406. (defvar org-blocker-hook nil
  2407. "Hook for functions that are allowed to block a state change.
  2408. Functions in this hook should not modify the buffer.
  2409. Each function gets as its single argument a property list,
  2410. see `org-trigger-hook' for more information about this list.
  2411. If any of the functions in this hook returns nil, the state change
  2412. is blocked.")
  2413. (defvar org-trigger-hook nil
  2414. "Hook for functions that are triggered by a state change.
  2415. Each function gets as its single argument a property list with at
  2416. least the following elements:
  2417. (:type type-of-change :position pos-at-entry-start
  2418. :from old-state :to new-state)
  2419. Depending on the type, more properties may be present.
  2420. This mechanism is currently implemented for:
  2421. TODO state changes
  2422. ------------------
  2423. :type todo-state-change
  2424. :from previous state (keyword as a string), or nil, or a symbol
  2425. `todo' or `done', to indicate the general type of state.
  2426. :to new state, like in :from")
  2427. (defcustom org-enforce-todo-dependencies nil
  2428. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2429. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2430. be blocked if any prior sibling is not yet done.
  2431. Finally, if the parent is blocked because of ordered siblings of its own,
  2432. the child will also be blocked."
  2433. :set (lambda (var val)
  2434. (set var val)
  2435. (if val
  2436. (add-hook 'org-blocker-hook
  2437. 'org-block-todo-from-children-or-siblings-or-parent)
  2438. (remove-hook 'org-blocker-hook
  2439. 'org-block-todo-from-children-or-siblings-or-parent)))
  2440. :group 'org-todo
  2441. :type 'boolean)
  2442. (defcustom org-enforce-todo-checkbox-dependencies nil
  2443. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2444. When this is nil, checkboxes have no influence on switching TODO states.
  2445. When non-nil, you first need to check off all check boxes before the TODO
  2446. entry can be switched to DONE.
  2447. This variable needs to be set before org.el is loaded, and you need to
  2448. restart Emacs after a change to make the change effective. The only way
  2449. to change is while Emacs is running is through the customize interface."
  2450. :set (lambda (var val)
  2451. (set var val)
  2452. (if val
  2453. (add-hook 'org-blocker-hook
  2454. 'org-block-todo-from-checkboxes)
  2455. (remove-hook 'org-blocker-hook
  2456. 'org-block-todo-from-checkboxes)))
  2457. :group 'org-todo
  2458. :type 'boolean)
  2459. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2460. "Non-nil means inserting a TODO heading is treated as state change.
  2461. So when the command `\\[org-insert-todo-heading]' is used, state change
  2462. logging will apply if appropriate. When nil, the new TODO item will
  2463. be inserted directly, and no logging will take place."
  2464. :group 'org-todo
  2465. :type 'boolean)
  2466. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2467. "Non-nil means switching TODO states with S-cursor counts as state change.
  2468. This is the default behavior. However, setting this to nil allows a
  2469. convenient way to select a TODO state and bypass any logging associated
  2470. with that."
  2471. :group 'org-todo
  2472. :type 'boolean)
  2473. (defcustom org-todo-state-tags-triggers nil
  2474. "Tag changes that should be triggered by TODO state changes.
  2475. This is a list. Each entry is
  2476. (state-change (tag . flag) .......)
  2477. State-change can be a string with a state, and empty string to indicate the
  2478. state that has no TODO keyword, or it can be one of the symbols `todo'
  2479. or `done', meaning any not-done or done state, respectively."
  2480. :group 'org-todo
  2481. :group 'org-tags
  2482. :type '(repeat
  2483. (cons (choice :tag "When changing to"
  2484. (const :tag "Not-done state" todo)
  2485. (const :tag "Done state" done)
  2486. (string :tag "State"))
  2487. (repeat
  2488. (cons :tag "Tag action"
  2489. (string :tag "Tag")
  2490. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2491. (defcustom org-log-done nil
  2492. "Information to record when a task moves to the DONE state.
  2493. Possible values are:
  2494. nil Don't add anything, just change the keyword
  2495. time Add a time stamp to the task
  2496. note Prompt for a note and add it with template `org-log-note-headings'
  2497. This option can also be set with on a per-file-basis with
  2498. #+STARTUP: nologdone
  2499. #+STARTUP: logdone
  2500. #+STARTUP: lognotedone
  2501. You can have local logging settings for a subtree by setting the LOGGING
  2502. property to one or more of these keywords."
  2503. :group 'org-todo
  2504. :group 'org-progress
  2505. :type '(choice
  2506. (const :tag "No logging" nil)
  2507. (const :tag "Record CLOSED timestamp" time)
  2508. (const :tag "Record CLOSED timestamp with note." note)))
  2509. ;; Normalize old uses of org-log-done.
  2510. (cond
  2511. ((eq org-log-done t) (setq org-log-done 'time))
  2512. ((and (listp org-log-done) (memq 'done org-log-done))
  2513. (setq org-log-done 'note)))
  2514. (defcustom org-log-reschedule nil
  2515. "Information to record when the scheduling date of a tasks is modified.
  2516. Possible values are:
  2517. nil Don't add anything, just change the date
  2518. time Add a time stamp to the task
  2519. note Prompt for a note and add it with template `org-log-note-headings'
  2520. This option can also be set with on a per-file-basis with
  2521. #+STARTUP: nologreschedule
  2522. #+STARTUP: logreschedule
  2523. #+STARTUP: lognotereschedule"
  2524. :group 'org-todo
  2525. :group 'org-progress
  2526. :type '(choice
  2527. (const :tag "No logging" nil)
  2528. (const :tag "Record timestamp" time)
  2529. (const :tag "Record timestamp with note." note)))
  2530. (defcustom org-log-redeadline nil
  2531. "Information to record when the deadline date of a tasks is modified.
  2532. Possible values are:
  2533. nil Don't add anything, just change the date
  2534. time Add a time stamp to the task
  2535. note Prompt for a note and add it with template `org-log-note-headings'
  2536. This option can also be set with on a per-file-basis with
  2537. #+STARTUP: nologredeadline
  2538. #+STARTUP: logredeadline
  2539. #+STARTUP: lognoteredeadline
  2540. You can have local logging settings for a subtree by setting the LOGGING
  2541. property to one or more of these keywords."
  2542. :group 'org-todo
  2543. :group 'org-progress
  2544. :type '(choice
  2545. (const :tag "No logging" nil)
  2546. (const :tag "Record timestamp" time)
  2547. (const :tag "Record timestamp with note." note)))
  2548. (defcustom org-log-note-clock-out nil
  2549. "Non-nil means record a note when clocking out of an item.
  2550. This can also be configured on a per-file basis by adding one of
  2551. the following lines anywhere in the buffer:
  2552. #+STARTUP: lognoteclock-out
  2553. #+STARTUP: nolognoteclock-out"
  2554. :group 'org-todo
  2555. :group 'org-progress
  2556. :type 'boolean)
  2557. (defcustom org-log-done-with-time t
  2558. "Non-nil means the CLOSED time stamp will contain date and time.
  2559. When nil, only the date will be recorded."
  2560. :group 'org-progress
  2561. :type 'boolean)
  2562. (defcustom org-log-note-headings
  2563. '((done . "CLOSING NOTE %t")
  2564. (state . "State %-12s from %-12S %t")
  2565. (note . "Note taken on %t")
  2566. (reschedule . "Rescheduled from %S on %t")
  2567. (delschedule . "Not scheduled, was %S on %t")
  2568. (redeadline . "New deadline from %S on %t")
  2569. (deldeadline . "Removed deadline, was %S on %t")
  2570. (refile . "Refiled on %t")
  2571. (clock-out . ""))
  2572. "Headings for notes added to entries.
  2573. The value is an alist, with the car being a symbol indicating the
  2574. note context, and the cdr is the heading to be used. The heading
  2575. may also be the empty string. The following placeholders can be
  2576. used:
  2577. %t a time stamp.
  2578. %T an active time stamp instead the default inactive one
  2579. %d a short-format time stamp.
  2580. %D an active short-format time stamp.
  2581. %s the new TODO state or time stamp (inactive), in double quotes.
  2582. %S the old TODO state or time stamp (inactive), in double quotes.
  2583. %u the user name.
  2584. %U full user name.
  2585. In fact, it is not a good idea to change the `state' entry,
  2586. because Agenda Log mode depends on the format of these entries."
  2587. :group 'org-todo
  2588. :group 'org-progress
  2589. :type '(list :greedy t
  2590. (cons (const :tag "Heading when closing an item" done) string)
  2591. (cons (const :tag
  2592. "Heading when changing todo state (todo sequence only)"
  2593. state) string)
  2594. (cons (const :tag "Heading when just taking a note" note) string)
  2595. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2596. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2597. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2598. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2599. (cons (const :tag "Heading when refiling" refile) string)
  2600. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2601. (unless (assq 'note org-log-note-headings)
  2602. (push '(note . "%t") org-log-note-headings))
  2603. (defcustom org-log-into-drawer nil
  2604. "Non-nil means insert state change notes and time stamps into a drawer.
  2605. When nil, state changes notes will be inserted after the headline and
  2606. any scheduling and clock lines, but not inside a drawer.
  2607. The value of this variable should be the name of the drawer to use.
  2608. LOGBOOK is proposed as the default drawer for this purpose, you can
  2609. also set this to a string to define the drawer of your choice.
  2610. A value of t is also allowed, representing \"LOGBOOK\".
  2611. A value of t or nil can also be set with on a per-file-basis with
  2612. #+STARTUP: logdrawer
  2613. #+STARTUP: nologdrawer
  2614. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2615. will be ignored.
  2616. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2617. a subtree.
  2618. Do not check directly this variable in a Lisp program. Call
  2619. function `org-log-into-drawer' instead."
  2620. :group 'org-todo
  2621. :group 'org-progress
  2622. :type '(choice
  2623. (const :tag "Not into a drawer" nil)
  2624. (const :tag "LOGBOOK" t)
  2625. (string :tag "Other")))
  2626. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2627. (defun org-log-into-drawer ()
  2628. "Name of the log drawer, as a string, or nil.
  2629. This is the value of `org-log-into-drawer'. However, if the
  2630. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2631. be used instead of the default value."
  2632. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2633. (cond ((equal p "nil") nil)
  2634. ((equal p "t") "LOGBOOK")
  2635. ((stringp p) p)
  2636. (p "LOGBOOK")
  2637. ((stringp org-log-into-drawer) org-log-into-drawer)
  2638. (org-log-into-drawer "LOGBOOK"))))
  2639. (defcustom org-log-state-notes-insert-after-drawers nil
  2640. "Non-nil means insert state change notes after any drawers in entry.
  2641. Only the drawers that *immediately* follow the headline and the
  2642. deadline/scheduled line are skipped.
  2643. When nil, insert notes right after the heading and perhaps the line
  2644. with deadline/scheduling if present.
  2645. This variable will have no effect if `org-log-into-drawer' is
  2646. set."
  2647. :group 'org-todo
  2648. :group 'org-progress
  2649. :type 'boolean)
  2650. (defcustom org-log-states-order-reversed t
  2651. "Non-nil means the latest state note will be directly after heading.
  2652. When nil, the state change notes will be ordered according to time.
  2653. This option can also be set with on a per-file-basis with
  2654. #+STARTUP: logstatesreversed
  2655. #+STARTUP: nologstatesreversed"
  2656. :group 'org-todo
  2657. :group 'org-progress
  2658. :type 'boolean)
  2659. (defcustom org-todo-repeat-to-state nil
  2660. "The TODO state to which a repeater should return the repeating task.
  2661. By default this is the first task in a TODO sequence, or the previous state
  2662. in a TODO_TYP set. But you can specify another task here.
  2663. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2664. :group 'org-todo
  2665. :version "24.1"
  2666. :type '(choice (const :tag "Head of sequence" nil)
  2667. (string :tag "Specific 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', `:engroup', `: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 (string :tag "Tag name")
  2960. (character :tag "Access char"))
  2961. (const :tag "Start radio group" (:startgroup))
  2962. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2963. (const :tag "Group tags delimiter" (:grouptags))
  2964. (const :tag "End radio group" (:endgroup))
  2965. (const :tag "End tag group, non distinct" (:endgrouptag))
  2966. (const :tag "New line" (:newline)))))
  2967. (defcustom org-tag-persistent-alist nil
  2968. "Tags always available in Org files.
  2969. The value of this variable is an alist. Associations either:
  2970. (TAG)
  2971. (TAG . SELECT)
  2972. (SPECIAL)
  2973. where TAG is a tag as a string, SELECT is a character, used to
  2974. select that tag through the fast tag selection interface, and
  2975. SPECIAL is one of the following keywords: `:startgroup',
  2976. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2977. `:newline'. These keywords are used to define a hierarchy of
  2978. tags. See manual for details.
  2979. Unlike to `org-tag-alist', tags defined in this variable do not
  2980. depend on a local TAGS keyword. Instead, to disable these tags
  2981. on a per-file basis, insert anywhere in the file:
  2982. #+STARTUP: noptag"
  2983. :group 'org-tags
  2984. :type '(repeat
  2985. (choice
  2986. (cons (string :tag "Tag name")
  2987. (character :tag "Access char"))
  2988. (const :tag "Start radio group" (:startgroup))
  2989. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2990. (const :tag "Group tags delimiter" (:grouptags))
  2991. (const :tag "End radio group" (:endgroup))
  2992. (const :tag "End tag group, non distinct" (:endgrouptag))
  2993. (const :tag "New line" (:newline)))))
  2994. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2995. "If non-nil, always offer completion for all tags of all agenda files.
  2996. Instead of customizing this variable directly, you might want to
  2997. set it locally for capture buffers, because there no list of
  2998. tags in that file can be created dynamically (there are none).
  2999. (add-hook \\='org-capture-mode-hook
  3000. (lambda ()
  3001. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3002. :group 'org-tags
  3003. :version "24.1"
  3004. :type 'boolean)
  3005. (defvar org-file-tags nil
  3006. "List of tags that can be inherited by all entries in the file.
  3007. The tags will be inherited if the variable `org-use-tag-inheritance'
  3008. says they should be.
  3009. This variable is populated from #+FILETAGS lines.")
  3010. (defcustom org-use-fast-tag-selection 'auto
  3011. "Non-nil means use fast tag selection scheme.
  3012. This is a special interface to select and deselect tags with single keys.
  3013. When nil, fast selection is never used.
  3014. When the symbol `auto', fast selection is used if and only if selection
  3015. characters for tags have been configured, either through the variable
  3016. `org-tag-alist' or through a #+TAGS line in the buffer.
  3017. When t, fast selection is always used and selection keys are assigned
  3018. automatically if necessary."
  3019. :group 'org-tags
  3020. :type '(choice
  3021. (const :tag "Always" t)
  3022. (const :tag "Never" nil)
  3023. (const :tag "When selection characters are configured" auto)))
  3024. (defcustom org-fast-tag-selection-single-key nil
  3025. "Non-nil means fast tag selection exits after first change.
  3026. When nil, you have to press RET to exit it.
  3027. During fast tag selection, you can toggle this flag with `C-c'.
  3028. This variable can also have the value `expert'. In this case, the window
  3029. displaying the tags menu is not even shown, until you press C-c again."
  3030. :group 'org-tags
  3031. :type '(choice
  3032. (const :tag "No" nil)
  3033. (const :tag "Yes" t)
  3034. (const :tag "Expert" expert)))
  3035. (defvar org-fast-tag-selection-include-todo nil
  3036. "Non-nil means fast tags selection interface will also offer TODO states.
  3037. This is an undocumented feature, you should not rely on it.")
  3038. (defcustom org-tags-column -77
  3039. "The column to which tags should be indented in a headline.
  3040. If this number is positive, it specifies the column. If it is negative,
  3041. it means that the tags should be flushright to that column. For example,
  3042. -80 works well for a normal 80 character screen.
  3043. When 0, place tags directly after headline text, with only one space in
  3044. between."
  3045. :group 'org-tags
  3046. :type 'integer)
  3047. (defcustom org-auto-align-tags t
  3048. "Non-nil keeps tags aligned when modifying headlines.
  3049. Some operations (i.e. demoting) change the length of a headline and
  3050. therefore shift the tags around. With this option turned on, after
  3051. each such operation the tags are again aligned to `org-tags-column'."
  3052. :group 'org-tags
  3053. :type 'boolean)
  3054. (defcustom org-use-tag-inheritance t
  3055. "Non-nil means tags in levels apply also for sublevels.
  3056. When nil, only the tags directly given in a specific line apply there.
  3057. This may also be a list of tags that should be inherited, or a regexp that
  3058. matches tags that should be inherited. Additional control is possible
  3059. with the variable `org-tags-exclude-from-inheritance' which gives an
  3060. explicit list of tags to be excluded from inheritance, even if the value of
  3061. `org-use-tag-inheritance' would select it for inheritance.
  3062. If this option is t, a match early-on in a tree can lead to a large
  3063. number of matches in the subtree when constructing the agenda or creating
  3064. a sparse tree. If you only want to see the first match in a tree during
  3065. a search, check out the variable `org-tags-match-list-sublevels'."
  3066. :group 'org-tags
  3067. :type '(choice
  3068. (const :tag "Not" nil)
  3069. (const :tag "Always" t)
  3070. (repeat :tag "Specific tags" (string :tag "Tag"))
  3071. (regexp :tag "Tags matched by regexp")))
  3072. (defcustom org-tags-exclude-from-inheritance nil
  3073. "List of tags that should never be inherited.
  3074. This is a way to exclude a few tags from inheritance. For way to do
  3075. the opposite, to actively allow inheritance for selected tags,
  3076. see the variable `org-use-tag-inheritance'."
  3077. :group 'org-tags
  3078. :type '(repeat (string :tag "Tag")))
  3079. (defun org-tag-inherit-p (tag)
  3080. "Check if TAG is one that should be inherited."
  3081. (cond
  3082. ((member tag org-tags-exclude-from-inheritance) nil)
  3083. ((eq org-use-tag-inheritance t) t)
  3084. ((not org-use-tag-inheritance) nil)
  3085. ((stringp org-use-tag-inheritance)
  3086. (string-match org-use-tag-inheritance tag))
  3087. ((listp org-use-tag-inheritance)
  3088. (member tag org-use-tag-inheritance))
  3089. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3090. (defcustom org-tags-match-list-sublevels t
  3091. "Non-nil means list also sublevels of headlines matching a search.
  3092. This variable applies to tags/property searches, and also to stuck
  3093. projects because this search is based on a tags match as well.
  3094. When set to the symbol `indented', sublevels are indented with
  3095. leading dots.
  3096. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3097. the sublevels of a headline matching a tag search often also match
  3098. the same search. Listing all of them can create very long lists.
  3099. Setting this variable to nil causes subtrees of a match to be skipped.
  3100. This variable is semi-obsolete and probably should always be true. It
  3101. is better to limit inheritance to certain tags using the variables
  3102. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3103. :group 'org-tags
  3104. :type '(choice
  3105. (const :tag "No, don't list them" nil)
  3106. (const :tag "Yes, do list them" t)
  3107. (const :tag "List them, indented with leading dots" indented)))
  3108. (defcustom org-tags-sort-function nil
  3109. "When set, tags are sorted using this function as a comparator."
  3110. :group 'org-tags
  3111. :type '(choice
  3112. (const :tag "No sorting" nil)
  3113. (const :tag "Alphabetical" string<)
  3114. (const :tag "Reverse alphabetical" string>)
  3115. (function :tag "Custom function" nil)))
  3116. (defvar org-tags-history nil
  3117. "History of minibuffer reads for tags.")
  3118. (defvar org-last-tags-completion-table nil
  3119. "The last used completion table for tags.")
  3120. (defvar org-after-tags-change-hook nil
  3121. "Hook that is run after the tags in a line have changed.")
  3122. (defgroup org-properties nil
  3123. "Options concerning properties in Org mode."
  3124. :tag "Org Properties"
  3125. :group 'org)
  3126. (defcustom org-property-format "%-10s %s"
  3127. "How property key/value pairs should be formatted by `indent-line'.
  3128. When `indent-line' hits a property definition, it will format the line
  3129. according to this format, mainly to make sure that the values are
  3130. lined-up with respect to each other."
  3131. :group 'org-properties
  3132. :type 'string)
  3133. (defcustom org-properties-postprocess-alist nil
  3134. "Alist of properties and functions to adjust inserted values.
  3135. Elements of this alist must be of the form
  3136. ([string] [function])
  3137. where [string] must be a property name and [function] must be a
  3138. lambda expression: this lambda expression must take one argument,
  3139. the value to adjust, and return the new value as a string.
  3140. For example, this element will allow the property \"Remaining\"
  3141. to be updated wrt the relation between the \"Effort\" property
  3142. and the clock summary:
  3143. ((\"Remaining\" (lambda(value)
  3144. (let ((clocksum (org-clock-sum-current-item))
  3145. (effort (org-duration-to-minutes
  3146. (org-entry-get (point) \"Effort\"))))
  3147. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3148. :group 'org-properties
  3149. :version "24.1"
  3150. :type '(alist :key-type (string :tag "Property")
  3151. :value-type (function :tag "Function")))
  3152. (defcustom org-use-property-inheritance nil
  3153. "Non-nil means properties apply also for sublevels.
  3154. This setting is chiefly used during property searches. Turning it on can
  3155. cause significant overhead when doing a search, which is why it is not
  3156. on by default.
  3157. When nil, only the properties directly given in the current entry count.
  3158. When t, every property is inherited. The value may also be a list of
  3159. properties that should have inheritance, or a regular expression matching
  3160. properties that should be inherited.
  3161. However, note that some special properties use inheritance under special
  3162. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3163. and the properties ending in \"_ALL\" when they are used as descriptor
  3164. for valid values of a property.
  3165. Note for programmers:
  3166. When querying an entry with `org-entry-get', you can control if inheritance
  3167. should be used. By default, `org-entry-get' looks only at the local
  3168. properties. You can request inheritance by setting the inherit argument
  3169. to t (to force inheritance) or to `selective' (to respect the setting
  3170. in this variable)."
  3171. :group 'org-properties
  3172. :type '(choice
  3173. (const :tag "Not" nil)
  3174. (const :tag "Always" t)
  3175. (repeat :tag "Specific properties" (string :tag "Property"))
  3176. (regexp :tag "Properties matched by regexp")))
  3177. (defun org-property-inherit-p (property)
  3178. "Return a non-nil value if PROPERTY should be inherited."
  3179. (cond
  3180. ((eq org-use-property-inheritance t) t)
  3181. ((not org-use-property-inheritance) nil)
  3182. ((stringp org-use-property-inheritance)
  3183. (string-match org-use-property-inheritance property))
  3184. ((listp org-use-property-inheritance)
  3185. (member-ignore-case property org-use-property-inheritance))
  3186. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3187. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3188. "The default column format, if no other format has been defined.
  3189. This variable can be set on the per-file basis by inserting a line
  3190. #+COLUMNS: %25ITEM ....."
  3191. :group 'org-properties
  3192. :type 'string)
  3193. (defcustom org-columns-ellipses ".."
  3194. "The ellipses to be used when a field in column view is truncated.
  3195. When this is the empty string, as many characters as possible are shown,
  3196. but then there will be no visual indication that the field has been truncated.
  3197. When this is a string of length N, the last N characters of a truncated
  3198. field are replaced by this string. If the column is narrower than the
  3199. ellipses string, only part of the ellipses string will be shown."
  3200. :group 'org-properties
  3201. :type 'string)
  3202. (defconst org-global-properties-fixed
  3203. '(("VISIBILITY_ALL" . "folded children content all")
  3204. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3205. "List of property/value pairs that can be inherited by any entry.
  3206. These are fixed values, for the preset properties. The user variable
  3207. that can be used to add to this list is `org-global-properties'.
  3208. The entries in this list are cons cells where the car is a property
  3209. name and cdr is a string with the value. If the value represents
  3210. multiple items like an \"_ALL\" property, separate the items by
  3211. spaces.")
  3212. (defcustom org-global-properties nil
  3213. "List of property/value pairs that can be inherited by any entry.
  3214. This list will be combined with the constant `org-global-properties-fixed'.
  3215. The entries in this list are cons cells where the car is a property
  3216. name and cdr is a string with the value.
  3217. You can set buffer-local values for the same purpose in the variable
  3218. `org-file-properties' this by adding lines like
  3219. #+PROPERTY: NAME VALUE"
  3220. :group 'org-properties
  3221. :type '(repeat
  3222. (cons (string :tag "Property")
  3223. (string :tag "Value"))))
  3224. (defvar-local org-file-properties nil
  3225. "List of property/value pairs that can be inherited by any entry.
  3226. Valid for the current buffer.
  3227. This variable is populated from #+PROPERTY lines.")
  3228. (defgroup org-agenda nil
  3229. "Options concerning agenda views in Org mode."
  3230. :tag "Org Agenda"
  3231. :group 'org)
  3232. (defvar-local org-category nil
  3233. "Variable used by org files to set a category for agenda display.
  3234. Such files should use a file variable to set it, for example
  3235. # -*- mode: org; org-category: \"ELisp\"
  3236. or contain a special line
  3237. #+CATEGORY: ELisp
  3238. If the file does not specify a category, then file's base name
  3239. is used instead.")
  3240. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3241. (defcustom org-agenda-files nil
  3242. "The files to be used for agenda display.
  3243. If an entry is a directory, all files in that directory that are matched
  3244. by `org-agenda-file-regexp' will be part of the file list.
  3245. If the value of the variable is not a list but a single file name, then
  3246. the list of agenda files is actually stored and maintained in that file,
  3247. one agenda file per line. In this file paths can be given relative to
  3248. `org-directory'. Tilde expansion and environment variable substitution
  3249. are also made.
  3250. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3251. and removed with `\\[org-remove-file]'."
  3252. :group 'org-agenda
  3253. :type '(choice
  3254. (repeat :tag "List of files and directories" file)
  3255. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3256. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3257. "Regular expression to match files for `org-agenda-files'.
  3258. If any element in the list in that variable contains a directory instead
  3259. of a normal file, all files in that directory that are matched by this
  3260. regular expression will be included."
  3261. :group 'org-agenda
  3262. :type 'regexp)
  3263. (defcustom org-agenda-text-search-extra-files nil
  3264. "List of extra files to be searched by text search commands.
  3265. These files will be searched in addition to the agenda files by the
  3266. commands `org-search-view' (`\\[org-agenda] s') \
  3267. and `org-occur-in-agenda-files'.
  3268. Note that these files will only be searched for text search commands,
  3269. not for the other agenda views like todo lists, tag searches or the weekly
  3270. agenda. This variable is intended to list notes and possibly archive files
  3271. that should also be searched by these two commands.
  3272. In fact, if the first element in the list is the symbol `agenda-archives',
  3273. then all archive files of all agenda files will be added to the search
  3274. scope."
  3275. :group 'org-agenda
  3276. :type '(set :greedy t
  3277. (const :tag "Agenda Archives" agenda-archives)
  3278. (repeat :inline t (file))))
  3279. (defvaralias 'org-agenda-multi-occur-extra-files
  3280. 'org-agenda-text-search-extra-files)
  3281. (defcustom org-agenda-skip-unavailable-files nil
  3282. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3283. A nil value means to remove them, after a query, from the list."
  3284. :group 'org-agenda
  3285. :type 'boolean)
  3286. (defcustom org-calendar-to-agenda-key [?c]
  3287. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3288. The command `org-calendar-goto-agenda' will be bound to this key. The
  3289. default is the character `c' because then `c' can be used to switch back and
  3290. forth between agenda and calendar."
  3291. :group 'org-agenda
  3292. :type 'sexp)
  3293. (defcustom org-calendar-insert-diary-entry-key [?i]
  3294. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3295. This option is irrelevant until `org-agenda-diary-file' has been configured
  3296. to point to an Org file. When that is the case, the command
  3297. `org-agenda-diary-entry' will be bound to the key given here, by default
  3298. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3299. if you want to continue doing this, you need to change this to a different
  3300. key."
  3301. :group 'org-agenda
  3302. :type 'sexp)
  3303. (defcustom org-agenda-diary-file 'diary-file
  3304. "File to which to add new entries with the `i' key in agenda and calendar.
  3305. When this is the symbol `diary-file', the functionality in the Emacs
  3306. calendar will be used to add entries to the `diary-file'. But when this
  3307. points to a file, `org-agenda-diary-entry' will be used instead."
  3308. :group 'org-agenda
  3309. :type '(choice
  3310. (const :tag "The standard Emacs diary file" diary-file)
  3311. (file :tag "Special Org file diary entries")))
  3312. (eval-after-load "calendar"
  3313. '(progn
  3314. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3315. 'org-calendar-goto-agenda)
  3316. (add-hook 'calendar-mode-hook
  3317. (lambda ()
  3318. (unless (eq org-agenda-diary-file 'diary-file)
  3319. (define-key calendar-mode-map
  3320. org-calendar-insert-diary-entry-key
  3321. 'org-agenda-diary-entry))))))
  3322. (defgroup org-latex nil
  3323. "Options for embedding LaTeX code into Org mode."
  3324. :tag "Org LaTeX"
  3325. :group 'org)
  3326. (defcustom org-format-latex-options
  3327. '(:foreground default :background default :scale 1.0
  3328. :html-foreground "Black" :html-background "Transparent"
  3329. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3330. "Options for creating images from LaTeX fragments.
  3331. This is a property list with the following properties:
  3332. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3333. `default' means use the foreground of the default face.
  3334. `auto' means use the foreground from the text face.
  3335. :background the background color, or \"Transparent\".
  3336. `default' means use the background of the default face.
  3337. `auto' means use the background from the text face.
  3338. :scale a scaling factor for the size of the images, to get more pixels
  3339. :html-foreground, :html-background, :html-scale
  3340. the same numbers for HTML export.
  3341. :matchers a list indicating which matchers should be used to
  3342. find LaTeX fragments. Valid members of this list are:
  3343. \"begin\" find environments
  3344. \"$1\" find single characters surrounded by $.$
  3345. \"$\" find math expressions surrounded by $...$
  3346. \"$$\" find math expressions surrounded by $$....$$
  3347. \"\\(\" find math expressions surrounded by \\(...\\)
  3348. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3349. :group 'org-latex
  3350. :type 'plist)
  3351. (defcustom org-format-latex-signal-error t
  3352. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3353. When nil, just push out a message."
  3354. :group 'org-latex
  3355. :version "24.1"
  3356. :type 'boolean)
  3357. (defcustom org-latex-to-mathml-jar-file nil
  3358. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3359. Use this to specify additional executable file say a jar file.
  3360. When using MathToWeb as the converter, specify the full-path to
  3361. your mathtoweb.jar file."
  3362. :group 'org-latex
  3363. :version "24.1"
  3364. :type '(choice
  3365. (const :tag "None" nil)
  3366. (file :tag "JAR file" :must-match t)))
  3367. (defcustom org-latex-to-mathml-convert-command nil
  3368. "Command to convert LaTeX fragments to MathML.
  3369. Replace format-specifiers in the command as noted below and use
  3370. `shell-command' to convert LaTeX to MathML.
  3371. %j: Executable file in fully expanded form as specified by
  3372. `org-latex-to-mathml-jar-file'.
  3373. %I: Input LaTeX file in fully expanded form.
  3374. %i: The latex fragment to be converted.
  3375. %o: Output MathML file.
  3376. This command is used by `org-create-math-formula'.
  3377. When using MathToWeb as the converter, set this option to
  3378. \"java -jar %j -unicode -force -df %o %I\".
  3379. When using LaTeXML set this option to
  3380. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3381. :group 'org-latex
  3382. :version "24.1"
  3383. :type '(choice
  3384. (const :tag "None" nil)
  3385. (string :tag "\nShell command")))
  3386. (defcustom org-preview-latex-default-process 'dvipng
  3387. "The default process to convert LaTeX fragments to image files.
  3388. All available processes and theirs documents can be found in
  3389. `org-preview-latex-process-alist', which see."
  3390. :group 'org-latex
  3391. :version "26.1"
  3392. :package-version '(Org . "9.0")
  3393. :type 'symbol)
  3394. (defcustom org-preview-latex-process-alist
  3395. '((dvipng
  3396. :programs ("latex" "dvipng")
  3397. :description "dvi > png"
  3398. :message "you need to install the programs: latex and dvipng."
  3399. :image-input-type "dvi"
  3400. :image-output-type "png"
  3401. :image-size-adjust (1.0 . 1.0)
  3402. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3403. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3404. (dvisvgm
  3405. :programs ("latex" "dvisvgm")
  3406. :description "dvi > svg"
  3407. :message "you need to install the programs: latex and dvisvgm."
  3408. :use-xcolor t
  3409. :image-input-type "dvi"
  3410. :image-output-type "svg"
  3411. :image-size-adjust (1.7 . 1.5)
  3412. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3413. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3414. (imagemagick
  3415. :programs ("latex" "convert")
  3416. :description "pdf > png"
  3417. :message "you need to install the programs: latex and imagemagick."
  3418. :use-xcolor t
  3419. :image-input-type "pdf"
  3420. :image-output-type "png"
  3421. :image-size-adjust (1.0 . 1.0)
  3422. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3423. :image-converter
  3424. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3425. "Definitions of external processes for LaTeX previewing.
  3426. Org mode can use some external commands to generate TeX snippet's images for
  3427. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3428. `org-create-formula-image' how to call them.
  3429. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3430. PROPERTIES accepts the following attributes:
  3431. :programs list of strings, required programs.
  3432. :description string, describe the process.
  3433. :message string, message it when required programs cannot be found.
  3434. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3435. :image-output-type string, output file type of image converter (e.g., \"png\").
  3436. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3437. deal with background and foreground color of image.
  3438. Otherwise, dvipng style background and foregroud color
  3439. format are generated. You may then refer to them in
  3440. command options with \"%F\" and \"%B\".
  3441. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3442. image size showed in buffer and the cdr element is for
  3443. HTML file. This option is only useful for process
  3444. developers, users should use variable
  3445. `org-format-latex-options' instead.
  3446. :post-clean list of strings, files matched are to be cleaned up once
  3447. the image is generated. When nil, the files with \".dvi\",
  3448. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3449. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3450. be cleaned up.
  3451. :latex-header list of strings, the LaTeX header of the snippet file.
  3452. When nil, the fallback value is used instead, which is
  3453. controlled by `org-format-latex-header',
  3454. `org-latex-default-packages-alist' and
  3455. `org-latex-packages-alist', which see.
  3456. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3457. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3458. replaced with values defined below.
  3459. :image-converter list of image converter commands strings. Each of them is
  3460. given to the shell and supports any of the following
  3461. place-holders defined below.
  3462. Place-holders used by `:image-converter' and `:latex-compiler':
  3463. %f input file name
  3464. %b base name of input file
  3465. %o base directory of input file
  3466. %O absolute output file name
  3467. Place-holders only used by `:image-converter':
  3468. %F foreground of image
  3469. %B background of image
  3470. %D dpi, which is used to adjust image size by some processing commands.
  3471. %S the image size scale ratio, which is used to adjust image size by some
  3472. processing commands."
  3473. :group 'org-latex
  3474. :version "26.1"
  3475. :package-version '(Org . "9.0")
  3476. :type '(alist :tag "LaTeX to image backends"
  3477. :value-type (plist)))
  3478. (defcustom org-preview-latex-image-directory "ltximg/"
  3479. "Path to store latex preview images.
  3480. A relative path here creates many directories relative to the
  3481. processed org files paths. An absolute path puts all preview
  3482. images at the same place."
  3483. :group 'org-latex
  3484. :version "26.1"
  3485. :package-version '(Org . "9.0")
  3486. :type 'string)
  3487. (defun org-format-latex-mathml-available-p ()
  3488. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3489. (save-match-data
  3490. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3491. org-latex-to-mathml-convert-command)
  3492. (let ((executable (car (split-string
  3493. org-latex-to-mathml-convert-command))))
  3494. (when (executable-find executable)
  3495. (if (string-match
  3496. "%j" org-latex-to-mathml-convert-command)
  3497. (file-readable-p org-latex-to-mathml-jar-file)
  3498. t))))))
  3499. (defcustom org-format-latex-header "\\documentclass{article}
  3500. \\usepackage[usenames]{color}
  3501. \[PACKAGES]
  3502. \[DEFAULT-PACKAGES]
  3503. \\pagestyle{empty} % do not remove
  3504. % The settings below are copied from fullpage.sty
  3505. \\setlength{\\textwidth}{\\paperwidth}
  3506. \\addtolength{\\textwidth}{-3cm}
  3507. \\setlength{\\oddsidemargin}{1.5cm}
  3508. \\addtolength{\\oddsidemargin}{-2.54cm}
  3509. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3510. \\setlength{\\textheight}{\\paperheight}
  3511. \\addtolength{\\textheight}{-\\headheight}
  3512. \\addtolength{\\textheight}{-\\headsep}
  3513. \\addtolength{\\textheight}{-\\footskip}
  3514. \\addtolength{\\textheight}{-3cm}
  3515. \\setlength{\\topmargin}{1.5cm}
  3516. \\addtolength{\\topmargin}{-2.54cm}"
  3517. "The document header used for processing LaTeX fragments.
  3518. It is imperative that this header make sure that no page number
  3519. appears on the page. The package defined in the variables
  3520. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3521. will either replace the placeholder \"[PACKAGES]\" in this
  3522. header, or they will be appended."
  3523. :group 'org-latex
  3524. :type 'string)
  3525. (defun org-set-packages-alist (var val)
  3526. "Set the packages alist and make sure it has 3 elements per entry."
  3527. (set var (mapcar (lambda (x)
  3528. (if (and (consp x) (= (length x) 2))
  3529. (list (car x) (nth 1 x) t)
  3530. x))
  3531. val)))
  3532. (defun org-get-packages-alist (var)
  3533. "Get the packages alist and make sure it has 3 elements per entry."
  3534. (mapcar (lambda (x)
  3535. (if (and (consp x) (= (length x) 2))
  3536. (list (car x) (nth 1 x) t)
  3537. x))
  3538. (default-value var)))
  3539. (defcustom org-latex-default-packages-alist
  3540. '(("AUTO" "inputenc" t ("pdflatex"))
  3541. ("T1" "fontenc" t ("pdflatex"))
  3542. ("" "graphicx" t)
  3543. ("" "grffile" t)
  3544. ("" "longtable" nil)
  3545. ("" "wrapfig" nil)
  3546. ("" "rotating" nil)
  3547. ("normalem" "ulem" t)
  3548. ("" "amsmath" t)
  3549. ("" "textcomp" t)
  3550. ("" "amssymb" t)
  3551. ("" "capt-of" nil)
  3552. ("" "hyperref" nil))
  3553. "Alist of default packages to be inserted in the header.
  3554. Change this only if one of the packages here causes an
  3555. incompatibility with another package you are using.
  3556. The packages in this list are needed by one part or another of
  3557. Org mode to function properly:
  3558. - inputenc, fontenc: for basic font and character selection
  3559. - graphicx: for including images
  3560. - grffile: allow periods and spaces in graphics file names
  3561. - longtable: For multipage tables
  3562. - wrapfig: for figure placement
  3563. - rotating: for sideways figures and tables
  3564. - ulem: for underline and strike-through
  3565. - amsmath: for subscript and superscript and math environments
  3566. - textcomp, amssymb: for various symbols used
  3567. for interpreting the entities in `org-entities'. You can skip
  3568. some of these packages if you don't use any of their symbols.
  3569. - capt-of: for captions outside of floats
  3570. - hyperref: for cross references
  3571. Therefore you should not modify this variable unless you know
  3572. what you are doing. The one reason to change it anyway is that
  3573. you might be loading some other package that conflicts with one
  3574. of the default packages. Each element is either a cell or
  3575. a string.
  3576. A cell is of the format
  3577. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3578. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3579. when compiling LaTeX snippets into images for inclusion into
  3580. non-LaTeX output. COMPILERS is a list of compilers that should
  3581. include the package, see `org-latex-compiler'. If the document
  3582. compiler is not in the list, and the list is non-nil, the package
  3583. will not be inserted in the final document.
  3584. A string will be inserted as-is in the header of the document."
  3585. :group 'org-latex
  3586. :group 'org-export-latex
  3587. :set 'org-set-packages-alist
  3588. :get 'org-get-packages-alist
  3589. :version "26.1"
  3590. :package-version '(Org . "8.3")
  3591. :type '(repeat
  3592. (choice
  3593. (list :tag "options/package pair"
  3594. (string :tag "options")
  3595. (string :tag "package")
  3596. (boolean :tag "Snippet"))
  3597. (string :tag "A line of LaTeX"))))
  3598. (defcustom org-latex-packages-alist nil
  3599. "Alist of packages to be inserted in every LaTeX header.
  3600. These will be inserted after `org-latex-default-packages-alist'.
  3601. Each element is either a cell or a string.
  3602. A cell is of the format:
  3603. (\"options\" \"package\" SNIPPET-FLAG)
  3604. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3605. needed when turning LaTeX snippets into images for inclusion into
  3606. non-LaTeX output.
  3607. A string will be inserted as-is in the header of the document.
  3608. Make sure that you only list packages here which:
  3609. - you want in every file;
  3610. - do not conflict with the setup in `org-format-latex-header';
  3611. - do not conflict with the default packages in
  3612. `org-latex-default-packages-alist'."
  3613. :group 'org-latex
  3614. :group 'org-export-latex
  3615. :set 'org-set-packages-alist
  3616. :get 'org-get-packages-alist
  3617. :type '(repeat
  3618. (choice
  3619. (list :tag "options/package pair"
  3620. (string :tag "options")
  3621. (string :tag "package")
  3622. (boolean :tag "Snippet"))
  3623. (string :tag "A line of LaTeX"))))
  3624. (defgroup org-appearance nil
  3625. "Settings for Org mode appearance."
  3626. :tag "Org Appearance"
  3627. :group 'org)
  3628. (defcustom org-level-color-stars-only nil
  3629. "Non-nil means fontify only the stars in each headline.
  3630. When nil, the entire headline is fontified.
  3631. Changing it requires restart of `font-lock-mode' to become effective
  3632. also in regions already fontified."
  3633. :group 'org-appearance
  3634. :type 'boolean)
  3635. (defcustom org-hide-leading-stars nil
  3636. "Non-nil means hide the first N-1 stars in a headline.
  3637. This works by using the face `org-hide' for these stars. This
  3638. face is white for a light background, and black for a dark
  3639. background. You may have to customize the face `org-hide' to
  3640. make this work.
  3641. Changing it requires restart of `font-lock-mode' to become effective
  3642. also in regions already fontified.
  3643. You may also set this on a per-file basis by adding one of the following
  3644. lines to the buffer:
  3645. #+STARTUP: hidestars
  3646. #+STARTUP: showstars"
  3647. :group 'org-appearance
  3648. :type 'boolean)
  3649. (defcustom org-hidden-keywords nil
  3650. "List of symbols corresponding to keywords to be hidden the org buffer.
  3651. For example, a value \\='(title) for this list will make the document's title
  3652. appear in the buffer without the initial #+TITLE: keyword."
  3653. :group 'org-appearance
  3654. :version "24.1"
  3655. :type '(set (const :tag "#+AUTHOR" author)
  3656. (const :tag "#+DATE" date)
  3657. (const :tag "#+EMAIL" email)
  3658. (const :tag "#+TITLE" title)))
  3659. (defcustom org-custom-properties nil
  3660. "List of properties (as strings) with a special meaning.
  3661. The default use of these custom properties is to let the user
  3662. hide them with `org-toggle-custom-properties-visibility'."
  3663. :group 'org-properties
  3664. :group 'org-appearance
  3665. :version "24.3"
  3666. :type '(repeat (string :tag "Property Name")))
  3667. (defcustom org-fontify-done-headline nil
  3668. "Non-nil means change the face of a headline if it is marked DONE.
  3669. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3670. When this is non-nil, the headline after the keyword is set to the
  3671. `org-headline-done' as an additional indication."
  3672. :group 'org-appearance
  3673. :type 'boolean)
  3674. (defcustom org-fontify-emphasized-text t
  3675. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3676. Changing this variable requires a restart of Emacs to take effect."
  3677. :group 'org-appearance
  3678. :type 'boolean)
  3679. (defcustom org-fontify-whole-heading-line nil
  3680. "Non-nil means fontify the whole line for headings.
  3681. This is useful when setting a background color for the
  3682. org-level-* faces."
  3683. :group 'org-appearance
  3684. :type 'boolean)
  3685. (defcustom org-highlight-latex-and-related nil
  3686. "Non-nil means highlight LaTeX related syntax in the buffer.
  3687. When non nil, the value should be a list containing any of the
  3688. following symbols:
  3689. `latex' Highlight LaTeX snippets and environments.
  3690. `script' Highlight subscript and superscript.
  3691. `entities' Highlight entities."
  3692. :group 'org-appearance
  3693. :version "24.4"
  3694. :package-version '(Org . "8.0")
  3695. :type '(choice
  3696. (const :tag "No highlighting" nil)
  3697. (set :greedy t :tag "Highlight"
  3698. (const :tag "LaTeX snippets and environments" latex)
  3699. (const :tag "Subscript and superscript" script)
  3700. (const :tag "Entities" entities))))
  3701. (defcustom org-hide-emphasis-markers nil
  3702. "Non-nil mean font-lock should hide the emphasis marker characters."
  3703. :group 'org-appearance
  3704. :type 'boolean)
  3705. (defcustom org-hide-macro-markers nil
  3706. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3707. :group 'org-appearance
  3708. :type 'boolean)
  3709. (defcustom org-pretty-entities nil
  3710. "Non-nil means show entities as UTF8 characters.
  3711. When nil, the \\name form remains in the buffer."
  3712. :group 'org-appearance
  3713. :version "24.1"
  3714. :type 'boolean)
  3715. (defcustom org-pretty-entities-include-sub-superscripts t
  3716. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3717. :group 'org-appearance
  3718. :version "24.1"
  3719. :type 'boolean)
  3720. (defvar org-emph-re nil
  3721. "Regular expression for matching emphasis.
  3722. After a match, the match groups contain these elements:
  3723. 0 The match of the full regular expression, including the characters
  3724. before and after the proper match
  3725. 1 The character before the proper match, or empty at beginning of line
  3726. 2 The proper match, including the leading and trailing markers
  3727. 3 The leading marker like * or /, indicating the type of highlighting
  3728. 4 The text between the emphasis markers, not including the markers
  3729. 5 The character after the match, empty at the end of a line")
  3730. (defvar org-verbatim-re nil
  3731. "Regular expression for matching verbatim text.")
  3732. (defvar org-emphasis-regexp-components) ; defined just below
  3733. (defvar org-emphasis-alist) ; defined just below
  3734. (defun org-set-emph-re (var val)
  3735. "Set variable and compute the emphasis regular expression."
  3736. (set var val)
  3737. (when (and (boundp 'org-emphasis-alist)
  3738. (boundp 'org-emphasis-regexp-components)
  3739. org-emphasis-alist org-emphasis-regexp-components)
  3740. (pcase-let*
  3741. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3742. (body (if (<= nl 0) body
  3743. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3744. (template
  3745. (format (concat "\\([%s]\\|^\\)" ;before markers
  3746. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3747. "\\([%s]\\|$\\)") ;after markers
  3748. pre border border body border post)))
  3749. (setq org-emph-re (format template "*/_+"))
  3750. (setq org-verbatim-re (format template "=~")))))
  3751. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3752. ;; set this option proved cumbersome. See this message/thread:
  3753. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3754. (defvar org-emphasis-regexp-components
  3755. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3756. "Components used to build the regular expression for emphasis.
  3757. This is a list with five entries. Terminology: In an emphasis string
  3758. like \" *strong word* \", we call the initial space PREMATCH, the final
  3759. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3760. and \"trong wor\" is the body. The different components in this variable
  3761. specify what is allowed/forbidden in each part:
  3762. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3763. post Chars allowed as postmatch. End of line will be allowed too.
  3764. border The chars *forbidden* as border characters.
  3765. body-regexp A regexp like \".\" to match a body character. Don't use
  3766. non-shy groups here, and don't allow newline here.
  3767. newline The maximum number of newlines allowed in an emphasis exp.
  3768. You need to reload Org or to restart Emacs after customizing this.")
  3769. (defcustom org-emphasis-alist
  3770. '(("*" bold)
  3771. ("/" italic)
  3772. ("_" underline)
  3773. ("=" org-verbatim verbatim)
  3774. ("~" org-code verbatim)
  3775. ("+" (:strike-through t)))
  3776. "Alist of characters and faces to emphasize text.
  3777. Text starting and ending with a special character will be emphasized,
  3778. for example *bold*, _underlined_ and /italic/. This variable sets the
  3779. marker characters and the face to be used by font-lock for highlighting
  3780. in Org buffers.
  3781. You need to reload Org or to restart Emacs after customizing this."
  3782. :group 'org-appearance
  3783. :set 'org-set-emph-re
  3784. :version "24.4"
  3785. :package-version '(Org . "8.0")
  3786. :type '(repeat
  3787. (list
  3788. (string :tag "Marker character")
  3789. (choice
  3790. (face :tag "Font-lock-face")
  3791. (plist :tag "Face property list"))
  3792. (option (const verbatim)))))
  3793. (defvar org-protecting-blocks '("src" "example" "export")
  3794. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3795. This is needed for font-lock setup.")
  3796. ;;; Functions and variables from their packages
  3797. ;; Declared here to avoid compiler warnings
  3798. (defvar mark-active)
  3799. ;; Various packages
  3800. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3801. (declare-function calendar-forward-day "cal-move" (arg))
  3802. (declare-function calendar-goto-date "cal-move" (date))
  3803. (declare-function calendar-goto-today "cal-move" ())
  3804. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3805. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3806. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3807. (declare-function cdlatex-tab "ext:cdlatex" ())
  3808. (declare-function dired-get-filename
  3809. "dired"
  3810. (&optional localp no-error-if-not-filep))
  3811. (declare-function iswitchb-read-buffer
  3812. "iswitchb"
  3813. (prompt &optional
  3814. default require-match _predicate start matches-set))
  3815. (declare-function org-agenda-change-all-lines
  3816. "org-agenda"
  3817. (newhead hdmarker &optional fixface just-this))
  3818. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3819. "org-agenda"
  3820. (&optional end))
  3821. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3822. (declare-function org-agenda-format-item
  3823. "org-agenda"
  3824. (extra txt &optional level category tags dotime
  3825. remove-re habitp))
  3826. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3827. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3828. (declare-function org-agenda-save-markers-for-cut-and-paste
  3829. "org-agenda"
  3830. (beg end))
  3831. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3832. (declare-function org-agenda-skip "org-agenda" ())
  3833. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3834. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3835. (declare-function org-indent-mode "org-indent" (&optional arg))
  3836. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3837. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3838. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3839. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3840. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3841. (declare-function parse-time-string "parse-time" (string))
  3842. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3843. (defvar align-mode-rules-list)
  3844. (defvar calc-embedded-close-formula)
  3845. (defvar calc-embedded-open-formula)
  3846. (defvar calc-embedded-open-mode)
  3847. (defvar font-lock-unfontify-region-function)
  3848. (defvar iswitchb-temp-buflist)
  3849. (defvar org-agenda-tags-todo-honor-ignore-options)
  3850. (defvar remember-data-file)
  3851. (defvar texmathp-why)
  3852. ;;;###autoload
  3853. (defun turn-on-orgtbl ()
  3854. "Unconditionally turn on `orgtbl-mode'."
  3855. (require 'org-table)
  3856. (orgtbl-mode 1))
  3857. (defun org-at-table-p (&optional table-type)
  3858. "Non-nil if the cursor is inside an Org table.
  3859. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3860. If `org-enable-table-editor' is nil, return nil unconditionally."
  3861. (and
  3862. org-enable-table-editor
  3863. (save-excursion
  3864. (beginning-of-line)
  3865. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3866. (or (not (derived-mode-p 'org-mode))
  3867. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3868. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3869. (defun org-at-table.el-p ()
  3870. "Non-nil when point is at a table.el table."
  3871. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3872. (let ((element (org-element-at-point)))
  3873. (and (eq (org-element-type element) 'table)
  3874. (eq (org-element-property :type element) 'table.el)))))
  3875. (defun org-at-table-hline-p ()
  3876. "Non-nil when point is inside a hline in a table.
  3877. Assume point is already in a table. If `org-enable-table-editor'
  3878. is nil, return nil unconditionally."
  3879. (and org-enable-table-editor
  3880. (save-excursion
  3881. (beginning-of-line)
  3882. (looking-at org-table-hline-regexp))))
  3883. (defun org-table-map-tables (function &optional quietly)
  3884. "Apply FUNCTION to the start of all tables in the buffer."
  3885. (org-with-wide-buffer
  3886. (goto-char (point-min))
  3887. (while (re-search-forward org-table-any-line-regexp nil t)
  3888. (unless quietly
  3889. (message "Mapping tables: %d%%"
  3890. (floor (* 100.0 (point)) (buffer-size))))
  3891. (beginning-of-line 1)
  3892. (when (and (looking-at org-table-line-regexp)
  3893. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3894. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3895. (save-excursion (funcall function))
  3896. (or (looking-at org-table-line-regexp)
  3897. (forward-char 1)))
  3898. (re-search-forward org-table-any-border-regexp nil 1)))
  3899. (unless quietly (message "Mapping tables: done")))
  3900. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3901. (declare-function org-clock-update-mode-line "org-clock" ())
  3902. (declare-function org-resolve-clocks "org-clock"
  3903. (&optional also-non-dangling-p prompt last-valid))
  3904. (defun org-at-TBLFM-p (&optional pos)
  3905. "Non-nil when point (or POS) is in #+TBLFM line."
  3906. (save-excursion
  3907. (goto-char (or pos (point)))
  3908. (beginning-of-line)
  3909. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3910. (eq (org-element-type (org-element-at-point)) 'table))))
  3911. (defvar org-clock-start-time)
  3912. (defvar org-clock-marker (make-marker)
  3913. "Marker recording the last clock-in.")
  3914. (defvar org-clock-hd-marker (make-marker)
  3915. "Marker recording the last clock-in, but the headline position.")
  3916. (defvar org-clock-heading ""
  3917. "The heading of the current clock entry.")
  3918. (defun org-clock-is-active ()
  3919. "Return the buffer where the clock is currently running.
  3920. Return nil if no clock is running."
  3921. (marker-buffer org-clock-marker))
  3922. (defun org-check-running-clock ()
  3923. "Check if the current buffer contains the running clock.
  3924. If yes, offer to stop it and to save the buffer with the changes."
  3925. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3926. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3927. (buffer-name))))
  3928. (org-clock-out)
  3929. (when (y-or-n-p "Save changed buffer?")
  3930. (save-buffer))))
  3931. (defun org-clocktable-try-shift (dir n)
  3932. "Check if this line starts a clock table, if yes, shift the time block."
  3933. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3934. (org-clocktable-shift dir n)))
  3935. ;;;###autoload
  3936. (defun org-clock-persistence-insinuate ()
  3937. "Set up hooks for clock persistence."
  3938. (require 'org-clock)
  3939. (add-hook 'org-mode-hook 'org-clock-load)
  3940. (add-hook 'kill-emacs-hook 'org-clock-save))
  3941. (defgroup org-archive nil
  3942. "Options concerning archiving in Org mode."
  3943. :tag "Org Archive"
  3944. :group 'org-structure)
  3945. (defcustom org-archive-location "%s_archive::"
  3946. "The location where subtrees should be archived.
  3947. The value of this variable is a string, consisting of two parts,
  3948. separated by a double-colon. The first part is a filename and
  3949. the second part is a headline.
  3950. When the filename is omitted, archiving happens in the same file.
  3951. %s in the filename will be replaced by the current file
  3952. name (without the directory part). Archiving to a different file
  3953. is useful to keep archived entries from contributing to the
  3954. Org Agenda.
  3955. The archived entries will be filed as subtrees of the specified
  3956. headline. When the headline is omitted, the subtrees are simply
  3957. filed away at the end of the file, as top-level entries. Also in
  3958. the heading you can use %s to represent the file name, this can be
  3959. useful when using the same archive for a number of different files.
  3960. Here are a few examples:
  3961. \"%s_archive::\"
  3962. If the current file is Projects.org, archive in file
  3963. Projects.org_archive, as top-level trees. This is the default.
  3964. \"::* Archived Tasks\"
  3965. Archive in the current file, under the top-level headline
  3966. \"* Archived Tasks\".
  3967. \"~/org/archive.org::\"
  3968. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3969. \"~/org/archive.org::* From %s\"
  3970. Archive in file ~/org/archive.org (absolute path), under headlines
  3971. \"From FILENAME\" where file name is the current file name.
  3972. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3973. The \"datetree/\" string is special, signifying to archive
  3974. items to the datetree. Items are placed in either the CLOSED
  3975. date of the item, or the current date if there is no CLOSED date.
  3976. The heading will be a subentry to the current date. There doesn't
  3977. need to be a heading, but there always needs to be a slash after
  3978. datetree. For example, to store archived items directly in the
  3979. datetree, use \"~/org/datetree.org::datetree/\".
  3980. \"basement::** Finished Tasks\"
  3981. Archive in file ./basement (relative path), as level 3 trees
  3982. below the level 2 heading \"** Finished Tasks\".
  3983. You may set this option on a per-file basis by adding to the buffer a
  3984. line like
  3985. #+ARCHIVE: basement::** Finished Tasks
  3986. You may also define it locally for a subtree by setting an ARCHIVE property
  3987. in the entry. If such a property is found in an entry, or anywhere up
  3988. the hierarchy, it will be used."
  3989. :group 'org-archive
  3990. :type 'string)
  3991. (defcustom org-agenda-skip-archived-trees t
  3992. "Non-nil means the agenda will skip any items located in archived trees.
  3993. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3994. variable is no longer recommended, you should leave it at the value t.
  3995. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3996. :group 'org-archive
  3997. :group 'org-agenda-skip
  3998. :type 'boolean)
  3999. (defcustom org-columns-skip-archived-trees t
  4000. "Non-nil means ignore archived trees when creating column view."
  4001. :group 'org-archive
  4002. :group 'org-properties
  4003. :type 'boolean)
  4004. (defcustom org-cycle-open-archived-trees nil
  4005. "Non-nil means `org-cycle' will open archived trees.
  4006. An archived tree is a tree marked with the tag ARCHIVE.
  4007. When nil, archived trees will stay folded. You can still open them with
  4008. normal outline commands like `show-all', but not with the cycling commands."
  4009. :group 'org-archive
  4010. :group 'org-cycle
  4011. :type 'boolean)
  4012. (defcustom org-sparse-tree-open-archived-trees nil
  4013. "Non-nil means sparse tree construction shows matches in archived trees.
  4014. When nil, matches in these trees are highlighted, but the trees are kept in
  4015. collapsed state."
  4016. :group 'org-archive
  4017. :group 'org-sparse-trees
  4018. :type 'boolean)
  4019. (defcustom org-sparse-tree-default-date-type nil
  4020. "The default date type when building a sparse tree.
  4021. When this is nil, a date is a scheduled or a deadline timestamp.
  4022. Otherwise, these types are allowed:
  4023. all: all timestamps
  4024. active: only active timestamps (<...>)
  4025. inactive: only inactive timestamps ([...])
  4026. scheduled: only scheduled timestamps
  4027. deadline: only deadline timestamps"
  4028. :type '(choice (const :tag "Scheduled or deadline" nil)
  4029. (const :tag "All timestamps" all)
  4030. (const :tag "Only active timestamps" active)
  4031. (const :tag "Only inactive timestamps" inactive)
  4032. (const :tag "Only scheduled timestamps" scheduled)
  4033. (const :tag "Only deadline timestamps" deadline)
  4034. (const :tag "Only closed timestamps" closed))
  4035. :version "26.1"
  4036. :package-version '(Org . "8.3")
  4037. :group 'org-sparse-trees)
  4038. (defun org-cycle-hide-archived-subtrees (state)
  4039. "Re-hide all archived subtrees after a visibility state change."
  4040. (when (and (not org-cycle-open-archived-trees)
  4041. (not (memq state '(overview folded))))
  4042. (save-excursion
  4043. (let* ((globalp (memq state '(contents all)))
  4044. (beg (if globalp (point-min) (point)))
  4045. (end (if globalp (point-max) (org-end-of-subtree t))))
  4046. (org-hide-archived-subtrees beg end)
  4047. (goto-char beg)
  4048. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4049. (message "%s" (substitute-command-keys
  4050. "Subtree is archived and stays closed. Use \
  4051. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4052. (defun org-force-cycle-archived ()
  4053. "Cycle subtree even if it is archived."
  4054. (interactive)
  4055. (setq this-command 'org-cycle)
  4056. (let ((org-cycle-open-archived-trees t))
  4057. (call-interactively 'org-cycle)))
  4058. (defun org-hide-archived-subtrees (beg end)
  4059. "Re-hide all archived subtrees after a visibility state change."
  4060. (org-with-wide-buffer
  4061. (let ((case-fold-search nil)
  4062. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4063. (goto-char beg)
  4064. ;; Include headline point is currently on.
  4065. (beginning-of-line)
  4066. (while (and (< (point) end) (re-search-forward re end t))
  4067. (when (member org-archive-tag (org-get-tags))
  4068. (org-flag-subtree t)
  4069. (org-end-of-subtree t))))))
  4070. (declare-function outline-end-of-heading "outline" ())
  4071. (declare-function outline-flag-region "outline" (from to flag))
  4072. (defun org-flag-subtree (flag)
  4073. (save-excursion
  4074. (org-back-to-heading t)
  4075. (outline-end-of-heading)
  4076. (outline-flag-region (point)
  4077. (progn (org-end-of-subtree t) (point))
  4078. flag)))
  4079. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4080. ;; Declare Column View Code
  4081. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4082. (declare-function org-columns-compute "org-colview" (property))
  4083. ;; Declare ID code
  4084. (declare-function org-id-store-link "org-id")
  4085. (declare-function org-id-locations-load "org-id")
  4086. (declare-function org-id-locations-save "org-id")
  4087. (defvar org-id-track-globally)
  4088. ;;; Variables for pre-computed regular expressions, all buffer local
  4089. (defvar-local org-todo-regexp nil
  4090. "Matches any of the TODO state keywords.
  4091. Since TODO keywords are case-sensitive, `case-fold-search' is
  4092. expected to be bound to nil when matching against this regexp.")
  4093. (defvar-local org-not-done-regexp nil
  4094. "Matches any of the TODO state keywords except the last one.
  4095. Since TODO keywords are case-sensitive, `case-fold-search' is
  4096. expected to be bound to nil when matching against this regexp.")
  4097. (defvar-local org-not-done-heading-regexp nil
  4098. "Matches a TODO headline that is not done.
  4099. Since TODO keywords are case-sensitive, `case-fold-search' is
  4100. expected to be bound to nil when matching against this regexp.")
  4101. (defvar-local org-todo-line-regexp nil
  4102. "Matches a headline and puts TODO state into group 2 if present.
  4103. Since TODO keywords are case-sensitive, `case-fold-search' is
  4104. expected to be bound to nil when matching against this regexp.")
  4105. (defvar-local org-complex-heading-regexp nil
  4106. "Matches a headline and puts everything into groups:
  4107. group 1: Stars
  4108. group 2: The TODO keyword, maybe
  4109. group 3: Priority cookie
  4110. group 4: True headline
  4111. group 5: Tags
  4112. Since TODO keywords are case-sensitive, `case-fold-search' is
  4113. expected to be bound to nil when matching against this regexp.")
  4114. (defvar-local org-complex-heading-regexp-format nil
  4115. "Printf format to make regexp to match an exact headline.
  4116. This regexp will match the headline of any node which has the
  4117. exact headline text that is put into the format, but may have any
  4118. TODO state, priority and tags.")
  4119. (defvar-local org-todo-line-tags-regexp nil
  4120. "Matches a headline and puts TODO state into group 2 if present.
  4121. Also put tags into group 4 if tags are present.")
  4122. (defconst org-plain-time-of-day-regexp
  4123. (concat
  4124. "\\(\\<[012]?[0-9]"
  4125. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4126. "\\(--?"
  4127. "\\(\\<[012]?[0-9]"
  4128. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4129. "\\)?")
  4130. "Regular expression to match a plain time or time range.
  4131. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4132. groups carry important information:
  4133. 0 the full match
  4134. 1 the first time, range or not
  4135. 8 the second time, if it is a range.")
  4136. (defconst org-plain-time-extension-regexp
  4137. (concat
  4138. "\\(\\<[012]?[0-9]"
  4139. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4140. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4141. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4142. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4143. groups carry important information:
  4144. 0 the full match
  4145. 7 hours of duration
  4146. 9 minutes of duration")
  4147. (defconst org-stamp-time-of-day-regexp
  4148. (concat
  4149. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4150. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4151. "\\(--?"
  4152. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4153. "Regular expression to match a timestamp time or time range.
  4154. After a match, the following groups carry important information:
  4155. 0 the full match
  4156. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4157. 2 the first time, range or not
  4158. 4 the second time, if it is a range.")
  4159. (defconst org-startup-options
  4160. '(("fold" org-startup-folded t)
  4161. ("overview" org-startup-folded t)
  4162. ("nofold" org-startup-folded nil)
  4163. ("showall" org-startup-folded nil)
  4164. ("showeverything" org-startup-folded showeverything)
  4165. ("content" org-startup-folded content)
  4166. ("indent" org-startup-indented t)
  4167. ("noindent" org-startup-indented nil)
  4168. ("hidestars" org-hide-leading-stars t)
  4169. ("showstars" org-hide-leading-stars nil)
  4170. ("odd" org-odd-levels-only t)
  4171. ("oddeven" org-odd-levels-only nil)
  4172. ("align" org-startup-align-all-tables t)
  4173. ("noalign" org-startup-align-all-tables nil)
  4174. ("inlineimages" org-startup-with-inline-images t)
  4175. ("noinlineimages" org-startup-with-inline-images nil)
  4176. ("latexpreview" org-startup-with-latex-preview t)
  4177. ("nolatexpreview" org-startup-with-latex-preview nil)
  4178. ("customtime" org-display-custom-times t)
  4179. ("logdone" org-log-done time)
  4180. ("lognotedone" org-log-done note)
  4181. ("nologdone" org-log-done nil)
  4182. ("lognoteclock-out" org-log-note-clock-out t)
  4183. ("nolognoteclock-out" org-log-note-clock-out nil)
  4184. ("logrepeat" org-log-repeat state)
  4185. ("lognoterepeat" org-log-repeat note)
  4186. ("logdrawer" org-log-into-drawer t)
  4187. ("nologdrawer" org-log-into-drawer nil)
  4188. ("logstatesreversed" org-log-states-order-reversed t)
  4189. ("nologstatesreversed" org-log-states-order-reversed nil)
  4190. ("nologrepeat" org-log-repeat nil)
  4191. ("logreschedule" org-log-reschedule time)
  4192. ("lognotereschedule" org-log-reschedule note)
  4193. ("nologreschedule" org-log-reschedule nil)
  4194. ("logredeadline" org-log-redeadline time)
  4195. ("lognoteredeadline" org-log-redeadline note)
  4196. ("nologredeadline" org-log-redeadline nil)
  4197. ("logrefile" org-log-refile time)
  4198. ("lognoterefile" org-log-refile note)
  4199. ("nologrefile" org-log-refile nil)
  4200. ("fninline" org-footnote-define-inline t)
  4201. ("nofninline" org-footnote-define-inline nil)
  4202. ("fnlocal" org-footnote-section nil)
  4203. ("fnauto" org-footnote-auto-label t)
  4204. ("fnprompt" org-footnote-auto-label nil)
  4205. ("fnconfirm" org-footnote-auto-label confirm)
  4206. ("fnplain" org-footnote-auto-label plain)
  4207. ("fnadjust" org-footnote-auto-adjust t)
  4208. ("nofnadjust" org-footnote-auto-adjust nil)
  4209. ("constcgs" constants-unit-system cgs)
  4210. ("constSI" constants-unit-system SI)
  4211. ("noptag" org-tag-persistent-alist nil)
  4212. ("hideblocks" org-hide-block-startup t)
  4213. ("nohideblocks" org-hide-block-startup nil)
  4214. ("beamer" org-startup-with-beamer-mode t)
  4215. ("entitiespretty" org-pretty-entities t)
  4216. ("entitiesplain" org-pretty-entities nil))
  4217. "Variable associated with STARTUP options for org-mode.
  4218. Each element is a list of three items: the startup options (as written
  4219. in the #+STARTUP line), the corresponding variable, and the value to set
  4220. this variable to if the option is found. An optional forth element PUSH
  4221. means to push this value onto the list in the variable.")
  4222. (defcustom org-group-tags t
  4223. "When non-nil (the default), use group tags.
  4224. This can be turned on/off through `org-toggle-tags-groups'."
  4225. :group 'org-tags
  4226. :group 'org-startup
  4227. :type 'boolean)
  4228. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4229. (defun org-toggle-tags-groups ()
  4230. "Toggle support for group tags.
  4231. Support for group tags is controlled by the option
  4232. `org-group-tags', which is non-nil by default."
  4233. (interactive)
  4234. (setq org-group-tags (not org-group-tags))
  4235. (cond ((and (derived-mode-p 'org-agenda-mode)
  4236. org-group-tags)
  4237. (org-agenda-redo))
  4238. ((derived-mode-p 'org-mode)
  4239. (let ((org-inhibit-startup t)) (org-mode))))
  4240. (message "Groups tags support has been turned %s"
  4241. (if org-group-tags "on" "off")))
  4242. (defun org-set-regexps-and-options (&optional tags-only)
  4243. "Precompute regular expressions used in the current buffer.
  4244. When optional argument TAGS-ONLY is non-nil, only compute tags
  4245. related expressions."
  4246. (when (derived-mode-p 'org-mode)
  4247. (let ((alist (org--setup-collect-keywords
  4248. (org-make-options-regexp
  4249. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4250. (and (not tags-only)
  4251. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4252. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4253. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4254. ;; Startup options. Get this early since it does change
  4255. ;; behavior for other options (e.g., tags).
  4256. (let ((startup (cdr (assq 'startup alist))))
  4257. (dolist (option startup)
  4258. (let ((entry (assoc-string option org-startup-options t)))
  4259. (when entry
  4260. (let ((var (nth 1 entry))
  4261. (val (nth 2 entry)))
  4262. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4263. (unless (listp (symbol-value var))
  4264. (set (make-local-variable var) nil))
  4265. (add-to-list var val)))))))
  4266. (setq-local org-file-tags
  4267. (mapcar #'org-add-prop-inherited
  4268. (cdr (assq 'filetags alist))))
  4269. (setq org-current-tag-alist
  4270. (append org-tag-persistent-alist
  4271. (let ((tags (cdr (assq 'tags alist))))
  4272. (if tags (org-tag-string-to-alist tags)
  4273. org-tag-alist))))
  4274. (setq org-tag-groups-alist
  4275. (org-tag-alist-to-groups org-current-tag-alist))
  4276. (unless tags-only
  4277. ;; File properties.
  4278. (setq-local org-file-properties (cdr (assq 'property alist)))
  4279. ;; Archive location.
  4280. (let ((archive (cdr (assq 'archive alist))))
  4281. (when archive (setq-local org-archive-location archive)))
  4282. ;; Category.
  4283. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4284. (when cat
  4285. (setq-local org-category (intern cat))
  4286. (setq-local org-file-properties
  4287. (org--update-property-plist
  4288. "CATEGORY" cat org-file-properties))))
  4289. ;; Columns.
  4290. (let ((column (cdr (assq 'columns alist))))
  4291. (when column (setq-local org-columns-default-format column)))
  4292. ;; Constants.
  4293. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4294. ;; Link abbreviations.
  4295. (let ((links (cdr (assq 'link alist))))
  4296. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4297. ;; Priorities.
  4298. (let ((priorities (cdr (assq 'priorities alist))))
  4299. (when priorities
  4300. (setq-local org-highest-priority (nth 0 priorities))
  4301. (setq-local org-lowest-priority (nth 1 priorities))
  4302. (setq-local org-default-priority (nth 2 priorities))))
  4303. ;; Scripts.
  4304. (let ((scripts (assq 'scripts alist)))
  4305. (when scripts
  4306. (setq-local org-use-sub-superscripts (cdr scripts))))
  4307. ;; TODO keywords.
  4308. (setq-local org-todo-kwd-alist nil)
  4309. (setq-local org-todo-key-alist nil)
  4310. (setq-local org-todo-key-trigger nil)
  4311. (setq-local org-todo-keywords-1 nil)
  4312. (setq-local org-done-keywords nil)
  4313. (setq-local org-todo-heads nil)
  4314. (setq-local org-todo-sets nil)
  4315. (setq-local org-todo-log-states nil)
  4316. (let ((todo-sequences
  4317. (or (nreverse (cdr (assq 'todo alist)))
  4318. (let ((d (default-value 'org-todo-keywords)))
  4319. (if (not (stringp (car d))) d
  4320. ;; XXX: Backward compatibility code.
  4321. (list (cons org-todo-interpretation d)))))))
  4322. (dolist (sequence todo-sequences)
  4323. (let* ((sequence (or (run-hook-with-args-until-success
  4324. 'org-todo-setup-filter-hook sequence)
  4325. sequence))
  4326. (sequence-type (car sequence))
  4327. (keywords (cdr sequence))
  4328. (sep (member "|" keywords))
  4329. names alist)
  4330. (dolist (k (remove "|" keywords))
  4331. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4332. k)
  4333. (error "Invalid TODO keyword %s" k))
  4334. (let ((name (match-string 1 k))
  4335. (key (match-string 2 k))
  4336. (log (org-extract-log-state-settings k)))
  4337. (push name names)
  4338. (push (cons name (and key (string-to-char key))) alist)
  4339. (when log (push log org-todo-log-states))))
  4340. (let* ((names (nreverse names))
  4341. (done (if sep (org-remove-keyword-keys (cdr sep))
  4342. (last names)))
  4343. (head (car names))
  4344. (tail (list sequence-type head (car done) (org-last done))))
  4345. (add-to-list 'org-todo-heads head 'append)
  4346. (push names org-todo-sets)
  4347. (setq org-done-keywords (append org-done-keywords done nil))
  4348. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4349. (setq org-todo-key-alist
  4350. (append org-todo-key-alist
  4351. (and alist
  4352. (append '((:startgroup))
  4353. (nreverse alist)
  4354. '((:endgroup))))))
  4355. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4356. (setq org-todo-sets (nreverse org-todo-sets)
  4357. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4358. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4359. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4360. ;; Compute the regular expressions and other local variables.
  4361. ;; Using `org-outline-regexp-bol' would complicate them much,
  4362. ;; because of the fixed white space at the end of that string.
  4363. (unless org-done-keywords
  4364. (setq org-done-keywords
  4365. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4366. (setq org-not-done-keywords
  4367. (org-delete-all org-done-keywords
  4368. (copy-sequence org-todo-keywords-1))
  4369. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4370. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4371. org-not-done-heading-regexp
  4372. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4373. org-todo-line-regexp
  4374. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4375. org-complex-heading-regexp
  4376. (concat "^\\(\\*+\\)"
  4377. "\\(?: +" org-todo-regexp "\\)?"
  4378. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4379. "\\(?: +\\(.*?\\)\\)??"
  4380. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4381. "[ \t]*$")
  4382. org-complex-heading-regexp-format
  4383. (concat "^\\(\\*+\\)"
  4384. "\\(?: +" org-todo-regexp "\\)?"
  4385. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4386. "\\(?: +"
  4387. ;; Stats cookies can be stuck to body.
  4388. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4389. "\\(%s\\)"
  4390. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4391. "\\)"
  4392. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4393. "[ \t]*$")
  4394. org-todo-line-tags-regexp
  4395. (concat "^\\(\\*+\\)"
  4396. "\\(?: +" org-todo-regexp "\\)?"
  4397. "\\(?: +\\(.*?\\)\\)??"
  4398. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4399. "[ \t]*$"))
  4400. (org-compute-latex-and-related-regexp)))))
  4401. (defun org--setup-collect-keywords (regexp &optional files alist)
  4402. "Return setup keywords values as an alist.
  4403. REGEXP matches a subset of setup keywords. FILES is a list of
  4404. file names already visited. It is used to avoid circular setup
  4405. files. ALIST, when non-nil, is the alist computed so far.
  4406. Return value contains the following keys: `archive', `category',
  4407. `columns', `constants', `filetags', `link', `priorities',
  4408. `property', `scripts', `startup', `tags' and `todo'."
  4409. (org-with-wide-buffer
  4410. (goto-char (point-min))
  4411. (let ((case-fold-search t))
  4412. (while (re-search-forward regexp nil t)
  4413. (let ((element (org-element-at-point)))
  4414. (when (eq (org-element-type element) 'keyword)
  4415. (let ((key (org-element-property :key element))
  4416. (value (org-element-property :value element)))
  4417. (cond
  4418. ((equal key "ARCHIVE")
  4419. (when (org-string-nw-p value)
  4420. (push (cons 'archive value) alist)))
  4421. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4422. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4423. ((equal key "CONSTANTS")
  4424. (let* ((constants (assq 'constants alist))
  4425. (store (cdr constants)))
  4426. (dolist (pair (org-split-string value))
  4427. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4428. pair)
  4429. (let* ((name (match-string 1 pair))
  4430. (value (match-string 2 pair))
  4431. (old (assoc name store)))
  4432. (if old (setcdr old value)
  4433. (push (cons name value) store)))))
  4434. (if constants (setcdr constants store)
  4435. (push (cons 'constants store) alist))))
  4436. ((equal key "FILETAGS")
  4437. (when (org-string-nw-p value)
  4438. (let ((old (assq 'filetags alist))
  4439. (new (apply #'nconc
  4440. (mapcar (lambda (x) (org-split-string x ":"))
  4441. (org-split-string value)))))
  4442. (if old (setcdr old (append new (cdr old)))
  4443. (push (cons 'filetags new) alist)))))
  4444. ((equal key "LINK")
  4445. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4446. (let ((links (assq 'link alist))
  4447. (pair (cons (match-string-no-properties 1 value)
  4448. (match-string-no-properties 2 value))))
  4449. (if links (push pair (cdr links))
  4450. (push (list 'link pair) alist)))))
  4451. ((equal key "OPTIONS")
  4452. (when (and (org-string-nw-p value)
  4453. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4454. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4455. ((equal key "PRIORITIES")
  4456. (push (cons 'priorities
  4457. (let ((prio (org-split-string value)))
  4458. (if (< (length prio) 3) '(?A ?C ?B)
  4459. (mapcar #'string-to-char prio))))
  4460. alist))
  4461. ((equal key "PROPERTY")
  4462. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4463. (let* ((property (assq 'property alist))
  4464. (value (org--update-property-plist
  4465. (match-string-no-properties 1 value)
  4466. (match-string-no-properties 2 value)
  4467. (cdr property))))
  4468. (if property (setcdr property value)
  4469. (push (cons 'property value) alist)))))
  4470. ((equal key "STARTUP")
  4471. (let ((startup (assq 'startup alist)))
  4472. (if startup
  4473. (setcdr startup
  4474. (append (cdr startup) (org-split-string value)))
  4475. (push (cons 'startup (org-split-string value)) alist))))
  4476. ((equal key "TAGS")
  4477. (let ((tag-cell (assq 'tags alist)))
  4478. (if tag-cell
  4479. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4480. (push (cons 'tags value) alist))))
  4481. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4482. (let ((todo (assq 'todo alist))
  4483. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4484. (org-split-string value))))
  4485. (if todo (push value (cdr todo))
  4486. (push (list 'todo value) alist))))
  4487. ((equal key "SETUPFILE")
  4488. (unless buffer-read-only ; Do not check in Gnus messages.
  4489. (let ((f (and (org-string-nw-p value)
  4490. (expand-file-name
  4491. (org-unbracket-string "\"" "\"" value)))))
  4492. (when (and f (file-readable-p f) (not (member f files)))
  4493. (with-temp-buffer
  4494. (setq default-directory (file-name-directory f))
  4495. (insert-file-contents f)
  4496. (setq alist
  4497. ;; Fake Org mode to benefit from cache
  4498. ;; without recurring needlessly.
  4499. (let ((major-mode 'org-mode))
  4500. (org--setup-collect-keywords
  4501. regexp (cons f files) alist)))))))))))))))
  4502. alist)
  4503. (defun org-tag-string-to-alist (s)
  4504. "Return tag alist associated to string S.
  4505. S is a value for TAGS keyword or produced with
  4506. `org-tag-alist-to-string'. Return value is an alist suitable for
  4507. `org-tag-alist' or `org-tag-persistent-alist'."
  4508. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4509. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4510. "\\|{.+?}\\)" ; regular expression
  4511. "\\(?:(\\(.\\))\\)?\\'"))
  4512. alist group-flag)
  4513. (dolist (tokens lines (cdr (nreverse alist)))
  4514. (push '(:newline) alist)
  4515. (while tokens
  4516. (let ((token (pop tokens)))
  4517. (pcase token
  4518. ("{"
  4519. (push '(:startgroup) alist)
  4520. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4521. ("}"
  4522. (push '(:endgroup) alist)
  4523. (setq group-flag nil))
  4524. ("["
  4525. (push '(:startgrouptag) alist)
  4526. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4527. ("]"
  4528. (push '(:endgrouptag) alist)
  4529. (setq group-flag nil))
  4530. (":"
  4531. (push '(:grouptags) alist))
  4532. ((guard (string-match tag-re token))
  4533. (let ((tag (match-string 1 token))
  4534. (key (and (match-beginning 2)
  4535. (string-to-char (match-string 2 token)))))
  4536. ;; Push all tags in groups, no matter if they already
  4537. ;; appear somewhere else in the list.
  4538. (when (or group-flag (not (assoc tag alist)))
  4539. (push (cons tag key) alist))))))))))
  4540. (defun org-tag-alist-to-string (alist &optional skip-key)
  4541. "Return tag string associated to ALIST.
  4542. ALIST is an alist, as defined in `org-tag-alist' or
  4543. `org-tag-persistent-alist', or produced with
  4544. `org-tag-string-to-alist'.
  4545. Return value is a string suitable as a value for \"TAGS\"
  4546. keyword.
  4547. When optional argument SKIP-KEY is non-nil, skip selection keys
  4548. next to tags."
  4549. (mapconcat (lambda (token)
  4550. (pcase token
  4551. (`(:startgroup) "{")
  4552. (`(:endgroup) "}")
  4553. (`(:startgrouptag) "[")
  4554. (`(:endgrouptag) "]")
  4555. (`(:grouptags) ":")
  4556. (`(:newline) "\\n")
  4557. ((and
  4558. (guard (not skip-key))
  4559. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4560. (format "%s(%c)" tag key))
  4561. (`(,(and tag (pred stringp)) . ,_) tag)
  4562. (_ (user-error "Invalid tag token: %S" token))))
  4563. alist
  4564. " "))
  4565. (defun org-tag-alist-to-groups (alist)
  4566. "Return group alist from tag ALIST.
  4567. ALIST is an alist, as defined in `org-tag-alist' or
  4568. `org-tag-persistent-alist', or produced with
  4569. `org-tag-string-to-alist'. Return value is an alist following
  4570. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4571. a string, summarizing TAGS, as a list of strings."
  4572. (let (groups group-status current-group)
  4573. (dolist (token alist (nreverse groups))
  4574. (pcase token
  4575. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4576. (`(,(or :endgroup :endgrouptag))
  4577. (when (eq group-status 'append)
  4578. (push (nreverse current-group) groups))
  4579. (setq group-status nil))
  4580. (`(:grouptags) (setq group-status 'append))
  4581. ((and `(,tag . ,_) (guard group-status))
  4582. (if (eq group-status 'append) (push tag current-group)
  4583. (setq current-group (list tag))))
  4584. (_ nil)))))
  4585. (defun org-file-contents (file &optional noerror)
  4586. "Return the contents of FILE, as a string."
  4587. (if (and file (file-readable-p file))
  4588. (with-temp-buffer
  4589. (insert-file-contents file)
  4590. (buffer-string))
  4591. (funcall (if noerror 'message 'error)
  4592. "Cannot read file \"%s\"%s"
  4593. file
  4594. (let ((from (buffer-file-name (buffer-base-buffer))))
  4595. (if from (concat " (referenced in file \"" from "\")") "")))))
  4596. (defun org-extract-log-state-settings (x)
  4597. "Extract the log state setting from a TODO keyword string.
  4598. This will extract info from a string like \"WAIT(w@/!)\"."
  4599. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4600. (let ((kw (match-string 1 x))
  4601. (log1 (and (match-end 3) (match-string 3 x)))
  4602. (log2 (and (match-end 4) (match-string 4 x))))
  4603. (and (or log1 log2)
  4604. (list kw
  4605. (and log1 (if (equal log1 "!") 'time 'note))
  4606. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4607. (defun org-remove-keyword-keys (list)
  4608. "Remove a pair of parenthesis at the end of each string in LIST."
  4609. (mapcar (lambda (x)
  4610. (if (string-match "(.*)$" x)
  4611. (substring x 0 (match-beginning 0))
  4612. x))
  4613. list))
  4614. (defun org-assign-fast-keys (alist)
  4615. "Assign fast keys to a keyword-key alist.
  4616. Respect keys that are already there."
  4617. (let (new e (alt ?0))
  4618. (while (setq e (pop alist))
  4619. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4620. (cdr e)) ;; Key already assigned.
  4621. (push e new)
  4622. (let ((clist (string-to-list (downcase (car e))))
  4623. (used (append new alist)))
  4624. (when (= (car clist) ?@)
  4625. (pop clist))
  4626. (while (and clist (rassoc (car clist) used))
  4627. (pop clist))
  4628. (unless clist
  4629. (while (rassoc alt used)
  4630. (cl-incf alt)))
  4631. (push (cons (car e) (or (car clist) alt)) new))))
  4632. (nreverse new)))
  4633. ;;; Some variables used in various places
  4634. (defvar org-window-configuration nil
  4635. "Used in various places to store a window configuration.")
  4636. (defvar org-selected-window nil
  4637. "Used in various places to store a window configuration.")
  4638. (defvar org-finish-function nil
  4639. "Function to be called when `C-c C-c' is used.
  4640. This is for getting out of special buffers like capture.")
  4641. (defvar org-last-state)
  4642. ;; Defined somewhere in this file, but used before definition.
  4643. (defvar org-entities) ;; defined in org-entities.el
  4644. (defvar org-struct-menu)
  4645. (defvar org-org-menu)
  4646. (defvar org-tbl-menu)
  4647. ;;;; Define the Org mode
  4648. ;; We use a before-change function to check if a table might need
  4649. ;; an update.
  4650. (defvar org-table-may-need-update t
  4651. "Indicates that a table might need an update.
  4652. This variable is set by `org-before-change-function'.
  4653. `org-table-align' sets it back to nil.")
  4654. (defun org-before-change-function (_beg _end)
  4655. "Every change indicates that a table might need an update."
  4656. (setq org-table-may-need-update t))
  4657. (defvar org-mode-map)
  4658. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4659. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4660. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4661. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4662. (defvar org-table-buffer-is-an nil)
  4663. (defvar bidi-paragraph-direction)
  4664. (defvar buffer-face-mode-face)
  4665. (require 'outline)
  4666. ;; Other stuff we need.
  4667. (require 'time-date)
  4668. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4669. (require 'easymenu)
  4670. (autoload 'easy-menu-add "easymenu")
  4671. (require 'overlay)
  4672. ;; (require 'org-macs) moved higher up in the file before it is first used
  4673. (require 'org-entities)
  4674. ;; (require 'org-compat) moved higher up in the file before it is first used
  4675. (require 'org-faces)
  4676. (require 'org-list)
  4677. (require 'org-pcomplete)
  4678. (require 'org-src)
  4679. (require 'org-footnote)
  4680. (require 'org-macro)
  4681. ;; babel
  4682. (require 'ob)
  4683. ;;;###autoload
  4684. (define-derived-mode org-mode outline-mode "Org"
  4685. "Outline-based notes management and organizer, alias
  4686. \"Carsten's outline-mode for keeping track of everything.\"
  4687. Org mode develops organizational tasks around a NOTES file which
  4688. contains information about projects as plain text. Org mode is
  4689. implemented on top of Outline mode, which is ideal to keep the content
  4690. of large files well structured. It supports ToDo items, deadlines and
  4691. time stamps, which magically appear in the diary listing of the Emacs
  4692. calendar. Tables are easily created with a built-in table editor.
  4693. Plain text URL-like links connect to websites, emails (VM), Usenet
  4694. messages (Gnus), BBDB entries, and any files related to the project.
  4695. For printing and sharing of notes, an Org file (or a part of it)
  4696. can be exported as a structured ASCII or HTML file.
  4697. The following commands are available:
  4698. \\{org-mode-map}"
  4699. ;; Get rid of Outline menus, they are not needed
  4700. ;; Need to do this here because define-derived-mode sets up
  4701. ;; the keymap so late. Still, it is a waste to call this each time
  4702. ;; we switch another buffer into Org mode.
  4703. (define-key org-mode-map [menu-bar headings] 'undefined)
  4704. (define-key org-mode-map [menu-bar hide] 'undefined)
  4705. (define-key org-mode-map [menu-bar show] 'undefined)
  4706. (org-load-modules-maybe)
  4707. (org-install-agenda-files-menu)
  4708. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4709. (add-to-invisibility-spec '(org-cwidth))
  4710. (add-to-invisibility-spec '(org-hide-block . t))
  4711. (setq-local outline-regexp org-outline-regexp)
  4712. (setq-local outline-level 'org-outline-level)
  4713. (setq bidi-paragraph-direction 'left-to-right)
  4714. (when (and org-ellipsis
  4715. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4716. (fboundp 'make-glyph-code))
  4717. (unless org-display-table
  4718. (setq org-display-table (make-display-table)))
  4719. (set-display-table-slot
  4720. org-display-table 4
  4721. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4722. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4723. (setq buffer-display-table org-display-table))
  4724. (org-set-regexps-and-options)
  4725. (org-set-font-lock-defaults)
  4726. (when (and org-tag-faces (not org-tags-special-faces-re))
  4727. ;; tag faces set outside customize.... force initialization.
  4728. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4729. ;; Calc embedded
  4730. (setq-local calc-embedded-open-mode "# ")
  4731. ;; Modify a few syntax entries
  4732. (modify-syntax-entry ?@ "w")
  4733. (modify-syntax-entry ?\" "\"")
  4734. (modify-syntax-entry ?\\ "_")
  4735. (modify-syntax-entry ?~ "_")
  4736. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4737. ;; Activate before-change-function
  4738. (setq-local org-table-may-need-update t)
  4739. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4740. ;; Check for running clock before killing a buffer
  4741. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4742. ;; Initialize macros templates.
  4743. (org-macro-initialize-templates)
  4744. ;; Initialize radio targets.
  4745. (org-update-radio-target-regexp)
  4746. ;; Indentation.
  4747. (setq-local indent-line-function 'org-indent-line)
  4748. (setq-local indent-region-function 'org-indent-region)
  4749. ;; Filling and auto-filling.
  4750. (org-setup-filling)
  4751. ;; Comments.
  4752. (org-setup-comments-handling)
  4753. ;; Initialize cache.
  4754. (org-element-cache-reset)
  4755. ;; Beginning/end of defun
  4756. (setq-local beginning-of-defun-function 'org-backward-element)
  4757. (setq-local end-of-defun-function
  4758. (lambda ()
  4759. (if (not (org-at-heading-p))
  4760. (org-forward-element)
  4761. (org-forward-element)
  4762. (forward-char -1))))
  4763. ;; Next error for sparse trees
  4764. (setq-local next-error-function 'org-occur-next-match)
  4765. ;; Make sure dependence stuff works reliably, even for users who set it
  4766. ;; too late :-(
  4767. (if org-enforce-todo-dependencies
  4768. (add-hook 'org-blocker-hook
  4769. 'org-block-todo-from-children-or-siblings-or-parent)
  4770. (remove-hook 'org-blocker-hook
  4771. 'org-block-todo-from-children-or-siblings-or-parent))
  4772. (if org-enforce-todo-checkbox-dependencies
  4773. (add-hook 'org-blocker-hook
  4774. 'org-block-todo-from-checkboxes)
  4775. (remove-hook 'org-blocker-hook
  4776. 'org-block-todo-from-checkboxes))
  4777. ;; Align options lines
  4778. (setq-local
  4779. align-mode-rules-list
  4780. '((org-in-buffer-settings
  4781. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4782. (modes . '(org-mode)))))
  4783. ;; Imenu
  4784. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4785. ;; Make isearch reveal context
  4786. (setq-local outline-isearch-open-invisible-function
  4787. (lambda (&rest _) (org-show-context 'isearch)))
  4788. ;; Setup the pcomplete hooks
  4789. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4790. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4791. (setq-local pcomplete-default-completion-function 'ignore)
  4792. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4793. (setq-local pcomplete-termination-string "")
  4794. (setq-local buffer-face-mode-face 'org-default)
  4795. ;; If empty file that did not turn on Org mode automatically, make
  4796. ;; it to.
  4797. (when (and org-insert-mode-line-in-empty-file
  4798. (called-interactively-p 'any)
  4799. (= (point-min) (point-max)))
  4800. (insert "# -*- mode: org -*-\n\n"))
  4801. (unless org-inhibit-startup
  4802. (org-unmodified
  4803. (when org-startup-with-beamer-mode (org-beamer-mode))
  4804. (when org-startup-align-all-tables
  4805. (org-table-map-tables #'org-table-align t))
  4806. (when org-startup-with-inline-images (org-display-inline-images))
  4807. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4808. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4809. (when org-startup-truncated (setq truncate-lines t))
  4810. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4811. (org-refresh-effort-properties)))
  4812. ;; Try to set `org-hide' face correctly.
  4813. (let ((foreground (org-find-invisible-foreground)))
  4814. (when foreground
  4815. (set-face-foreground 'org-hide foreground))))
  4816. ;; Update `customize-package-emacs-version-alist'
  4817. (add-to-list 'customize-package-emacs-version-alist
  4818. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4819. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4820. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4821. ("9.0" . "26.1")))
  4822. (defvar org-mode-transpose-word-syntax-table
  4823. (let ((st (make-syntax-table text-mode-syntax-table)))
  4824. (dolist (c org-emphasis-alist st)
  4825. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4826. (when (fboundp 'abbrev-table-put)
  4827. (abbrev-table-put org-mode-abbrev-table
  4828. :parents (list text-mode-abbrev-table)))
  4829. (defun org-find-invisible-foreground ()
  4830. (let ((candidates (remove
  4831. "unspecified-bg"
  4832. (nconc
  4833. (list (face-background 'default)
  4834. (face-background 'org-default))
  4835. (mapcar
  4836. (lambda (alist)
  4837. (when (boundp alist)
  4838. (cdr (assq 'background-color (symbol-value alist)))))
  4839. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4840. (list (face-foreground 'org-hide))))))
  4841. (car (remove nil candidates))))
  4842. (defun org-current-time (&optional rounding-minutes past)
  4843. "Current time, possibly rounded to ROUNDING-MINUTES.
  4844. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4845. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4846. the rounding returns a past time."
  4847. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4848. (car org-time-stamp-rounding-minutes)))
  4849. (time (decode-time)) res)
  4850. (if (< r 1)
  4851. (current-time)
  4852. (setq res
  4853. (apply 'encode-time
  4854. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4855. (nthcdr 2 time))))
  4856. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4857. (seconds-to-time (- (float-time res) (* r 60)))
  4858. res))))
  4859. (defun org-today ()
  4860. "Return today date, considering `org-extend-today-until'."
  4861. (time-to-days
  4862. (time-subtract (current-time)
  4863. (list 0 (* 3600 org-extend-today-until) 0))))
  4864. ;;;; Font-Lock stuff, including the activators
  4865. (defvar org-mouse-map (make-sparse-keymap))
  4866. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4867. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4868. (when org-mouse-1-follows-link
  4869. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4870. (when org-tab-follows-link
  4871. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4872. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4873. (require 'font-lock)
  4874. (defconst org-non-link-chars "]\t\n\r<>")
  4875. (defvar org-link-types-re nil
  4876. "Matches a link that has a url-like prefix like \"http:\"")
  4877. (defvar org-link-re-with-space nil
  4878. "Matches a link with spaces, optional angular brackets around it.")
  4879. (defvar org-link-re-with-space2 nil
  4880. "Matches a link with spaces, optional angular brackets around it.")
  4881. (defvar org-link-re-with-space3 nil
  4882. "Matches a link with spaces, only for internal part in bracket links.")
  4883. (defvar org-angle-link-re nil
  4884. "Matches link with angular brackets, spaces are allowed.")
  4885. (defvar org-plain-link-re nil
  4886. "Matches plain link, without spaces.")
  4887. (defvar org-bracket-link-regexp nil
  4888. "Matches a link in double brackets.")
  4889. (defvar org-bracket-link-analytic-regexp nil
  4890. "Regular expression used to analyze links.
  4891. Here is what the match groups contain after a match:
  4892. 1: http:
  4893. 2: http
  4894. 3: path
  4895. 4: [desc]
  4896. 5: desc")
  4897. (defvar org-bracket-link-analytic-regexp++ nil
  4898. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4899. (defvar org-any-link-re nil
  4900. "Regular expression matching any link.")
  4901. (defconst org-match-sexp-depth 3
  4902. "Number of stacked braces for sub/superscript matching.")
  4903. (defun org-create-multibrace-regexp (left right n)
  4904. "Create a regular expression which will match a balanced sexp.
  4905. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4906. as single character strings.
  4907. The regexp returned will match the entire expression including the
  4908. delimiters. It will also define a single group which contains the
  4909. match except for the outermost delimiters. The maximum depth of
  4910. stacked delimiters is N. Escaping delimiters is not possible."
  4911. (let* ((nothing (concat "[^" left right "]*?"))
  4912. (or "\\|")
  4913. (re nothing)
  4914. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4915. (while (> n 1)
  4916. (setq n (1- n)
  4917. re (concat re or next)
  4918. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4919. (concat left "\\(" re "\\)" right)))
  4920. (defconst org-match-substring-regexp
  4921. (concat
  4922. "\\(\\S-\\)\\([_^]\\)\\("
  4923. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4924. "\\|"
  4925. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4926. "\\|"
  4927. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4928. "The regular expression matching a sub- or superscript.")
  4929. (defconst org-match-substring-with-braces-regexp
  4930. (concat
  4931. "\\(\\S-\\)\\([_^]\\)"
  4932. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4933. "The regular expression matching a sub- or superscript, forcing braces.")
  4934. (defun org-make-link-regexps ()
  4935. "Update the link regular expressions.
  4936. This should be called after the variable `org-link-parameters' has changed."
  4937. (let ((types-re (regexp-opt (org-link-types) t)))
  4938. (setq org-link-types-re
  4939. (concat "\\`" types-re ":")
  4940. org-link-re-with-space
  4941. (concat "<?" types-re ":"
  4942. "\\([^" org-non-link-chars " ]"
  4943. "[^" org-non-link-chars "]*"
  4944. "[^" org-non-link-chars " ]\\)>?")
  4945. org-link-re-with-space2
  4946. (concat "<?" types-re ":"
  4947. "\\([^" org-non-link-chars " ]"
  4948. "[^\t\n\r]*"
  4949. "[^" org-non-link-chars " ]\\)>?")
  4950. org-link-re-with-space3
  4951. (concat "<?" types-re ":"
  4952. "\\([^" org-non-link-chars " ]"
  4953. "[^\t\n\r]*\\)")
  4954. org-angle-link-re
  4955. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4956. types-re)
  4957. org-plain-link-re
  4958. (concat
  4959. "\\<" types-re ":"
  4960. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4961. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4962. org-bracket-link-regexp
  4963. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4964. org-bracket-link-analytic-regexp
  4965. (concat
  4966. "\\[\\["
  4967. "\\(" types-re ":\\)?"
  4968. "\\([^]]+\\)"
  4969. "\\]"
  4970. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4971. "\\]")
  4972. org-bracket-link-analytic-regexp++
  4973. (concat
  4974. "\\[\\["
  4975. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4976. "\\([^]]+\\)"
  4977. "\\]"
  4978. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4979. "\\]")
  4980. org-any-link-re
  4981. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4982. org-angle-link-re "\\)\\|\\("
  4983. org-plain-link-re "\\)"))))
  4984. (org-make-link-regexps)
  4985. (defvar org-emph-face nil)
  4986. (defun org-do-emphasis-faces (limit)
  4987. "Run through the buffer and emphasize strings."
  4988. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4989. (car org-emphasis-regexp-components))))
  4990. (catch :exit
  4991. (while (re-search-forward quick-re limit t)
  4992. (let* ((marker (match-string 2))
  4993. (verbatim? (member marker '("~" "="))))
  4994. (when (save-excursion
  4995. (goto-char (match-beginning 0))
  4996. ;; Do not match headline stars. Do not consider
  4997. ;; stars of a headline as closing marker for bold
  4998. ;; markup either.
  4999. (and (not (looking-at-p org-outline-regexp-bol))
  5000. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5001. (not (string-match-p
  5002. (concat org-outline-regexp-bol "\\'")
  5003. (match-string 0)))))
  5004. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5005. (font-lock-prepend-text-property
  5006. (match-beginning 2) (match-end 2) 'face face)
  5007. (when verbatim?
  5008. (org-remove-flyspell-overlays-in
  5009. (match-beginning 0) (match-end 0)))
  5010. (add-text-properties (match-beginning 2) (match-end 2)
  5011. '(font-lock-multiline t org-emphasis t))
  5012. (when org-hide-emphasis-markers
  5013. (add-text-properties (match-end 4) (match-beginning 5)
  5014. '(invisible org-link))
  5015. (add-text-properties (match-beginning 3) (match-end 3)
  5016. '(invisible org-link)))
  5017. (throw :exit t))))))))
  5018. (defun org-emphasize (&optional char)
  5019. "Insert or change an emphasis, i.e. a font like bold or italic.
  5020. If there is an active region, change that region to a new emphasis.
  5021. If there is no region, just insert the marker characters and position
  5022. the cursor between them.
  5023. CHAR should be the marker character. If it is a space, it means to
  5024. remove the emphasis of the selected region.
  5025. If CHAR is not given (for example in an interactive call) it will be
  5026. prompted for."
  5027. (interactive)
  5028. (let ((erc org-emphasis-regexp-components)
  5029. (string "") beg end move s)
  5030. (if (org-region-active-p)
  5031. (setq beg (region-beginning)
  5032. end (region-end)
  5033. string (buffer-substring beg end))
  5034. (setq move t))
  5035. (unless char
  5036. (message "Emphasis marker or tag: [%s]"
  5037. (mapconcat #'car org-emphasis-alist ""))
  5038. (setq char (read-char-exclusive)))
  5039. (if (equal char ?\s)
  5040. (setq s ""
  5041. move nil)
  5042. (unless (assoc (char-to-string char) org-emphasis-alist)
  5043. (user-error "No such emphasis marker: \"%c\"" char))
  5044. (setq s (char-to-string char)))
  5045. (while (and (> (length string) 1)
  5046. (equal (substring string 0 1) (substring string -1))
  5047. (assoc (substring string 0 1) org-emphasis-alist))
  5048. (setq string (substring string 1 -1)))
  5049. (setq string (concat s string s))
  5050. (when beg (delete-region beg end))
  5051. (unless (or (bolp)
  5052. (string-match (concat "[" (nth 0 erc) "\n]")
  5053. (char-to-string (char-before (point)))))
  5054. (insert " "))
  5055. (unless (or (eobp)
  5056. (string-match (concat "[" (nth 1 erc) "\n]")
  5057. (char-to-string (char-after (point)))))
  5058. (insert " ") (backward-char 1))
  5059. (insert string)
  5060. (and move (backward-char 1))))
  5061. (defconst org-nonsticky-props
  5062. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5063. (defsubst org-rear-nonsticky-at (pos)
  5064. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5065. (defun org-activate-plain-links (limit)
  5066. "Add link properties for plain links."
  5067. (when (and (re-search-forward org-plain-link-re limit t)
  5068. (not (org-in-src-block-p)))
  5069. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5070. 'face))
  5071. (link (match-string-no-properties 0))
  5072. (type (match-string-no-properties 1))
  5073. (path (match-string-no-properties 2))
  5074. (link-start (match-beginning 0))
  5075. (link-end (match-end 0))
  5076. (link-face (org-link-get-parameter type :face))
  5077. (help-echo (org-link-get-parameter type :help-echo))
  5078. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5079. (activate-func (org-link-get-parameter type :activate-func)))
  5080. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5081. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5082. (add-text-properties (match-beginning 0) (match-end 0)
  5083. (list
  5084. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5085. 'highlight)
  5086. 'face (cond
  5087. ;; A function that returns a face
  5088. ((functionp link-face)
  5089. (funcall link-face path))
  5090. ;; a face
  5091. ((facep link-face)
  5092. link-face)
  5093. ;; An anonymous face
  5094. ((consp link-face)
  5095. link-face)
  5096. ;; default
  5097. (t
  5098. 'org-link))
  5099. 'help-echo (cond
  5100. ((stringp help-echo)
  5101. help-echo)
  5102. ((functionp help-echo)
  5103. help-echo)
  5104. (t
  5105. (concat "LINK: "
  5106. (save-match-data
  5107. (org-link-unescape link)))))
  5108. 'htmlize-link (cond
  5109. ((functionp htmlize-link)
  5110. (funcall htmlize-link path))
  5111. (t
  5112. `(:uri ,link)))
  5113. 'keymap (or (org-link-get-parameter type :keymap)
  5114. org-mouse-map)
  5115. 'org-link-start (match-beginning 0)))
  5116. (org-rear-nonsticky-at (match-end 0))
  5117. (when activate-func
  5118. (funcall activate-func link-start link-end path nil))
  5119. t))))
  5120. (defun org-activate-code (limit)
  5121. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5122. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5123. (remove-text-properties (match-beginning 0) (match-end 0)
  5124. '(display t invisible t intangible t))
  5125. t))
  5126. (defcustom org-src-fontify-natively t
  5127. "When non-nil, fontify code in code blocks.
  5128. See also the `org-block' face."
  5129. :type 'boolean
  5130. :version "24.4"
  5131. :package-version '(Org . "8.3")
  5132. :group 'org-appearance
  5133. :group 'org-babel)
  5134. (defcustom org-allow-promoting-top-level-subtree nil
  5135. "When non-nil, allow promoting a top level subtree.
  5136. The leading star of the top level headline will be replaced
  5137. by a #."
  5138. :type 'boolean
  5139. :version "24.1"
  5140. :group 'org-appearance)
  5141. (defun org-fontify-meta-lines-and-blocks (limit)
  5142. (condition-case nil
  5143. (org-fontify-meta-lines-and-blocks-1 limit)
  5144. (error (message "org-mode fontification error in %S at %d"
  5145. (current-buffer)
  5146. (line-number-at-pos)))))
  5147. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5148. "Fontify #+ lines and blocks."
  5149. (let ((case-fold-search t))
  5150. (when (re-search-forward
  5151. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5152. limit t)
  5153. (let ((beg (match-beginning 0))
  5154. (block-start (match-end 0))
  5155. (block-end nil)
  5156. (lang (match-string 7))
  5157. (beg1 (line-beginning-position 2))
  5158. (dc1 (downcase (match-string 2)))
  5159. (dc3 (downcase (match-string 3)))
  5160. end end1 quoting block-type)
  5161. (cond
  5162. ((and (match-end 4) (equal dc3 "+begin"))
  5163. ;; Truly a block
  5164. (setq block-type (downcase (match-string 5))
  5165. quoting (member block-type org-protecting-blocks))
  5166. (when (re-search-forward
  5167. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5168. nil t) ;; on purpose, we look further than LIMIT
  5169. (setq end (min (point-max) (match-end 0))
  5170. end1 (min (point-max) (1- (match-beginning 0))))
  5171. (setq block-end (match-beginning 0))
  5172. (when quoting
  5173. (org-remove-flyspell-overlays-in beg1 end1)
  5174. (remove-text-properties beg end
  5175. '(display t invisible t intangible t)))
  5176. (add-text-properties
  5177. beg end '(font-lock-fontified t font-lock-multiline t))
  5178. (add-text-properties beg beg1 '(face org-meta-line))
  5179. (org-remove-flyspell-overlays-in beg beg1)
  5180. (add-text-properties ; For end_src
  5181. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5182. (org-remove-flyspell-overlays-in end1 end)
  5183. (cond
  5184. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5185. (org-src-font-lock-fontify-block lang block-start block-end)
  5186. (add-text-properties beg1 block-end '(src-block t)))
  5187. (quoting
  5188. (add-text-properties beg1 (min (point-max) (1+ end1))
  5189. (list 'face
  5190. (list :inherit
  5191. (let ((face-name
  5192. (intern (format "org-block-%s" lang))))
  5193. (append (and (facep face-name) (list face-name))
  5194. '(org-block))))))) ; end of source block
  5195. ((not org-fontify-quote-and-verse-blocks))
  5196. ((string= block-type "quote")
  5197. (add-face-text-property
  5198. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5199. ((string= block-type "verse")
  5200. (add-face-text-property
  5201. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5202. (add-text-properties beg beg1 '(face org-block-begin-line))
  5203. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5204. '(face org-block-end-line))
  5205. t))
  5206. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5207. (org-remove-flyspell-overlays-in
  5208. (match-beginning 0)
  5209. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5210. (add-text-properties
  5211. beg (match-end 3)
  5212. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5213. '(font-lock-fontified t invisible t)
  5214. '(font-lock-fontified t face org-document-info-keyword)))
  5215. (add-text-properties
  5216. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5217. (if (string-equal dc1 "+title:")
  5218. '(font-lock-fontified t face org-document-title)
  5219. '(font-lock-fontified t face org-document-info))))
  5220. ((string-prefix-p "+caption" dc1)
  5221. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5222. (remove-text-properties (match-beginning 0) (match-end 0)
  5223. '(display t invisible t intangible t))
  5224. ;; Handle short captions.
  5225. (save-excursion
  5226. (beginning-of-line)
  5227. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5228. (add-text-properties (line-beginning-position) (match-end 1)
  5229. '(font-lock-fontified t face org-meta-line))
  5230. (add-text-properties (match-end 0) (line-end-position)
  5231. '(font-lock-fontified t face org-block))
  5232. t)
  5233. ((member dc3 '(" " ""))
  5234. (org-remove-flyspell-overlays-in beg (match-end 0))
  5235. (add-text-properties
  5236. beg (match-end 0)
  5237. '(font-lock-fontified t face font-lock-comment-face)))
  5238. (t ;; just any other in-buffer setting, but not indented
  5239. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5240. (remove-text-properties (match-beginning 0) (match-end 0)
  5241. '(display t invisible t intangible t))
  5242. (add-text-properties beg (match-end 0)
  5243. '(font-lock-fontified t face org-meta-line))
  5244. t))))))
  5245. (defun org-fontify-drawers (limit)
  5246. "Fontify drawers."
  5247. (when (re-search-forward org-drawer-regexp limit t)
  5248. (add-text-properties
  5249. (match-beginning 0) (match-end 0)
  5250. '(font-lock-fontified t face org-special-keyword))
  5251. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5252. t))
  5253. (defun org-fontify-macros (limit)
  5254. "Fontify macros."
  5255. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5256. (add-text-properties
  5257. (match-beginning 0) (match-end 0)
  5258. '(font-lock-fontified t face org-macro))
  5259. (when org-hide-macro-markers
  5260. (add-text-properties (match-end 2) (match-beginning 2)
  5261. '(invisible t))
  5262. (add-text-properties (match-beginning 1) (match-end 1)
  5263. '(invisible t)))
  5264. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5265. t))
  5266. (defun org-activate-angle-links (limit)
  5267. "Add text properties for angle links."
  5268. (when (and (re-search-forward org-angle-link-re limit t)
  5269. (not (org-in-src-block-p)))
  5270. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5271. (add-text-properties (match-beginning 0) (match-end 0)
  5272. (list 'mouse-face 'highlight
  5273. 'keymap org-mouse-map
  5274. 'font-lock-multiline t))
  5275. (org-rear-nonsticky-at (match-end 0))
  5276. t))
  5277. (defun org-activate-footnote-links (limit)
  5278. "Add text properties for footnotes."
  5279. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5280. (when fn
  5281. (let* ((beg (nth 1 fn))
  5282. (end (nth 2 fn))
  5283. (label (car fn))
  5284. (referencep (/= (line-beginning-position) beg)))
  5285. (when (and referencep (nth 3 fn))
  5286. (save-excursion
  5287. (goto-char beg)
  5288. (search-forward (or label "fn:"))
  5289. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5290. (add-text-properties beg end
  5291. (list 'mouse-face 'highlight
  5292. 'keymap org-mouse-map
  5293. 'help-echo
  5294. (if referencep "Footnote reference"
  5295. "Footnote definition")
  5296. 'font-lock-fontified t
  5297. 'font-lock-multiline t
  5298. 'face 'org-footnote))))))
  5299. (defun org-activate-bracket-links (limit)
  5300. "Add text properties for bracketed links."
  5301. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5302. (not (org-in-src-block-p)))
  5303. (let* ((hl (save-match-data
  5304. (org-link-expand-abbrev (match-string-no-properties 1))))
  5305. (type (save-match-data
  5306. (and (string-match org-plain-link-re hl)
  5307. (match-string-no-properties 1 hl))))
  5308. (path (save-match-data
  5309. (and (string-match org-plain-link-re hl)
  5310. (match-string-no-properties 2 hl))))
  5311. (link-start (match-beginning 0))
  5312. (link-end (match-end 0))
  5313. (bracketp t)
  5314. (help-echo (org-link-get-parameter type :help-echo))
  5315. (help (cond
  5316. ((stringp help-echo)
  5317. help-echo)
  5318. ((functionp help-echo)
  5319. help-echo)
  5320. (t
  5321. (concat "LINK: "
  5322. (save-match-data
  5323. (org-link-unescape hl))))))
  5324. (link-face (org-link-get-parameter type :face))
  5325. (face (cond
  5326. ;; A function that returns a face
  5327. ((functionp link-face)
  5328. (funcall link-face path))
  5329. ;; a face
  5330. ((facep link-face)
  5331. link-face)
  5332. ;; An anonymous face
  5333. ((consp link-face)
  5334. link-face)
  5335. ;; default
  5336. (t
  5337. 'org-link)))
  5338. (keymap (or (org-link-get-parameter type :keymap)
  5339. org-mouse-map))
  5340. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5341. 'highlight))
  5342. (htmlize (org-link-get-parameter type :htmlize-link))
  5343. (htmlize-link (cond
  5344. ((functionp htmlize)
  5345. (funcall htmlize))
  5346. (t
  5347. `(:uri ,(format "%s:%s" type path)))))
  5348. (activate-func (org-link-get-parameter type :activate-func))
  5349. ;; invisible part
  5350. (ip (list 'invisible (or
  5351. (org-link-get-parameter type :display)
  5352. 'org-link)
  5353. 'face face
  5354. 'keymap keymap
  5355. 'mouse-face mouse-face
  5356. 'font-lock-multiline t
  5357. 'help-echo help
  5358. 'htmlize-link htmlize-link))
  5359. ;; visible part
  5360. (vp (list 'keymap keymap
  5361. 'face face
  5362. 'mouse-face mouse-face
  5363. 'font-lock-multiline t
  5364. 'help-echo help
  5365. 'htmlize-link htmlize-link)))
  5366. ;; We need to remove the invisible property here. Table narrowing
  5367. ;; may have made some of this invisible.
  5368. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5369. (remove-text-properties (match-beginning 0) (match-end 0)
  5370. '(invisible nil))
  5371. (if (match-end 3)
  5372. (progn
  5373. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5374. (org-rear-nonsticky-at (match-beginning 3))
  5375. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5376. (org-rear-nonsticky-at (match-end 3))
  5377. (add-text-properties (match-end 3) (match-end 0) ip)
  5378. (org-rear-nonsticky-at (match-end 0)))
  5379. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5380. (org-rear-nonsticky-at (match-beginning 1))
  5381. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5382. (org-rear-nonsticky-at (match-end 1))
  5383. (add-text-properties (match-end 1) (match-end 0) ip)
  5384. (org-rear-nonsticky-at (match-end 0)))
  5385. (when activate-func
  5386. (funcall activate-func link-start link-end path bracketp))
  5387. t)))
  5388. (defun org-activate-dates (limit)
  5389. "Add text properties for dates."
  5390. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5391. (not (equal (char-before (match-beginning 0)) 91)))
  5392. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5393. (add-text-properties (match-beginning 0) (match-end 0)
  5394. (list 'mouse-face 'highlight
  5395. 'keymap org-mouse-map))
  5396. (org-rear-nonsticky-at (match-end 0))
  5397. (when org-display-custom-times
  5398. (if (match-end 3)
  5399. (org-display-custom-time (match-beginning 3) (match-end 3))
  5400. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5401. t))
  5402. (defvar-local org-target-link-regexp nil
  5403. "Regular expression matching radio targets in plain text.")
  5404. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5405. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5406. border border border))
  5407. "Regular expression matching a link target.")
  5408. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5409. "Regular expression matching a radio target.")
  5410. (defconst org-any-target-regexp
  5411. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5412. "Regular expression matching any target.")
  5413. (defun org-activate-target-links (limit)
  5414. "Add text properties for target matches."
  5415. (when org-target-link-regexp
  5416. (let ((case-fold-search t))
  5417. (when (re-search-forward org-target-link-regexp limit t)
  5418. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5419. (add-text-properties (match-beginning 1) (match-end 1)
  5420. (list 'mouse-face 'highlight
  5421. 'keymap org-mouse-map
  5422. 'help-echo "Radio target link"
  5423. 'org-linked-text t))
  5424. (org-rear-nonsticky-at (match-end 1))
  5425. t))))
  5426. (defun org-update-radio-target-regexp ()
  5427. "Find all radio targets in this file and update the regular expression.
  5428. Also refresh fontification if needed."
  5429. (interactive)
  5430. (let ((old-regexp org-target-link-regexp)
  5431. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5432. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5433. (targets
  5434. (org-with-wide-buffer
  5435. (goto-char (point-min))
  5436. (let (rtn)
  5437. (while (re-search-forward org-radio-target-regexp nil t)
  5438. ;; Make sure point is really within the object.
  5439. (backward-char)
  5440. (let ((obj (org-element-context)))
  5441. (when (eq (org-element-type obj) 'radio-target)
  5442. (cl-pushnew (org-element-property :value obj) rtn
  5443. :test #'equal))))
  5444. rtn))))
  5445. (setq org-target-link-regexp
  5446. (and targets
  5447. (concat before-re
  5448. (mapconcat
  5449. (lambda (x)
  5450. (replace-regexp-in-string
  5451. " +" "\\s-+" (regexp-quote x) t t))
  5452. targets
  5453. "\\|")
  5454. after-re)))
  5455. (unless (equal old-regexp org-target-link-regexp)
  5456. ;; Clean-up cache.
  5457. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5458. ((not org-target-link-regexp) old-regexp)
  5459. (t
  5460. (concat before-re
  5461. (mapconcat
  5462. (lambda (re)
  5463. (substring re (length before-re)
  5464. (- (length after-re))))
  5465. (list old-regexp org-target-link-regexp)
  5466. "\\|")
  5467. after-re)))))
  5468. (org-with-wide-buffer
  5469. (goto-char (point-min))
  5470. (while (re-search-forward regexp nil t)
  5471. (org-element-cache-refresh (match-beginning 1)))))
  5472. ;; Re fontify buffer.
  5473. (when (memq 'radio org-highlight-links)
  5474. (org-restart-font-lock)))))
  5475. (defun org-hide-wide-columns (limit)
  5476. (let (s e)
  5477. (setq s (text-property-any (point) (or limit (point-max))
  5478. 'org-cwidth t))
  5479. (when s
  5480. (setq e (next-single-property-change s 'org-cwidth))
  5481. (add-text-properties s e '(invisible org-cwidth))
  5482. (goto-char e)
  5483. t)))
  5484. (defvar org-latex-and-related-regexp nil
  5485. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5486. (defun org-compute-latex-and-related-regexp ()
  5487. "Compute regular expression for LaTeX, entities and sub/superscript.
  5488. Result depends on variable `org-highlight-latex-and-related'."
  5489. (setq-local
  5490. org-latex-and-related-regexp
  5491. (let* ((re-sub
  5492. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5493. ((eq org-use-sub-superscripts '{})
  5494. (list org-match-substring-with-braces-regexp))
  5495. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5496. (re-latex
  5497. (when (memq 'latex org-highlight-latex-and-related)
  5498. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5499. (delq nil
  5500. (mapcar (lambda (x)
  5501. (and (member (car x) matchers) (nth 1 x)))
  5502. org-latex-regexps)))))
  5503. (re-entities
  5504. (when (memq 'entities org-highlight-latex-and-related)
  5505. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5506. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5507. (defun org-do-latex-and-related (limit)
  5508. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5509. LIMIT bounds the search for syntax to highlight. Stop at first
  5510. highlighted object, if any. Return t if some highlighting was
  5511. done, nil otherwise."
  5512. (when (org-string-nw-p org-latex-and-related-regexp)
  5513. (catch 'found
  5514. (while (re-search-forward org-latex-and-related-regexp limit t)
  5515. (unless
  5516. (cl-some
  5517. (lambda (f)
  5518. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5519. (save-excursion
  5520. (goto-char (1+ (match-beginning 0)))
  5521. (face-at-point nil t)))
  5522. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5523. '(?_ ?^))
  5524. 1
  5525. 0)))
  5526. (font-lock-prepend-text-property
  5527. (+ offset (match-beginning 0)) (match-end 0)
  5528. 'face 'org-latex-and-related)
  5529. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5530. '(font-lock-multiline t)))
  5531. (throw 'found t)))
  5532. nil)))
  5533. (defun org-restart-font-lock ()
  5534. "Restart `font-lock-mode', to force refontification."
  5535. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5536. (font-lock-mode -1)
  5537. (font-lock-mode 1)))
  5538. (defun org-activate-tags (limit)
  5539. (when (re-search-forward
  5540. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5541. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5542. (add-text-properties (match-beginning 1) (match-end 1)
  5543. (list 'mouse-face 'highlight
  5544. 'keymap org-mouse-map))
  5545. (org-rear-nonsticky-at (match-end 1))
  5546. t))
  5547. (defun org-outline-level ()
  5548. "Compute the outline level of the heading at point.
  5549. If this is called at a normal headline, the level is the number
  5550. of stars. Use `org-reduced-level' to remove the effect of
  5551. `org-odd-levels'. Unlike to `org-current-level', this function
  5552. takes into consideration inlinetasks."
  5553. (org-with-wide-buffer
  5554. (end-of-line)
  5555. (if (re-search-backward org-outline-regexp-bol nil t)
  5556. (1- (- (match-end 0) (match-beginning 0)))
  5557. 0)))
  5558. (defvar org-font-lock-keywords nil)
  5559. (defsubst org-re-property (property &optional literal allow-null value)
  5560. "Return a regexp matching a PROPERTY line.
  5561. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5562. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5563. non-nil, match properties even without a value.
  5564. Match group 3 is set to the value when it exists. If there is no
  5565. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5566. With optional argument VALUE, match only property lines with
  5567. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5568. unless LITERAL is non-nil."
  5569. (concat
  5570. "^\\(?4:[ \t]*\\)"
  5571. (format "\\(?1::\\(?2:%s\\):\\)"
  5572. (if literal property (regexp-quote property)))
  5573. (cond (value
  5574. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5575. (if literal value (regexp-quote value))))
  5576. (allow-null
  5577. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5578. (t
  5579. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5580. (defconst org-property-re
  5581. (org-re-property "\\S-+" 'literal t)
  5582. "Regular expression matching a property line.
  5583. There are four matching groups:
  5584. 1: :PROPKEY: including the leading and trailing colon,
  5585. 2: PROPKEY without the leading and trailing colon,
  5586. 3: PROPVAL without leading or trailing spaces,
  5587. 4: the indentation of the current line,
  5588. 5: trailing whitespace.")
  5589. (defvar org-font-lock-hook nil
  5590. "Functions to be called for special font lock stuff.")
  5591. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5592. (defvar org-font-lock-set-keywords-hook nil
  5593. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5594. This is called after `org-font-lock-extra-keywords' is defined, but before
  5595. it is installed to be used by font lock. This can be useful if something
  5596. needs to be inserted at a specific position in the font-lock sequence.")
  5597. (defun org-font-lock-hook (limit)
  5598. "Run `org-font-lock-hook' within LIMIT."
  5599. (run-hook-with-args 'org-font-lock-hook limit))
  5600. (defun org-set-font-lock-defaults ()
  5601. "Set font lock defaults for the current buffer."
  5602. (let* ((em org-fontify-emphasized-text)
  5603. (lk org-highlight-links)
  5604. (org-font-lock-extra-keywords
  5605. (list
  5606. ;; Call the hook
  5607. '(org-font-lock-hook)
  5608. ;; Headlines
  5609. `(,(if org-fontify-whole-heading-line
  5610. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5611. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5612. (1 (org-get-level-face 1))
  5613. (2 (org-get-level-face 2))
  5614. (3 (org-get-level-face 3)))
  5615. ;; Table lines
  5616. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5617. (1 'org-table t))
  5618. ;; Table internals
  5619. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5620. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5621. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5622. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5623. ;; Drawers
  5624. '(org-fontify-drawers)
  5625. ;; Properties
  5626. (list org-property-re
  5627. '(1 'org-special-keyword t)
  5628. '(3 'org-property-value t))
  5629. ;; Links
  5630. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5631. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5632. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5633. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5634. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5635. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5636. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5637. ;; Targets.
  5638. (list org-any-target-regexp '(0 'org-target t))
  5639. ;; Diary sexps.
  5640. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5641. ;; Macro
  5642. '(org-fontify-macros)
  5643. '(org-hide-wide-columns (0 nil append))
  5644. ;; TODO keyword
  5645. (list (format org-heading-keyword-regexp-format
  5646. org-todo-regexp)
  5647. '(2 (org-get-todo-face 2) t))
  5648. ;; DONE
  5649. (if org-fontify-done-headline
  5650. (list (format org-heading-keyword-regexp-format
  5651. (concat
  5652. "\\(?:"
  5653. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5654. "\\)"))
  5655. '(2 'org-headline-done t))
  5656. nil)
  5657. ;; Priorities
  5658. '(org-font-lock-add-priority-faces)
  5659. ;; Tags
  5660. '(org-font-lock-add-tag-faces)
  5661. ;; Tags groups
  5662. (when (and org-group-tags org-tag-groups-alist)
  5663. (list (concat org-outline-regexp-bol ".+\\(:"
  5664. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5665. ":\\).*$")
  5666. '(1 'org-tag-group prepend)))
  5667. ;; Special keywords
  5668. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5669. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5670. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5671. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5672. ;; Emphasis
  5673. (when em '(org-do-emphasis-faces))
  5674. ;; Checkboxes
  5675. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5676. 1 'org-checkbox prepend)
  5677. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5678. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5679. (0 (org-get-checkbox-statistics-face) t)))
  5680. ;; Description list items
  5681. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5682. 1 'org-list-dt prepend)
  5683. ;; ARCHIVEd headings
  5684. (list (concat
  5685. org-outline-regexp-bol
  5686. "\\(.*:" org-archive-tag ":.*\\)")
  5687. '(1 'org-archived prepend))
  5688. ;; Specials
  5689. '(org-do-latex-and-related)
  5690. '(org-fontify-entities)
  5691. '(org-raise-scripts)
  5692. ;; Code
  5693. '(org-activate-code (1 'org-code t))
  5694. ;; COMMENT
  5695. (list (format
  5696. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5697. org-todo-regexp
  5698. org-comment-string)
  5699. '(9 'org-special-keyword t))
  5700. ;; Blocks and meta lines
  5701. '(org-fontify-meta-lines-and-blocks))))
  5702. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5703. (run-hooks 'org-font-lock-set-keywords-hook)
  5704. ;; Now set the full font-lock-keywords
  5705. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5706. (setq-local font-lock-defaults
  5707. '(org-font-lock-keywords t nil nil backward-paragraph))
  5708. (kill-local-variable 'font-lock-keywords)
  5709. nil))
  5710. (defun org-toggle-pretty-entities ()
  5711. "Toggle the composition display of entities as UTF8 characters."
  5712. (interactive)
  5713. (setq-local org-pretty-entities (not org-pretty-entities))
  5714. (org-restart-font-lock)
  5715. (if org-pretty-entities
  5716. (message "Entities are now displayed as UTF8 characters")
  5717. (save-restriction
  5718. (widen)
  5719. (decompose-region (point-min) (point-max))
  5720. (message "Entities are now displayed as plain text"))))
  5721. (defvar-local org-custom-properties-overlays nil
  5722. "List of overlays used for custom properties.")
  5723. (defun org-toggle-custom-properties-visibility ()
  5724. "Display or hide properties in `org-custom-properties'."
  5725. (interactive)
  5726. (if org-custom-properties-overlays
  5727. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5728. (setq org-custom-properties-overlays nil))
  5729. (when org-custom-properties
  5730. (org-with-wide-buffer
  5731. (goto-char (point-min))
  5732. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5733. (while (re-search-forward regexp nil t)
  5734. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5735. (when (and end (< (point) end))
  5736. ;; Hide first custom property in current drawer.
  5737. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5738. (overlay-put o 'invisible t)
  5739. (overlay-put o 'org-custom-property t)
  5740. (push o org-custom-properties-overlays))
  5741. ;; Hide additional custom properties in the same drawer.
  5742. (while (re-search-forward regexp end t)
  5743. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5744. (overlay-put o 'invisible t)
  5745. (overlay-put o 'org-custom-property t)
  5746. (push o org-custom-properties-overlays)))))
  5747. ;; Each entry is limited to a single property drawer.
  5748. (outline-next-heading)))))))
  5749. (defun org-fontify-entities (limit)
  5750. "Find an entity to fontify."
  5751. (let (ee)
  5752. (when org-pretty-entities
  5753. (catch 'match
  5754. ;; "\_ "-family is left out on purpose. Only the first one,
  5755. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5756. ;; confusing when adding a second white space character.
  5757. (while (re-search-forward
  5758. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5759. limit t)
  5760. (when (and (not (org-at-comment-p))
  5761. (setq ee (org-entity-get (match-string 1)))
  5762. (= (length (nth 6 ee)) 1))
  5763. (let* ((end (if (equal (match-string 2) "{}")
  5764. (match-end 2)
  5765. (match-end 1))))
  5766. (add-text-properties
  5767. (match-beginning 0) end
  5768. (list 'font-lock-fontified t))
  5769. (compose-region (match-beginning 0) end
  5770. (nth 6 ee) nil)
  5771. (backward-char 1)
  5772. (throw 'match t))))
  5773. nil))))
  5774. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5775. "Fontify string S like in Org mode."
  5776. (with-temp-buffer
  5777. (insert s)
  5778. (let ((org-odd-levels-only odd-levels))
  5779. (org-mode)
  5780. (org-font-lock-ensure)
  5781. (buffer-string))))
  5782. (defvar org-m nil)
  5783. (defvar org-l nil)
  5784. (defvar org-f nil)
  5785. (defun org-get-level-face (n)
  5786. "Get the right face for match N in font-lock matching of headlines."
  5787. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5788. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5789. (if org-cycle-level-faces
  5790. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5791. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5792. (cond
  5793. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5794. ((eq n 2) org-f)
  5795. (t (unless org-level-color-stars-only org-f))))
  5796. (defun org-face-from-face-or-color (context inherit face-or-color)
  5797. "Create a face list that inherits INHERIT, but sets the foreground color.
  5798. When FACE-OR-COLOR is not a string, just return it."
  5799. (if (stringp face-or-color)
  5800. (list :inherit inherit
  5801. (cdr (assoc context org-faces-easy-properties))
  5802. face-or-color)
  5803. face-or-color))
  5804. (defun org-get-todo-face (kwd)
  5805. "Get the right face for a TODO keyword KWD.
  5806. If KWD is a number, get the corresponding match group."
  5807. (when (numberp kwd) (setq kwd (match-string kwd)))
  5808. (or (org-face-from-face-or-color
  5809. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5810. (and (member kwd org-done-keywords) 'org-done)
  5811. 'org-todo))
  5812. (defun org-get-priority-face (priority)
  5813. "Get the right face for PRIORITY.
  5814. PRIORITY is a character."
  5815. (or (org-face-from-face-or-color
  5816. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5817. 'org-priority))
  5818. (defun org-get-tag-face (tag)
  5819. "Get the right face for TAG.
  5820. If TAG is a number, get the corresponding match group."
  5821. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5822. (or (org-face-from-face-or-color
  5823. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5824. 'org-tag)))
  5825. (defun org-font-lock-add-priority-faces (limit)
  5826. "Add the special priority faces."
  5827. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5828. (add-text-properties
  5829. (match-beginning 1) (match-end 1)
  5830. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5831. 'font-lock-fontified t))))
  5832. (defun org-font-lock-add-tag-faces (limit)
  5833. "Add the special tag faces."
  5834. (when (and org-tag-faces org-tags-special-faces-re)
  5835. (while (re-search-forward org-tags-special-faces-re limit t)
  5836. (add-text-properties (match-beginning 1) (match-end 1)
  5837. (list 'face (org-get-tag-face 1)
  5838. 'font-lock-fontified t))
  5839. (backward-char 1))))
  5840. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5841. "Remove fontification and activation overlays from links."
  5842. (font-lock-default-unfontify-region beg end)
  5843. (let* ((buffer-undo-list t)
  5844. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5845. (inhibit-modification-hooks t)
  5846. deactivate-mark buffer-file-name buffer-file-truename)
  5847. (decompose-region beg end)
  5848. (remove-text-properties beg end
  5849. '(mouse-face t keymap t org-linked-text t
  5850. invisible t intangible t
  5851. org-emphasis t))
  5852. (org-remove-font-lock-display-properties beg end)))
  5853. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5854. ((raise 0.3) (height 0.7))
  5855. ((raise -0.5))
  5856. ((raise 0.5)))
  5857. "Display properties for showing superscripts and subscripts.")
  5858. (defun org-remove-font-lock-display-properties (beg end)
  5859. "Remove specific display properties that have been added by font lock.
  5860. The will remove the raise properties that are used to show superscripts
  5861. and subscripts."
  5862. (let (next prop)
  5863. (while (< beg end)
  5864. (setq next (next-single-property-change beg 'display nil end)
  5865. prop (get-text-property beg 'display))
  5866. (when (member prop org-script-display)
  5867. (put-text-property beg next 'display nil))
  5868. (setq beg next))))
  5869. (defun org-raise-scripts (limit)
  5870. "Add raise properties to sub/superscripts."
  5871. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5872. (re-search-forward
  5873. (if (eq org-use-sub-superscripts t)
  5874. org-match-substring-regexp
  5875. org-match-substring-with-braces-regexp)
  5876. limit t))
  5877. (let* ((pos (point)) table-p comment-p
  5878. (mpos (match-beginning 3))
  5879. (emph-p (get-text-property mpos 'org-emphasis))
  5880. (link-p (get-text-property mpos 'mouse-face))
  5881. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5882. (goto-char (point-at-bol))
  5883. (setq table-p (looking-at-p org-table-dataline-regexp)
  5884. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5885. (goto-char pos)
  5886. ;; Handle a_b^c
  5887. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5888. (unless (or comment-p emph-p link-p keyw-p)
  5889. (put-text-property (match-beginning 3) (match-end 0)
  5890. 'display
  5891. (if (equal (char-after (match-beginning 2)) ?^)
  5892. (nth (if table-p 3 1) org-script-display)
  5893. (nth (if table-p 2 0) org-script-display)))
  5894. (add-text-properties (match-beginning 2) (match-end 2)
  5895. (list 'invisible t
  5896. 'org-dwidth t 'org-dwidth-n 1))
  5897. (if (and (eq (char-after (match-beginning 3)) ?{)
  5898. (eq (char-before (match-end 3)) ?}))
  5899. (progn
  5900. (add-text-properties
  5901. (match-beginning 3) (1+ (match-beginning 3))
  5902. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  5903. (add-text-properties
  5904. (1- (match-end 3)) (match-end 3)
  5905. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  5906. t)))
  5907. ;;;; Visibility cycling, including org-goto and indirect buffer
  5908. ;;; Cycling
  5909. (defvar-local org-cycle-global-status nil)
  5910. (put 'org-cycle-global-status 'org-state t)
  5911. (defvar-local org-cycle-subtree-status nil)
  5912. (put 'org-cycle-subtree-status 'org-state t)
  5913. (defvar org-inlinetask-min-level)
  5914. (defun org-unlogged-message (&rest args)
  5915. "Display a message, but avoid logging it in the *Messages* buffer."
  5916. (let ((message-log-max nil))
  5917. (apply 'message args)))
  5918. ;;;###autoload
  5919. (defun org-cycle (&optional arg)
  5920. "TAB-action and visibility cycling for Org mode.
  5921. This is the command invoked in Org mode by the `TAB' key. Its main
  5922. purpose is outline visibility cycling, but it also invokes other actions
  5923. in special contexts.
  5924. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5925. the entire
  5926. buffer through 3 states (global cycling)
  5927. 1. OVERVIEW: Show only top-level headlines.
  5928. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5929. 3. SHOW ALL: Show everything.
  5930. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5931. switch to the startup visibility,
  5932. determined by the variable `org-startup-folded', and by any VISIBILITY
  5933. properties in the buffer.
  5934. With a `\\[universal-argument] \\[universal-argument] \
  5935. \\[universal-argument]' prefix argument, show the entire buffer, including
  5936. any drawers.
  5937. When inside a table, re-align the table and move to the next field.
  5938. When point is at the beginning of a headline, rotate the subtree started
  5939. by this line through 3 different states (local cycling)
  5940. 1. FOLDED: Only the main headline is shown.
  5941. 2. CHILDREN: The main headline and the direct children are shown.
  5942. From this state, you can move to one of the children
  5943. and zoom in further.
  5944. 3. SUBTREE: Show the entire subtree, including body text.
  5945. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5946. When point is at the beginning of an empty headline and the variable
  5947. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5948. of the headline by demoting and promoting it to likely levels. This
  5949. speeds up creation document structure by pressing `TAB' once or several
  5950. times right after creating a new headline.
  5951. When there is a numeric prefix, go up to a heading with level ARG, do
  5952. a `show-subtree' and return to the previous cursor position. If ARG
  5953. is negative, go up that many levels.
  5954. When point is not at the beginning of a headline, execute the global
  5955. binding for `TAB', which is re-indenting the line. See the option
  5956. `org-cycle-emulate-tab' for details.
  5957. As a special case, if point is at the beginning of the buffer and there is
  5958. no headline in line 1, this function will act as if called with prefix arg
  5959. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5960. prefix arg, but only
  5961. if the variable `org-cycle-global-at-bob' is t."
  5962. (interactive "P")
  5963. (org-load-modules-maybe)
  5964. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5965. (and org-cycle-level-after-item/entry-creation
  5966. (or (org-cycle-level)
  5967. (org-cycle-item-indentation))))
  5968. (let* ((limit-level
  5969. (or org-cycle-max-level
  5970. (and (boundp 'org-inlinetask-min-level)
  5971. org-inlinetask-min-level
  5972. (1- org-inlinetask-min-level))))
  5973. (nstars (and limit-level
  5974. (if org-odd-levels-only
  5975. (and limit-level (1- (* limit-level 2)))
  5976. limit-level)))
  5977. (org-outline-regexp
  5978. (if (not (derived-mode-p 'org-mode))
  5979. outline-regexp
  5980. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5981. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5982. (not (looking-at org-outline-regexp))))
  5983. (org-cycle-hook
  5984. (if bob-special
  5985. (delq 'org-optimize-window-after-visibility-change
  5986. (copy-sequence org-cycle-hook))
  5987. org-cycle-hook))
  5988. (pos (point)))
  5989. (cond
  5990. ((equal arg '(16))
  5991. (setq last-command 'dummy)
  5992. (org-set-startup-visibility)
  5993. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5994. ((equal arg '(64))
  5995. (outline-show-all)
  5996. (org-unlogged-message "Entire buffer visible, including drawers"))
  5997. ((equal arg '(4)) (org-cycle-internal-global))
  5998. ;; Try hiding block at point.
  5999. ((org-hide-block-toggle-maybe))
  6000. ;; Try cdlatex TAB completion
  6001. ((org-try-cdlatex-tab))
  6002. ;; Table: enter it or move to the next field.
  6003. ((org-at-table-p 'any)
  6004. (if (org-at-table.el-p)
  6005. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6006. Use `\\[org-edit-special]' to edit table.el tables"))
  6007. (if arg (org-table-edit-field t)
  6008. (org-table-justify-field-maybe)
  6009. (call-interactively 'org-table-next-field))))
  6010. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6011. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6012. (bob-special (org-cycle-internal-global))
  6013. ;; Drawers: delegate to `org-flag-drawer'.
  6014. ((save-excursion
  6015. (beginning-of-line 1)
  6016. (looking-at org-drawer-regexp))
  6017. (org-flag-drawer ; toggle block visibility
  6018. (not (get-char-property (match-end 0) 'invisible))))
  6019. ;; Show-subtree, ARG levels up from here.
  6020. ((integerp arg)
  6021. (save-excursion
  6022. (org-back-to-heading)
  6023. (outline-up-heading (if (< arg 0) (- arg)
  6024. (- (funcall outline-level) arg)))
  6025. (org-show-subtree)))
  6026. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6027. ((and (featurep 'org-inlinetask)
  6028. (org-inlinetask-at-task-p)
  6029. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6030. (org-inlinetask-toggle-visibility))
  6031. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6032. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6033. (save-excursion (move-beginning-of-line 1)
  6034. (looking-at org-outline-regexp)))
  6035. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6036. (org-cycle-internal-local))
  6037. ;; From there: TAB emulation and template completion.
  6038. (buffer-read-only (org-back-to-heading))
  6039. ((run-hook-with-args-until-success
  6040. 'org-tab-after-check-for-cycling-hook))
  6041. ((org-try-structure-completion))
  6042. ((run-hook-with-args-until-success
  6043. 'org-tab-before-tab-emulation-hook))
  6044. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6045. (or (not (bolp))
  6046. (not (looking-at org-outline-regexp))))
  6047. (call-interactively (global-key-binding "\t")))
  6048. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6049. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6050. (or (and (eq org-cycle-emulate-tab 'white)
  6051. (= (match-end 0) (point-at-eol)))
  6052. (and (eq org-cycle-emulate-tab 'whitestart)
  6053. (>= (match-end 0) pos))))
  6054. t
  6055. (eq org-cycle-emulate-tab t))
  6056. (call-interactively (global-key-binding "\t")))
  6057. (t (save-excursion
  6058. (org-back-to-heading)
  6059. (org-cycle)))))))
  6060. (defun org-cycle-internal-global ()
  6061. "Do the global cycling action."
  6062. ;; Hack to avoid display of messages for .org attachments in Gnus
  6063. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6064. (cond
  6065. ((and (eq last-command this-command)
  6066. (eq org-cycle-global-status 'overview))
  6067. ;; We just created the overview - now do table of contents
  6068. ;; This can be slow in very large buffers, so indicate action
  6069. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6070. (unless ga (org-unlogged-message "CONTENTS..."))
  6071. (org-content)
  6072. (unless ga (org-unlogged-message "CONTENTS...done"))
  6073. (setq org-cycle-global-status 'contents)
  6074. (run-hook-with-args 'org-cycle-hook 'contents))
  6075. ((and (eq last-command this-command)
  6076. (eq org-cycle-global-status 'contents))
  6077. ;; We just showed the table of contents - now show everything
  6078. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6079. (outline-show-all)
  6080. (unless ga (org-unlogged-message "SHOW ALL"))
  6081. (setq org-cycle-global-status 'all)
  6082. (run-hook-with-args 'org-cycle-hook 'all))
  6083. (t
  6084. ;; Default action: go to overview
  6085. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6086. (org-overview)
  6087. (unless ga (org-unlogged-message "OVERVIEW"))
  6088. (setq org-cycle-global-status 'overview)
  6089. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6090. (defvar org-called-with-limited-levels nil
  6091. "Non-nil when `org-with-limited-levels' is currently active.")
  6092. (defun org-cycle-internal-local ()
  6093. "Do the local cycling action."
  6094. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6095. ;; First, determine end of headline (EOH), end of subtree or item
  6096. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6097. (save-excursion
  6098. (if (org-at-item-p)
  6099. (progn
  6100. (beginning-of-line)
  6101. (setq struct (org-list-struct))
  6102. (setq eoh (point-at-eol))
  6103. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6104. (setq has-children (org-list-has-child-p (point) struct)))
  6105. (org-back-to-heading)
  6106. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6107. (setq eos (save-excursion (org-end-of-subtree t t)
  6108. (when (bolp) (backward-char)) (point)))
  6109. (setq has-children
  6110. (or (save-excursion
  6111. (let ((level (funcall outline-level)))
  6112. (outline-next-heading)
  6113. (and (org-at-heading-p t)
  6114. (> (funcall outline-level) level))))
  6115. (save-excursion
  6116. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6117. ;; Determine end invisible part of buffer (EOL)
  6118. (beginning-of-line 2)
  6119. (while (and (not (eobp)) ;This is like `next-line'.
  6120. (get-char-property (1- (point)) 'invisible))
  6121. (goto-char (next-single-char-property-change (point) 'invisible))
  6122. (and (eolp) (beginning-of-line 2)))
  6123. (setq eol (point)))
  6124. ;; Find out what to do next and set `this-command'
  6125. (cond
  6126. ((= eos eoh)
  6127. ;; Nothing is hidden behind this heading
  6128. (unless (org-before-first-heading-p)
  6129. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6130. (org-unlogged-message "EMPTY ENTRY")
  6131. (setq org-cycle-subtree-status nil)
  6132. (save-excursion
  6133. (goto-char eos)
  6134. (outline-next-heading)
  6135. (when (outline-invisible-p) (org-flag-heading nil))))
  6136. ((and (or (>= eol eos)
  6137. (not (string-match "\\S-" (buffer-substring eol eos))))
  6138. (or has-children
  6139. (not (setq children-skipped
  6140. org-cycle-skip-children-state-if-no-children))))
  6141. ;; Entire subtree is hidden in one line: children view
  6142. (unless (org-before-first-heading-p)
  6143. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6144. (if (org-at-item-p)
  6145. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6146. (org-show-entry)
  6147. (org-with-limited-levels (org-show-children))
  6148. ;; FIXME: This slows down the func way too much.
  6149. ;; How keep drawers hidden in subtree anyway?
  6150. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6151. ;; (org-cycle-hide-drawers 'subtree))
  6152. ;; Fold every list in subtree to top-level items.
  6153. (when (eq org-cycle-include-plain-lists 'integrate)
  6154. (save-excursion
  6155. (org-back-to-heading)
  6156. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6157. (beginning-of-line 1)
  6158. (let* ((struct (org-list-struct))
  6159. (prevs (org-list-prevs-alist struct))
  6160. (end (org-list-get-bottom-point struct)))
  6161. (dolist (e (org-list-get-all-items (point) struct prevs))
  6162. (org-list-set-item-visibility e struct 'folded))
  6163. (goto-char (if (< end eos) end eos)))))))
  6164. (org-unlogged-message "CHILDREN")
  6165. (save-excursion
  6166. (goto-char eos)
  6167. (outline-next-heading)
  6168. (when (outline-invisible-p) (org-flag-heading nil)))
  6169. (setq org-cycle-subtree-status 'children)
  6170. (unless (org-before-first-heading-p)
  6171. (run-hook-with-args 'org-cycle-hook 'children)))
  6172. ((or children-skipped
  6173. (and (eq last-command this-command)
  6174. (eq org-cycle-subtree-status 'children)))
  6175. ;; We just showed the children, or no children are there,
  6176. ;; now show everything.
  6177. (unless (org-before-first-heading-p)
  6178. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6179. (outline-flag-region eoh eos nil)
  6180. (org-unlogged-message
  6181. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6182. (setq org-cycle-subtree-status 'subtree)
  6183. (unless (org-before-first-heading-p)
  6184. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6185. (t
  6186. ;; Default action: hide the subtree.
  6187. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6188. (outline-flag-region eoh eos t)
  6189. (org-unlogged-message "FOLDED")
  6190. (setq org-cycle-subtree-status 'folded)
  6191. (unless (org-before-first-heading-p)
  6192. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6193. ;;;###autoload
  6194. (defun org-global-cycle (&optional arg)
  6195. "Cycle the global visibility. For details see `org-cycle'.
  6196. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6197. With a numeric prefix, show all headlines up to that level."
  6198. (interactive "P")
  6199. (let ((org-cycle-include-plain-lists
  6200. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6201. (cond
  6202. ((integerp arg)
  6203. (outline-show-all)
  6204. (outline-hide-sublevels arg)
  6205. (setq org-cycle-global-status 'contents))
  6206. ((equal arg '(4))
  6207. (org-set-startup-visibility)
  6208. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6209. (t
  6210. (org-cycle '(4))))))
  6211. (defun org-set-startup-visibility ()
  6212. "Set the visibility required by startup options and properties."
  6213. (cond
  6214. ((eq org-startup-folded t)
  6215. (org-overview))
  6216. ((eq org-startup-folded 'content)
  6217. (org-content))
  6218. ((or (eq org-startup-folded 'showeverything)
  6219. (eq org-startup-folded nil))
  6220. (outline-show-all)))
  6221. (unless (eq org-startup-folded 'showeverything)
  6222. (when org-hide-block-startup (org-hide-block-all))
  6223. (org-set-visibility-according-to-property 'no-cleanup)
  6224. (org-cycle-hide-archived-subtrees 'all)
  6225. (org-cycle-hide-drawers 'all)
  6226. (org-cycle-show-empty-lines t)))
  6227. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6228. "Switch subtree visibilities according to :VISIBILITY: property."
  6229. (interactive)
  6230. (org-with-wide-buffer
  6231. (goto-char (point-min))
  6232. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6233. (if (not (org-at-property-p)) (outline-next-heading)
  6234. (let ((state (match-string 3)))
  6235. (save-excursion
  6236. (org-back-to-heading t)
  6237. (outline-hide-subtree)
  6238. (org-reveal)
  6239. (cond
  6240. ((equal state "folded")
  6241. (outline-hide-subtree))
  6242. ((equal state "children")
  6243. (org-show-hidden-entry)
  6244. (org-show-children))
  6245. ((equal state "content")
  6246. (save-excursion
  6247. (save-restriction
  6248. (org-narrow-to-subtree)
  6249. (org-content))))
  6250. ((member state '("all" "showall"))
  6251. (outline-show-subtree)))))))
  6252. (unless no-cleanup
  6253. (org-cycle-hide-archived-subtrees 'all)
  6254. (org-cycle-hide-drawers 'all)
  6255. (org-cycle-show-empty-lines 'all))))
  6256. ;; This function uses outline-regexp instead of the more fundamental
  6257. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6258. ;; buffers, where outline-regexp is needed.
  6259. (defun org-overview ()
  6260. "Switch to overview mode, showing only top-level headlines.
  6261. This shows all headlines with a level equal or greater than the level
  6262. of the first headline in the buffer. This is important, because if the
  6263. first headline is not level one, then (hide-sublevels 1) gives confusing
  6264. results."
  6265. (interactive)
  6266. (save-excursion
  6267. (let ((level
  6268. (save-excursion
  6269. (goto-char (point-min))
  6270. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6271. (goto-char (match-beginning 0))
  6272. (funcall outline-level)))))
  6273. (and level (outline-hide-sublevels level)))))
  6274. (defun org-content (&optional arg)
  6275. "Show all headlines in the buffer, like a table of contents.
  6276. With numerical argument N, show content up to level N."
  6277. (interactive "P")
  6278. (org-overview)
  6279. (save-excursion
  6280. ;; Visit all headings and show their offspring
  6281. (and (integerp arg) (org-overview))
  6282. (goto-char (point-max))
  6283. (catch 'exit
  6284. (while (and (progn (condition-case nil
  6285. (outline-previous-visible-heading 1)
  6286. (error (goto-char (point-min))))
  6287. t)
  6288. (looking-at org-outline-regexp))
  6289. (if (integerp arg)
  6290. (org-show-children (1- arg))
  6291. (outline-show-branches))
  6292. (when (bobp) (throw 'exit nil))))))
  6293. (defun org-optimize-window-after-visibility-change (state)
  6294. "Adjust the window after a change in outline visibility.
  6295. This function is the default value of the hook `org-cycle-hook'."
  6296. (when (get-buffer-window (current-buffer))
  6297. (cond
  6298. ((eq state 'content) nil)
  6299. ((eq state 'all) nil)
  6300. ((eq state 'folded) nil)
  6301. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6302. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6303. (defun org-remove-empty-overlays-at (pos)
  6304. "Remove outline overlays that do not contain non-white stuff."
  6305. (dolist (o (overlays-at pos))
  6306. (and (eq 'outline (overlay-get o 'invisible))
  6307. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6308. (overlay-end o))))
  6309. (delete-overlay o))))
  6310. (defun org-clean-visibility-after-subtree-move ()
  6311. "Fix visibility issues after moving a subtree."
  6312. ;; First, find a reasonable region to look at:
  6313. ;; Start two siblings above, end three below
  6314. (let* ((beg (save-excursion
  6315. (and (org-get-last-sibling)
  6316. (org-get-last-sibling))
  6317. (point)))
  6318. (end (save-excursion
  6319. (and (org-get-next-sibling)
  6320. (org-get-next-sibling)
  6321. (org-get-next-sibling))
  6322. (if (org-at-heading-p)
  6323. (point-at-eol)
  6324. (point))))
  6325. (level (looking-at "\\*+"))
  6326. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6327. (save-excursion
  6328. (save-restriction
  6329. (narrow-to-region beg end)
  6330. (when re
  6331. ;; Properly fold already folded siblings
  6332. (goto-char (point-min))
  6333. (while (re-search-forward re nil t)
  6334. (when (and (not (outline-invisible-p))
  6335. (save-excursion
  6336. (goto-char (point-at-eol)) (outline-invisible-p)))
  6337. (outline-hide-entry))))
  6338. (org-cycle-show-empty-lines 'overview)
  6339. (org-cycle-hide-drawers 'overview)))))
  6340. (defun org-cycle-show-empty-lines (state)
  6341. "Show empty lines above all visible headlines.
  6342. The region to be covered depends on STATE when called through
  6343. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6344. entire buffer covered. Note that an empty line is only shown if there
  6345. are at least `org-cycle-separator-lines' empty lines before the headline."
  6346. (when (/= org-cycle-separator-lines 0)
  6347. (save-excursion
  6348. (let* ((n (abs org-cycle-separator-lines))
  6349. (re (cond
  6350. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6351. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6352. (t (let ((ns (number-to-string (- n 2))))
  6353. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6354. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6355. beg end)
  6356. (cond
  6357. ((memq state '(overview contents t))
  6358. (setq beg (point-min) end (point-max)))
  6359. ((memq state '(children folded))
  6360. (setq beg (point)
  6361. end (progn (org-end-of-subtree t t)
  6362. (line-beginning-position 2)))))
  6363. (when beg
  6364. (goto-char beg)
  6365. (while (re-search-forward re end t)
  6366. (unless (get-char-property (match-end 1) 'invisible)
  6367. (let ((e (match-end 1))
  6368. (b (if (>= org-cycle-separator-lines 0)
  6369. (match-beginning 1)
  6370. (save-excursion
  6371. (goto-char (match-beginning 0))
  6372. (skip-chars-backward " \t\n")
  6373. (line-end-position)))))
  6374. (outline-flag-region b e nil))))))))
  6375. ;; Never hide empty lines at the end of the file.
  6376. (save-excursion
  6377. (goto-char (point-max))
  6378. (outline-previous-heading)
  6379. (outline-end-of-heading)
  6380. (when (and (looking-at "[ \t\n]+")
  6381. (= (match-end 0) (point-max)))
  6382. (outline-flag-region (point) (match-end 0) nil))))
  6383. (defun org-show-empty-lines-in-parent ()
  6384. "Move to the parent and re-show empty lines before visible headlines."
  6385. (save-excursion
  6386. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6387. (org-cycle-show-empty-lines context))))
  6388. (defun org-files-list ()
  6389. "Return `org-agenda-files' list, plus all open Org files.
  6390. This is useful for operations that need to scan all of a user's
  6391. open and agenda-wise Org files."
  6392. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6393. (dolist (buf (buffer-list))
  6394. (with-current-buffer buf
  6395. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6396. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6397. files))
  6398. (defsubst org-entry-beginning-position ()
  6399. "Return the beginning position of the current entry."
  6400. (save-excursion (org-back-to-heading t) (point)))
  6401. (defsubst org-entry-end-position ()
  6402. "Return the end position of the current entry."
  6403. (save-excursion (outline-next-heading) (point)))
  6404. (defun org-cycle-hide-drawers (state &optional exceptions)
  6405. "Re-hide all drawers after a visibility state change.
  6406. When non-nil, optional argument EXCEPTIONS is a list of strings
  6407. specifying which drawers should not be hidden."
  6408. (when (and (derived-mode-p 'org-mode)
  6409. (not (memq state '(overview folded contents))))
  6410. (save-excursion
  6411. (let* ((globalp (memq state '(contents all)))
  6412. (beg (if globalp (point-min) (point)))
  6413. (end (if globalp (point-max)
  6414. (if (eq state 'children)
  6415. (save-excursion (outline-next-heading) (point))
  6416. (org-end-of-subtree t)))))
  6417. (goto-char beg)
  6418. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6419. (unless (member-ignore-case (match-string 1) exceptions)
  6420. (let ((drawer (org-element-at-point)))
  6421. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6422. (org-flag-drawer t drawer)
  6423. ;; Make sure to skip drawer entirely or we might flag
  6424. ;; it another time when matching its ending line with
  6425. ;; `org-drawer-regexp'.
  6426. (goto-char (org-element-property :end drawer))))))))))
  6427. (defun org-flag-drawer (flag &optional element)
  6428. "When FLAG is non-nil, hide the drawer we are at.
  6429. Otherwise make it visible. When optional argument ELEMENT is
  6430. a parsed drawer, as returned by `org-element-at-point', hide or
  6431. show that drawer instead."
  6432. (let ((drawer (or element
  6433. (and (save-excursion
  6434. (beginning-of-line)
  6435. (looking-at-p org-drawer-regexp))
  6436. (org-element-at-point)))))
  6437. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6438. (let ((post (org-element-property :post-affiliated drawer)))
  6439. (save-excursion
  6440. (outline-flag-region
  6441. (progn (goto-char post) (line-end-position))
  6442. (progn (goto-char (org-element-property :end drawer))
  6443. (skip-chars-backward " \r\t\n")
  6444. (line-end-position))
  6445. flag))
  6446. ;; When the drawer is hidden away, make sure point lies in
  6447. ;; a visible part of the buffer.
  6448. (when (and flag (> (line-beginning-position) post))
  6449. (goto-char post))))))
  6450. (defun org-subtree-end-visible-p ()
  6451. "Is the end of the current subtree visible?"
  6452. (pos-visible-in-window-p
  6453. (save-excursion (org-end-of-subtree t) (point))))
  6454. (defun org-first-headline-recenter ()
  6455. "Move cursor to the first headline and recenter the headline."
  6456. (let ((window (get-buffer-window)))
  6457. (when window
  6458. (goto-char (point-min))
  6459. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6460. (set-window-start window (line-beginning-position))))))
  6461. ;;; Saving and restoring visibility
  6462. (defun org-outline-overlay-data (&optional use-markers)
  6463. "Return a list of the locations of all outline overlays.
  6464. These are overlays with the `invisible' property value `outline'.
  6465. The return value is a list of cons cells, with start and stop
  6466. positions for each overlay.
  6467. If USE-MARKERS is set, return the positions as markers."
  6468. (let (beg end)
  6469. (org-with-wide-buffer
  6470. (delq nil
  6471. (mapcar (lambda (o)
  6472. (when (eq (overlay-get o 'invisible) 'outline)
  6473. (setq beg (overlay-start o)
  6474. end (overlay-end o))
  6475. (and beg end (> end beg)
  6476. (if use-markers
  6477. (cons (copy-marker beg)
  6478. (copy-marker end t))
  6479. (cons beg end)))))
  6480. (overlays-in (point-min) (point-max)))))))
  6481. (defun org-set-outline-overlay-data (data)
  6482. "Create visibility overlays for all positions in DATA.
  6483. DATA should have been made by `org-outline-overlay-data'."
  6484. (org-with-wide-buffer
  6485. (outline-show-all)
  6486. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6487. ;;; Folding of blocks
  6488. (defvar-local org-hide-block-overlays nil
  6489. "Overlays hiding blocks.")
  6490. (defun org-block-map (function &optional start end)
  6491. "Call FUNCTION at the head of all source blocks in the current buffer.
  6492. Optional arguments START and END can be used to limit the range."
  6493. (let ((start (or start (point-min)))
  6494. (end (or end (point-max))))
  6495. (save-excursion
  6496. (goto-char start)
  6497. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6498. (save-excursion
  6499. (save-match-data
  6500. (goto-char (match-beginning 0))
  6501. (funcall function)))))))
  6502. (defun org-hide-block-toggle-all ()
  6503. "Toggle the visibility of all blocks in the current buffer."
  6504. (org-block-map 'org-hide-block-toggle))
  6505. (defun org-hide-block-all ()
  6506. "Fold all blocks in the current buffer."
  6507. (interactive)
  6508. (org-show-block-all)
  6509. (org-block-map 'org-hide-block-toggle-maybe))
  6510. (defun org-show-block-all ()
  6511. "Unfold all blocks in the current buffer."
  6512. (interactive)
  6513. (mapc #'delete-overlay org-hide-block-overlays)
  6514. (setq org-hide-block-overlays nil))
  6515. (defun org-hide-block-toggle-maybe ()
  6516. "Toggle visibility of block at point.
  6517. Unlike to `org-hide-block-toggle', this function does not throw
  6518. an error. Return a non-nil value when toggling is successful."
  6519. (interactive)
  6520. (ignore-errors (org-hide-block-toggle)))
  6521. (defun org-hide-block-toggle (&optional force)
  6522. "Toggle the visibility of the current block.
  6523. When optional argument FORCE is `off', make block visible. If it
  6524. is non-nil, hide it unconditionally. Throw an error when not at
  6525. a block. Return a non-nil value when toggling is successful."
  6526. (interactive)
  6527. (let ((element (org-element-at-point)))
  6528. (unless (memq (org-element-type element)
  6529. '(center-block comment-block dynamic-block example-block
  6530. export-block quote-block special-block
  6531. src-block verse-block))
  6532. (user-error "Not at a block"))
  6533. (let* ((start (save-excursion
  6534. (goto-char (org-element-property :post-affiliated element))
  6535. (line-end-position)))
  6536. (end (save-excursion
  6537. (goto-char (org-element-property :end element))
  6538. (skip-chars-backward " \r\t\n")
  6539. (line-end-position)))
  6540. (overlays (overlays-at start)))
  6541. (cond
  6542. ;; Do nothing when not before or at the block opening line or
  6543. ;; at the block closing line.
  6544. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6545. ((and (not (eq force 'off))
  6546. (not (memq t (mapcar
  6547. (lambda (o)
  6548. (eq (overlay-get o 'invisible) 'org-hide-block))
  6549. overlays))))
  6550. (let ((ov (make-overlay start end)))
  6551. (overlay-put ov 'invisible 'org-hide-block)
  6552. ;; Make the block accessible to `isearch'.
  6553. (overlay-put
  6554. ov 'isearch-open-invisible
  6555. (lambda (ov)
  6556. (when (memq ov org-hide-block-overlays)
  6557. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6558. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6559. (delete-overlay ov))))
  6560. (push ov org-hide-block-overlays)
  6561. ;; When the block is hidden away, make sure point is left in
  6562. ;; a visible part of the buffer.
  6563. (when (> (line-beginning-position) start)
  6564. (goto-char start)
  6565. (beginning-of-line))
  6566. ;; Signal successful toggling.
  6567. t))
  6568. ((or (not force) (eq force 'off))
  6569. (dolist (ov overlays t)
  6570. (when (memq ov org-hide-block-overlays)
  6571. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6572. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6573. (delete-overlay ov))))))))
  6574. ;; Remove overlays when changing major mode
  6575. (add-hook 'org-mode-hook
  6576. (lambda () (add-hook 'change-major-mode-hook
  6577. 'org-show-block-all 'append 'local)))
  6578. ;;; Org-goto
  6579. (defvar org-goto-window-configuration nil)
  6580. (defvar org-goto-marker nil)
  6581. (defvar org-goto-map)
  6582. (defun org-goto-map ()
  6583. "Set the keymap `org-goto'."
  6584. (setq org-goto-map
  6585. (let ((map (make-sparse-keymap)))
  6586. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6587. mouse-drag-region universal-argument org-occur)))
  6588. (dolist (cmd cmds)
  6589. (substitute-key-definition cmd cmd map global-map)))
  6590. (suppress-keymap map)
  6591. (org-defkey map "\C-m" 'org-goto-ret)
  6592. (org-defkey map [(return)] 'org-goto-ret)
  6593. (org-defkey map [(left)] 'org-goto-left)
  6594. (org-defkey map [(right)] 'org-goto-right)
  6595. (org-defkey map [(control ?g)] 'org-goto-quit)
  6596. (org-defkey map "\C-i" 'org-cycle)
  6597. (org-defkey map [(tab)] 'org-cycle)
  6598. (org-defkey map [(down)] 'outline-next-visible-heading)
  6599. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6600. (if org-goto-auto-isearch
  6601. (if (fboundp 'define-key-after)
  6602. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6603. nil)
  6604. (org-defkey map "q" 'org-goto-quit)
  6605. (org-defkey map "n" 'outline-next-visible-heading)
  6606. (org-defkey map "p" 'outline-previous-visible-heading)
  6607. (org-defkey map "f" 'outline-forward-same-level)
  6608. (org-defkey map "b" 'outline-backward-same-level)
  6609. (org-defkey map "u" 'outline-up-heading))
  6610. (org-defkey map "/" 'org-occur)
  6611. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6612. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6613. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6614. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6615. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6616. map)))
  6617. (defconst org-goto-help
  6618. "Browse buffer copy, to find location or copy text.%s
  6619. RET=jump to location C-g=quit and return to previous location
  6620. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6621. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6622. (defun org-goto (&optional alternative-interface)
  6623. "Look up a different location in the current file, keeping current visibility.
  6624. When you want look-up or go to a different location in a
  6625. document, the fastest way is often to fold the entire buffer and
  6626. then dive into the tree. This method has the disadvantage, that
  6627. the previous location will be folded, which may not be what you
  6628. want.
  6629. This command works around this by showing a copy of the current
  6630. buffer in an indirect buffer, in overview mode. You can dive
  6631. into the tree in that copy, use org-occur and incremental search
  6632. to find a location. When pressing RET or `Q', the command
  6633. returns to the original buffer in which the visibility is still
  6634. unchanged. After RET it will also jump to the location selected
  6635. in the indirect buffer and expose the headline hierarchy above.
  6636. With a prefix argument, use the alternative interface: e.g., if
  6637. `org-goto-interface' is `outline' use `outline-path-completion'."
  6638. (interactive "P")
  6639. (org-goto-map)
  6640. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6641. (org-refile-use-outline-path t)
  6642. (org-refile-target-verify-function nil)
  6643. (interface
  6644. (if (not alternative-interface)
  6645. org-goto-interface
  6646. (if (eq org-goto-interface 'outline)
  6647. 'outline-path-completion
  6648. 'outline)))
  6649. (org-goto-start-pos (point))
  6650. (selected-point
  6651. (if (eq interface 'outline)
  6652. (car (org-get-location (current-buffer) org-goto-help))
  6653. (let ((pa (org-refile-get-location "Goto")))
  6654. (org-refile-check-position pa)
  6655. (nth 3 pa)))))
  6656. (if selected-point
  6657. (progn
  6658. (org-mark-ring-push org-goto-start-pos)
  6659. (goto-char selected-point)
  6660. (when (or (outline-invisible-p) (org-invisible-p2))
  6661. (org-show-context 'org-goto)))
  6662. (message "Quit"))))
  6663. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6664. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6665. (defvar org-goto-local-auto-isearch-map) ; defined below
  6666. (defun org-get-location (_buf help)
  6667. "Let the user select a location in current buffer.
  6668. This function uses a recursive edit. It returns the selected position
  6669. or nil."
  6670. (org-no-popups
  6671. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6672. (isearch-hide-immediately nil)
  6673. (isearch-search-fun-function
  6674. (lambda () 'org-goto-local-search-headings))
  6675. (org-goto-selected-point org-goto-exit-command))
  6676. (save-excursion
  6677. (save-window-excursion
  6678. (delete-other-windows)
  6679. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6680. (pop-to-buffer-same-window
  6681. (condition-case nil
  6682. (make-indirect-buffer (current-buffer) "*org-goto*")
  6683. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6684. (with-output-to-temp-buffer "*Org Help*"
  6685. (princ (format help (if org-goto-auto-isearch
  6686. " Just type for auto-isearch."
  6687. " n/p/f/b/u to navigate, q to quit."))))
  6688. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6689. (setq buffer-read-only nil)
  6690. (let ((org-startup-truncated t)
  6691. (org-startup-folded nil)
  6692. (org-startup-align-all-tables nil))
  6693. (org-mode)
  6694. (org-overview))
  6695. (setq buffer-read-only t)
  6696. (if (and (boundp 'org-goto-start-pos)
  6697. (integer-or-marker-p org-goto-start-pos))
  6698. (progn (goto-char org-goto-start-pos)
  6699. (when (outline-invisible-p)
  6700. (org-show-set-visibility 'lineage)))
  6701. (goto-char (point-min)))
  6702. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6703. (message "Select location and press RET")
  6704. (use-local-map org-goto-map)
  6705. (recursive-edit)))
  6706. (kill-buffer "*org-goto*")
  6707. (cons org-goto-selected-point org-goto-exit-command))))
  6708. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6709. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6710. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6711. (if (fboundp 'isearch-other-control-char)
  6712. (progn
  6713. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6714. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6715. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6716. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6717. (define-key org-goto-local-auto-isearch-map [return] nil))
  6718. (defun org-goto-local-search-headings (string bound noerror)
  6719. "Search and make sure that any matches are in headlines."
  6720. (catch 'return
  6721. (while (if isearch-forward
  6722. (search-forward string bound noerror)
  6723. (search-backward string bound noerror))
  6724. (when (save-match-data
  6725. (and (save-excursion
  6726. (beginning-of-line)
  6727. (looking-at org-complex-heading-regexp))
  6728. (or (not (match-beginning 5))
  6729. (< (point) (match-beginning 5)))))
  6730. (throw 'return (point))))))
  6731. (defun org-goto-local-auto-isearch ()
  6732. "Start isearch."
  6733. (interactive)
  6734. (goto-char (point-min))
  6735. (let ((keys (this-command-keys)))
  6736. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6737. (isearch-mode t)
  6738. (isearch-process-search-char (string-to-char keys)))))
  6739. (defun org-goto-ret (&optional _arg)
  6740. "Finish `org-goto' by going to the new location."
  6741. (interactive "P")
  6742. (setq org-goto-selected-point (point))
  6743. (setq org-goto-exit-command 'return)
  6744. (throw 'exit nil))
  6745. (defun org-goto-left ()
  6746. "Finish `org-goto' by going to the new location."
  6747. (interactive)
  6748. (if (org-at-heading-p)
  6749. (progn
  6750. (beginning-of-line 1)
  6751. (setq org-goto-selected-point (point)
  6752. org-goto-exit-command 'left)
  6753. (throw 'exit nil))
  6754. (user-error "Not on a heading")))
  6755. (defun org-goto-right ()
  6756. "Finish `org-goto' by going to the new location."
  6757. (interactive)
  6758. (if (org-at-heading-p)
  6759. (progn
  6760. (setq org-goto-selected-point (point)
  6761. org-goto-exit-command 'right)
  6762. (throw 'exit nil))
  6763. (user-error "Not on a heading")))
  6764. (defun org-goto-quit ()
  6765. "Finish `org-goto' without cursor motion."
  6766. (interactive)
  6767. (setq org-goto-selected-point nil)
  6768. (setq org-goto-exit-command 'quit)
  6769. (throw 'exit nil))
  6770. ;;; Indirect buffer display of subtrees
  6771. (defvar org-indirect-dedicated-frame nil
  6772. "This is the frame being used for indirect tree display.")
  6773. (defvar org-last-indirect-buffer nil)
  6774. (defun org-tree-to-indirect-buffer (&optional arg)
  6775. "Create indirect buffer and narrow it to current subtree.
  6776. With a numerical prefix ARG, go up to this level and then take that tree.
  6777. If ARG is negative, go up that many levels.
  6778. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6779. indirect buffer previously made with this command, to avoid proliferation of
  6780. indirect buffers. However, when you call the command with a \
  6781. `\\[universal-argument]' prefix, or
  6782. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6783. so that you can work with several indirect buffers at the same time. If
  6784. `org-indirect-buffer-display' is `dedicated-frame', the \
  6785. `\\[universal-argument]' prefix also
  6786. requests that a new frame be made for the new buffer, so that the dedicated
  6787. frame is not changed."
  6788. (interactive "P")
  6789. (let ((cbuf (current-buffer))
  6790. (cwin (selected-window))
  6791. (pos (point))
  6792. beg end level heading ibuf)
  6793. (save-excursion
  6794. (org-back-to-heading t)
  6795. (when (numberp arg)
  6796. (setq level (org-outline-level))
  6797. (when (< arg 0) (setq arg (+ level arg)))
  6798. (while (> (setq level (org-outline-level)) arg)
  6799. (org-up-heading-safe)))
  6800. (setq beg (point)
  6801. heading (org-get-heading 'no-tags))
  6802. (org-end-of-subtree t t)
  6803. (when (org-at-heading-p) (backward-char 1))
  6804. (setq end (point)))
  6805. (when (and (buffer-live-p org-last-indirect-buffer)
  6806. (not (eq org-indirect-buffer-display 'new-frame))
  6807. (not arg))
  6808. (kill-buffer org-last-indirect-buffer))
  6809. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6810. org-last-indirect-buffer ibuf)
  6811. (cond
  6812. ((or (eq org-indirect-buffer-display 'new-frame)
  6813. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6814. (select-frame (make-frame))
  6815. (delete-other-windows)
  6816. (pop-to-buffer-same-window ibuf)
  6817. (org-set-frame-title heading))
  6818. ((eq org-indirect-buffer-display 'dedicated-frame)
  6819. (raise-frame
  6820. (select-frame (or (and org-indirect-dedicated-frame
  6821. (frame-live-p org-indirect-dedicated-frame)
  6822. org-indirect-dedicated-frame)
  6823. (setq org-indirect-dedicated-frame (make-frame)))))
  6824. (delete-other-windows)
  6825. (pop-to-buffer-same-window ibuf)
  6826. (org-set-frame-title (concat "Indirect: " heading)))
  6827. ((eq org-indirect-buffer-display 'current-window)
  6828. (pop-to-buffer-same-window ibuf))
  6829. ((eq org-indirect-buffer-display 'other-window)
  6830. (pop-to-buffer ibuf))
  6831. (t (error "Invalid value")))
  6832. (narrow-to-region beg end)
  6833. (outline-show-all)
  6834. (goto-char pos)
  6835. (run-hook-with-args 'org-cycle-hook 'all)
  6836. (and (window-live-p cwin) (select-window cwin))))
  6837. (defun org-get-indirect-buffer (&optional buffer heading)
  6838. (setq buffer (or buffer (current-buffer)))
  6839. (let ((n 1) (base (buffer-name buffer)) bname)
  6840. (while (buffer-live-p
  6841. (get-buffer
  6842. (setq bname
  6843. (concat base "-"
  6844. (if heading (concat heading "-" (number-to-string n))
  6845. (number-to-string n))))))
  6846. (setq n (1+ n)))
  6847. (condition-case nil
  6848. (make-indirect-buffer buffer bname 'clone)
  6849. (error (make-indirect-buffer buffer bname)))))
  6850. (defun org-set-frame-title (title)
  6851. "Set the title of the current frame to the string TITLE."
  6852. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6853. ;;;; Structure editing
  6854. ;;; Inserting headlines
  6855. (defun org--line-empty-p (n)
  6856. "Is the Nth next line empty?
  6857. Counts the current line as N = 1 and the previous line as N = 0;
  6858. see `beginning-of-line'."
  6859. (save-excursion
  6860. (and (not (bobp))
  6861. (or (beginning-of-line n) t)
  6862. (save-match-data
  6863. (looking-at "[ \t]*$")))))
  6864. (defun org-previous-line-empty-p ()
  6865. "Is the previous line a blank line?
  6866. When NEXT is non-nil, check the next line instead."
  6867. (org--line-empty-p 0))
  6868. (defun org-next-line-empty-p ()
  6869. "Is the previous line a blank line?
  6870. When NEXT is non-nil, check the next line instead."
  6871. (org--line-empty-p 2))
  6872. (defun org--blank-before-heading-p (&optional parent)
  6873. "Non-nil when an empty line should precede a new heading here.
  6874. When optional argument PARENT is non-nil, consider parent
  6875. headline instead of current one."
  6876. (pcase (assq 'heading org-blank-before-new-entry)
  6877. (`(heading . auto)
  6878. (save-excursion
  6879. (org-with-limited-levels
  6880. (unless (and (org-before-first-heading-p)
  6881. (not (outline-next-heading)))
  6882. (org-back-to-heading t)
  6883. (when parent (org-up-heading-safe))
  6884. (cond ((not (bobp))
  6885. (org-previous-line-empty-p))
  6886. ((outline-next-heading)
  6887. (org-previous-line-empty-p))
  6888. ;; Ignore trailing spaces on last buffer line.
  6889. ((progn (skip-chars-backward " \t") (bolp))
  6890. (org-previous-line-empty-p))
  6891. (t nil))))))
  6892. (`(heading . ,value) value)
  6893. (_ nil)))
  6894. (defun org-insert-heading (&optional arg invisible-ok top)
  6895. "Insert a new heading or an item with the same depth at point.
  6896. If point is at the beginning of a heading, insert a new heading
  6897. or a new headline above the current one. When at the beginning
  6898. of a regular line of text, turn it into a heading.
  6899. If point is in the middle of a line, split it and create a new
  6900. headline with the text in the current line after point (see
  6901. `org-M-RET-may-split-line' on how to modify this behavior). As
  6902. a special case, on a headline, splitting can only happen on the
  6903. title itself. E.g., this excludes breaking stars or tags.
  6904. With a `\\[universal-argument]' prefix, set \
  6905. `org-insert-heading-respect-content' to
  6906. a non-nil value for the duration of the command. This forces the
  6907. insertion of a heading after the current subtree, independently
  6908. on the location of point.
  6909. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6910. insert the heading at the end of the tree
  6911. above the current heading. For example, if point is within a
  6912. 2nd-level heading, then it will insert a 2nd-level heading at
  6913. the end of the 1st-level parent subtree.
  6914. When INVISIBLE-OK is set, stop at invisible headlines when going
  6915. back. This is important for non-interactive uses of the
  6916. command.
  6917. When optional argument TOP is non-nil, insert a level 1 heading,
  6918. unconditionally."
  6919. (interactive "P")
  6920. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6921. (level (org-current-level))
  6922. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6923. (cond
  6924. ((or org-insert-heading-respect-content
  6925. (member arg '((4) (16)))
  6926. (and (not invisible-ok)
  6927. (invisible-p (max (1- (point)) (point-min)))))
  6928. ;; Position point at the location of insertion.
  6929. (if (not level) ;before first headline
  6930. (org-with-limited-levels (outline-next-heading))
  6931. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6932. ;; is nil.
  6933. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6934. (cond ((equal arg '(16))
  6935. (org-up-heading-safe)
  6936. (org-end-of-subtree t t))
  6937. (t
  6938. (org-end-of-subtree t t))))
  6939. (unless (bolp) (insert "\n")) ;ensure final newline
  6940. (unless (and blank? (org-previous-line-empty-p))
  6941. (org-N-empty-lines-before-current (if blank? 1 0)))
  6942. (insert stars " \n")
  6943. (forward-char -1))
  6944. ;; At a headline...
  6945. ((org-at-heading-p)
  6946. (cond ((bolp)
  6947. (when blank? (save-excursion (insert "\n")))
  6948. (save-excursion (insert stars " \n"))
  6949. (unless (and blank? (org-previous-line-empty-p))
  6950. (org-N-empty-lines-before-current (if blank? 1 0)))
  6951. (end-of-line))
  6952. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6953. (org-match-line org-complex-heading-regexp)
  6954. (org-pos-in-match-range (point) 4))
  6955. ;; Grab the text that should moved to the new headline.
  6956. ;; Preserve tags.
  6957. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6958. (if (looking-at "[ \t]*$") (replace-match "")
  6959. (org-set-tags nil t))
  6960. (end-of-line)
  6961. (when blank? (insert "\n"))
  6962. (insert "\n" stars " ")
  6963. (when (org-string-nw-p split) (insert split))
  6964. (when (eobp) (save-excursion (insert "\n")))))
  6965. (t
  6966. (end-of-line)
  6967. (when blank? (insert "\n"))
  6968. (insert "\n" stars " ")
  6969. (when (eobp) (save-excursion (insert "\n"))))))
  6970. ;; On regular text, turn line into a headline or split, if
  6971. ;; appropriate.
  6972. ((bolp)
  6973. (insert stars " ")
  6974. (unless (and blank? (org-previous-line-empty-p))
  6975. (org-N-empty-lines-before-current (if blank? 1 0))))
  6976. (t
  6977. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6978. (end-of-line))
  6979. (insert "\n" stars " ")
  6980. (unless (and blank? (org-previous-line-empty-p))
  6981. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6982. (run-hooks 'org-insert-heading-hook))
  6983. (defun org-N-empty-lines-before-current (n)
  6984. "Make the number of empty lines before current exactly N.
  6985. So this will delete or add empty lines."
  6986. (let ((column (current-column)))
  6987. (beginning-of-line)
  6988. (unless (bobp)
  6989. (let ((start (save-excursion
  6990. (skip-chars-backward " \r\t\n")
  6991. (line-end-position))))
  6992. (delete-region start (line-end-position 0))))
  6993. (insert (make-string n ?\n))
  6994. (move-to-column column)))
  6995. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6996. "Return the heading of the current entry, without the stars.
  6997. When NO-TAGS is non-nil, don't include tags.
  6998. When NO-TODO is non-nil, don't include TODO keywords.
  6999. When NO-PRIORITY is non-nil, don't include priority cookie.
  7000. When NO-COMMENT is non-nil, don't include COMMENT string."
  7001. (save-excursion
  7002. (org-back-to-heading t)
  7003. (let ((case-fold-search nil))
  7004. (looking-at org-complex-heading-regexp)
  7005. (let ((todo (and (not no-todo) (match-string 2)))
  7006. (priority (and (not no-priority) (match-string 3)))
  7007. (headline (pcase (match-string 4)
  7008. (`nil "")
  7009. ((and (guard no-comment) h)
  7010. (replace-regexp-in-string
  7011. (eval-when-compile
  7012. (format "\\`%s[ \t]+" org-comment-string))
  7013. "" h))
  7014. (h h)))
  7015. (tags (and (not no-tags) (match-string 5))))
  7016. (mapconcat #'identity
  7017. (delq nil (list todo priority headline tags))
  7018. " ")))))
  7019. (defvar orgstruct-mode) ; defined below
  7020. (defun org-heading-components ()
  7021. "Return the components of the current heading.
  7022. This is a list with the following elements:
  7023. - the level as an integer
  7024. - the reduced level, different if `org-odd-levels-only' is set.
  7025. - the TODO keyword, or nil
  7026. - the priority character, like ?A, or nil if no priority is given
  7027. - the headline text itself, or the tags string if no headline text
  7028. - the tags string, or nil."
  7029. (save-excursion
  7030. (org-back-to-heading t)
  7031. (when (let (case-fold-search)
  7032. (looking-at
  7033. (if orgstruct-mode
  7034. org-heading-regexp
  7035. org-complex-heading-regexp)))
  7036. (if orgstruct-mode
  7037. (list (length (match-string 1))
  7038. (org-reduced-level (length (match-string 1)))
  7039. nil
  7040. nil
  7041. (match-string 2)
  7042. nil)
  7043. (list (length (match-string 1))
  7044. (org-reduced-level (length (match-string 1)))
  7045. (match-string-no-properties 2)
  7046. (and (match-end 3) (aref (match-string 3) 2))
  7047. (match-string-no-properties 4)
  7048. (match-string-no-properties 5))))))
  7049. (defun org-get-entry ()
  7050. "Get the entry text, after heading, entire subtree."
  7051. (save-excursion
  7052. (org-back-to-heading t)
  7053. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7054. (defun org-edit-headline (&optional heading)
  7055. "Edit the current headline.
  7056. Set it to HEADING when provided."
  7057. (interactive)
  7058. (org-with-wide-buffer
  7059. (org-back-to-heading t)
  7060. (let ((case-fold-search nil))
  7061. (when (looking-at org-complex-heading-regexp)
  7062. (let* ((old (match-string-no-properties 4))
  7063. (new (save-match-data
  7064. (org-trim (or heading (read-string "Edit: " old))))))
  7065. (unless (equal old new)
  7066. (if old (replace-match new t t nil 4)
  7067. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7068. (insert " " new))
  7069. (org-set-tags nil t)
  7070. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7071. (defun org-insert-heading-after-current ()
  7072. "Insert a new heading with same level as current, after current subtree."
  7073. (interactive)
  7074. (org-back-to-heading)
  7075. (org-insert-heading)
  7076. (org-move-subtree-down)
  7077. (end-of-line 1))
  7078. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7079. "Insert heading with `org-insert-heading-respect-content' set to t."
  7080. (interactive)
  7081. (org-insert-heading '(4) invisible-ok))
  7082. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7083. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7084. (interactive)
  7085. (org-insert-todo-heading force-state '(4)))
  7086. (defun org-insert-todo-heading (arg &optional force-heading)
  7087. "Insert a new heading with the same level and TODO state as current heading.
  7088. If the heading has no TODO state, or if the state is DONE, use
  7089. the first state (TODO by default). Also with one prefix arg,
  7090. force first state. With two prefix args, force inserting at the
  7091. end of the parent subtree.
  7092. When called at a plain list item, insert a new item with an
  7093. unchecked check box."
  7094. (interactive "P")
  7095. (when (or force-heading (not (org-insert-item 'checkbox)))
  7096. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7097. force-heading))
  7098. (save-excursion
  7099. (org-back-to-heading)
  7100. (outline-previous-heading)
  7101. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7102. (let* ((new-mark-x
  7103. (if (or (equal arg '(4))
  7104. (not (match-beginning 2))
  7105. (member (match-string 2) org-done-keywords))
  7106. (car org-todo-keywords-1)
  7107. (match-string 2)))
  7108. (new-mark
  7109. (or
  7110. (run-hook-with-args-until-success
  7111. 'org-todo-get-default-hook new-mark-x nil)
  7112. new-mark-x)))
  7113. (beginning-of-line 1)
  7114. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7115. (if org-treat-insert-todo-heading-as-state-change
  7116. (org-todo new-mark)
  7117. (insert new-mark " "))))
  7118. (when org-provide-todo-statistics
  7119. (org-update-parent-todo-statistics))))
  7120. (defun org-insert-subheading (arg)
  7121. "Insert a new subheading and demote it.
  7122. Works for outline headings and for plain lists alike."
  7123. (interactive "P")
  7124. (org-insert-heading arg)
  7125. (cond
  7126. ((org-at-heading-p) (org-do-demote))
  7127. ((org-at-item-p) (org-indent-item))))
  7128. (defun org-insert-todo-subheading (arg)
  7129. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7130. Works for outline headings and for plain lists alike."
  7131. (interactive "P")
  7132. (org-insert-todo-heading arg)
  7133. (cond
  7134. ((org-at-heading-p) (org-do-demote))
  7135. ((org-at-item-p) (org-indent-item))))
  7136. ;;; Promotion and Demotion
  7137. (defvar org-after-demote-entry-hook nil
  7138. "Hook run after an entry has been demoted.
  7139. The cursor will be at the beginning of the entry.
  7140. When a subtree is being demoted, the hook will be called for each node.")
  7141. (defvar org-after-promote-entry-hook nil
  7142. "Hook run after an entry has been promoted.
  7143. The cursor will be at the beginning of the entry.
  7144. When a subtree is being promoted, the hook will be called for each node.")
  7145. (defun org-promote-subtree ()
  7146. "Promote the entire subtree.
  7147. See also `org-promote'."
  7148. (interactive)
  7149. (save-excursion
  7150. (org-with-limited-levels (org-map-tree 'org-promote)))
  7151. (org-fix-position-after-promote))
  7152. (defun org-demote-subtree ()
  7153. "Demote the entire subtree.
  7154. See `org-demote' and `org-promote'."
  7155. (interactive)
  7156. (save-excursion
  7157. (org-with-limited-levels (org-map-tree 'org-demote)))
  7158. (org-fix-position-after-promote))
  7159. (defun org-do-promote ()
  7160. "Promote the current heading higher up the tree.
  7161. If the region is active in `transient-mark-mode', promote all
  7162. headings in the region."
  7163. (interactive)
  7164. (save-excursion
  7165. (if (org-region-active-p)
  7166. (org-map-region 'org-promote (region-beginning) (region-end))
  7167. (org-promote)))
  7168. (org-fix-position-after-promote))
  7169. (defun org-do-demote ()
  7170. "Demote the current heading lower down the tree.
  7171. If the region is active in `transient-mark-mode', demote all
  7172. headings in the region."
  7173. (interactive)
  7174. (save-excursion
  7175. (if (org-region-active-p)
  7176. (org-map-region 'org-demote (region-beginning) (region-end))
  7177. (org-demote)))
  7178. (org-fix-position-after-promote))
  7179. (defun org-fix-position-after-promote ()
  7180. "Fix cursor position and indentation after demoting/promoting."
  7181. (let ((pos (point)))
  7182. (when (save-excursion
  7183. (beginning-of-line)
  7184. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7185. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7186. (cond ((eobp) (insert " "))
  7187. ((eolp) (insert " "))
  7188. ((equal (char-after) ?\s) (forward-char 1))))))
  7189. (defun org-current-level ()
  7190. "Return the level of the current entry, or nil if before the first headline.
  7191. The level is the number of stars at the beginning of the
  7192. headline. Use `org-reduced-level' to remove the effect of
  7193. `org-odd-levels'. Unlike to `org-outline-level', this function
  7194. ignores inlinetasks."
  7195. (let ((level (org-with-limited-levels (org-outline-level))))
  7196. (and (> level 0) level)))
  7197. (defun org-get-previous-line-level ()
  7198. "Return the outline depth of the last headline before the current line.
  7199. Returns 0 for the first headline in the buffer, and nil if before the
  7200. first headline."
  7201. (and (org-current-level)
  7202. (or (and (/= (line-beginning-position) (point-min))
  7203. (save-excursion (beginning-of-line 0) (org-current-level)))
  7204. 0)))
  7205. (defun org-reduced-level (l)
  7206. "Compute the effective level of a heading.
  7207. This takes into account the setting of `org-odd-levels-only'."
  7208. (cond
  7209. ((zerop l) 0)
  7210. (org-odd-levels-only (1+ (floor (/ l 2))))
  7211. (t l)))
  7212. (defun org-level-increment ()
  7213. "Return the number of stars that will be added or removed at a
  7214. time to headlines when structure editing, based on the value of
  7215. `org-odd-levels-only'."
  7216. (if org-odd-levels-only 2 1))
  7217. (defun org-get-valid-level (level &optional change)
  7218. "Rectify a level change under the influence of `org-odd-levels-only'.
  7219. LEVEL is a current level, CHANGE is by how much the level should
  7220. be modified. Even if CHANGE is nil, LEVEL may be returned
  7221. modified because even level numbers will become the next higher
  7222. odd number. Returns values greater than 0."
  7223. (if org-odd-levels-only
  7224. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7225. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7226. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7227. (max 1 (+ level (or change 0)))))
  7228. (defun org-promote ()
  7229. "Promote the current heading higher up the tree."
  7230. (org-with-wide-buffer
  7231. (org-back-to-heading t)
  7232. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7233. after-change-functions))
  7234. (level (save-match-data (funcall outline-level)))
  7235. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7236. (diff (abs (- level (length up-head) -1))))
  7237. (cond
  7238. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7239. (replace-match "# " nil t))
  7240. ((= level 1)
  7241. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7242. (t (replace-match up-head nil t)))
  7243. (unless (= level 1)
  7244. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7245. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7246. (run-hooks 'org-after-promote-entry-hook))))
  7247. (defun org-demote ()
  7248. "Demote the current heading lower down the tree."
  7249. (org-with-wide-buffer
  7250. (org-back-to-heading t)
  7251. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7252. after-change-functions))
  7253. (level (save-match-data (funcall outline-level)))
  7254. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7255. (diff (abs (- level (length down-head) -1))))
  7256. (replace-match down-head nil t)
  7257. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7258. (when org-adapt-indentation (org-fixup-indentation diff))
  7259. (run-hooks 'org-after-demote-entry-hook))))
  7260. (defun org-cycle-level ()
  7261. "Cycle the level of an empty headline through possible states.
  7262. This goes first to child, then to parent, level, then up the hierarchy.
  7263. After top level, it switches back to sibling level."
  7264. (interactive)
  7265. (let ((org-adapt-indentation nil))
  7266. (when (org-point-at-end-of-empty-headline)
  7267. (setq this-command 'org-cycle-level) ; Only needed for caching
  7268. (let ((cur-level (org-current-level))
  7269. (prev-level (org-get-previous-line-level)))
  7270. (cond
  7271. ;; If first headline in file, promote to top-level.
  7272. ((= prev-level 0)
  7273. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7274. do (org-do-promote)))
  7275. ;; If same level as prev, demote one.
  7276. ((= prev-level cur-level)
  7277. (org-do-demote))
  7278. ;; If parent is top-level, promote to top level if not already.
  7279. ((= prev-level 1)
  7280. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7281. do (org-do-promote)))
  7282. ;; If top-level, return to prev-level.
  7283. ((= cur-level 1)
  7284. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7285. do (org-do-demote)))
  7286. ;; If less than prev-level, promote one.
  7287. ((< cur-level prev-level)
  7288. (org-do-promote))
  7289. ;; If deeper than prev-level, promote until higher than
  7290. ;; prev-level.
  7291. ((> cur-level prev-level)
  7292. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7293. do (org-do-promote))))
  7294. t))))
  7295. (defun org-map-tree (fun)
  7296. "Call FUN for every heading underneath the current one."
  7297. (org-back-to-heading t)
  7298. (let ((level (funcall outline-level)))
  7299. (save-excursion
  7300. (funcall fun)
  7301. (while (and (progn
  7302. (outline-next-heading)
  7303. (> (funcall outline-level) level))
  7304. (not (eobp)))
  7305. (funcall fun)))))
  7306. (defun org-map-region (fun beg end)
  7307. "Call FUN for every heading between BEG and END."
  7308. (let ((org-ignore-region t))
  7309. (save-excursion
  7310. (setq end (copy-marker end))
  7311. (goto-char beg)
  7312. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7313. (< (point) end))
  7314. (funcall fun))
  7315. (while (and (progn
  7316. (outline-next-heading)
  7317. (< (point) end))
  7318. (not (eobp)))
  7319. (funcall fun)))))
  7320. (defun org-fixup-indentation (diff)
  7321. "Change the indentation in the current entry by DIFF.
  7322. DIFF is an integer. Indentation is done according to the
  7323. following rules:
  7324. - Planning information and property drawers are always indented
  7325. according to the new level of the headline;
  7326. - Footnote definitions and their contents are ignored;
  7327. - Inlinetasks' boundaries are not shifted;
  7328. - Empty lines are ignored;
  7329. - Other lines' indentation are shifted by DIFF columns, unless
  7330. it would introduce a structural change in the document, in
  7331. which case no shifting is done at all.
  7332. Assume point is at a heading or an inlinetask beginning."
  7333. (org-with-wide-buffer
  7334. (narrow-to-region (line-beginning-position)
  7335. (save-excursion
  7336. (if (org-with-limited-levels (org-at-heading-p))
  7337. (org-with-limited-levels (outline-next-heading))
  7338. (org-inlinetask-goto-end))
  7339. (point)))
  7340. (forward-line)
  7341. ;; Indent properly planning info and property drawer.
  7342. (when (looking-at-p org-planning-line-re)
  7343. (org-indent-line)
  7344. (forward-line))
  7345. (when (looking-at org-property-drawer-re)
  7346. (goto-char (match-end 0))
  7347. (forward-line)
  7348. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7349. (catch 'no-shift
  7350. (when (zerop diff) (throw 'no-shift nil))
  7351. ;; If DIFF is negative, first check if a shift is possible at all
  7352. ;; (e.g., it doesn't break structure). This can only happen if
  7353. ;; some contents are not properly indented.
  7354. (let ((case-fold-search t))
  7355. (when (< diff 0)
  7356. (let ((diff (- diff))
  7357. (forbidden-re (concat org-outline-regexp
  7358. "\\|"
  7359. (substring org-footnote-definition-re 1))))
  7360. (save-excursion
  7361. (while (not (eobp))
  7362. (cond
  7363. ((looking-at-p "[ \t]*$") (forward-line))
  7364. ((and (looking-at-p org-footnote-definition-re)
  7365. (let ((e (org-element-at-point)))
  7366. (and (eq (org-element-type e) 'footnote-definition)
  7367. (goto-char (org-element-property :end e))))))
  7368. ((looking-at-p org-outline-regexp) (forward-line))
  7369. ;; Give up if shifting would move before column 0 or
  7370. ;; if it would introduce a headline or a footnote
  7371. ;; definition.
  7372. (t
  7373. (skip-chars-forward " \t")
  7374. (let ((ind (current-column)))
  7375. (when (or (< ind diff)
  7376. (and (= ind diff) (looking-at-p forbidden-re)))
  7377. (throw 'no-shift nil)))
  7378. ;; Ignore contents of example blocks and source
  7379. ;; blocks if their indentation is meant to be
  7380. ;; preserved. Jump to block's closing line.
  7381. (beginning-of-line)
  7382. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7383. (let ((e (org-element-at-point)))
  7384. (and (memq (org-element-type e)
  7385. '(example-block src-block))
  7386. (or org-src-preserve-indentation
  7387. (org-element-property :preserve-indent e))
  7388. (goto-char (org-element-property :end e))
  7389. (progn (skip-chars-backward " \r\t\n")
  7390. (beginning-of-line)
  7391. t))))
  7392. (forward-line))))))))
  7393. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7394. ;; by DIFF. Also skip contents of source or example blocks
  7395. ;; when indentation is meant to be preserved.
  7396. (while (not (eobp))
  7397. (cond
  7398. ((and (looking-at-p org-footnote-definition-re)
  7399. (let ((e (org-element-at-point)))
  7400. (and (eq (org-element-type e) 'footnote-definition)
  7401. (goto-char (org-element-property :end e))))))
  7402. ((looking-at-p org-outline-regexp) (forward-line))
  7403. ((looking-at-p "[ \t]*$") (forward-line))
  7404. (t
  7405. (indent-line-to (+ (org-get-indentation) diff))
  7406. (beginning-of-line)
  7407. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7408. (let ((e (org-element-at-point)))
  7409. (and (memq (org-element-type e)
  7410. '(example-block src-block))
  7411. (or org-src-preserve-indentation
  7412. (org-element-property :preserve-indent e))
  7413. (goto-char (org-element-property :end e))
  7414. (progn (skip-chars-backward " \r\t\n")
  7415. (beginning-of-line)
  7416. t))))
  7417. (forward-line)))))))))
  7418. (defun org-convert-to-odd-levels ()
  7419. "Convert an Org file with all levels allowed to one with odd levels.
  7420. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7421. level 5 etc."
  7422. (interactive)
  7423. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7424. (let ((outline-level 'org-outline-level)
  7425. (org-odd-levels-only nil) n)
  7426. (save-excursion
  7427. (goto-char (point-min))
  7428. (while (re-search-forward "^\\*\\*+ " nil t)
  7429. (setq n (- (length (match-string 0)) 2))
  7430. (while (>= (setq n (1- n)) 0)
  7431. (org-demote))
  7432. (end-of-line 1))))))
  7433. (defun org-convert-to-oddeven-levels ()
  7434. "Convert an Org file with only odd levels to one with odd/even levels.
  7435. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7436. file contains a section with an even level, conversion would
  7437. destroy the structure of the file. An error is signaled in this
  7438. case."
  7439. (interactive)
  7440. (goto-char (point-min))
  7441. ;; First check if there are no even levels
  7442. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7443. (org-show-set-visibility 'canonical)
  7444. (error "Not all levels are odd in this file. Conversion not possible"))
  7445. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7446. (let ((outline-regexp org-outline-regexp)
  7447. (outline-level 'org-outline-level)
  7448. (org-odd-levels-only nil) n)
  7449. (save-excursion
  7450. (goto-char (point-min))
  7451. (while (re-search-forward "^\\*\\*+ " nil t)
  7452. (setq n (/ (1- (length (match-string 0))) 2))
  7453. (while (>= (setq n (1- n)) 0)
  7454. (org-promote))
  7455. (end-of-line 1))))))
  7456. (defun org-tr-level (n)
  7457. "Make N odd if required."
  7458. (if org-odd-levels-only (1+ (/ n 2)) n))
  7459. ;;; Vertical tree motion, cutting and pasting of subtrees
  7460. (defun org-move-subtree-up (&optional arg)
  7461. "Move the current subtree up past ARG headlines of the same level."
  7462. (interactive "p")
  7463. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7464. (defun org-move-subtree-down (&optional arg)
  7465. "Move the current subtree down past ARG headlines of the same level."
  7466. (interactive "p")
  7467. (setq arg (prefix-numeric-value arg))
  7468. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7469. 'org-get-last-sibling))
  7470. (ins-point (make-marker))
  7471. (cnt (abs arg))
  7472. (col (current-column))
  7473. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7474. ;; Select the tree
  7475. (org-back-to-heading)
  7476. (setq beg0 (point))
  7477. (save-excursion
  7478. (setq ne-beg (org-back-over-empty-lines))
  7479. (setq beg (point)))
  7480. (save-match-data
  7481. (save-excursion (outline-end-of-heading)
  7482. (setq folded (outline-invisible-p)))
  7483. (progn (org-end-of-subtree nil t)
  7484. (unless (eobp) (backward-char))))
  7485. (outline-next-heading)
  7486. (setq ne-end (org-back-over-empty-lines))
  7487. (setq end (point))
  7488. (goto-char beg0)
  7489. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7490. ;; include less whitespace
  7491. (save-excursion
  7492. (goto-char beg)
  7493. (forward-line (- ne-beg ne-end))
  7494. (setq beg (point))))
  7495. ;; Find insertion point, with error handling
  7496. (while (> cnt 0)
  7497. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7498. (progn (goto-char beg0)
  7499. (user-error "Cannot move past superior level or buffer limit")))
  7500. (setq cnt (1- cnt)))
  7501. (when (> arg 0)
  7502. ;; Moving forward - still need to move over subtree
  7503. (org-end-of-subtree t t)
  7504. (save-excursion
  7505. (org-back-over-empty-lines)
  7506. (or (bolp) (newline))))
  7507. (setq ne-ins (org-back-over-empty-lines))
  7508. (move-marker ins-point (point))
  7509. (setq txt (buffer-substring beg end))
  7510. (org-save-markers-in-region beg end)
  7511. (delete-region beg end)
  7512. (org-remove-empty-overlays-at beg)
  7513. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7514. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7515. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7516. (let ((bbb (point)))
  7517. (insert-before-markers txt)
  7518. (org-reinstall-markers-in-region bbb)
  7519. (move-marker ins-point bbb))
  7520. (or (bolp) (insert "\n"))
  7521. (setq ins-end (point))
  7522. (goto-char ins-point)
  7523. (org-skip-whitespace)
  7524. (when (and (< arg 0)
  7525. (org-first-sibling-p)
  7526. (> ne-ins ne-beg))
  7527. ;; Move whitespace back to beginning
  7528. (save-excursion
  7529. (goto-char ins-end)
  7530. (let ((kill-whole-line t))
  7531. (kill-line (- ne-ins ne-beg)) (point)))
  7532. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7533. (move-marker ins-point nil)
  7534. (if folded
  7535. (outline-hide-subtree)
  7536. (org-show-entry)
  7537. (org-show-children)
  7538. (org-cycle-hide-drawers 'children))
  7539. (org-clean-visibility-after-subtree-move)
  7540. ;; move back to the initial column we were at
  7541. (move-to-column col)))
  7542. (defvar org-subtree-clip ""
  7543. "Clipboard for cut and paste of subtrees.
  7544. This is actually only a copy of the kill, because we use the normal kill
  7545. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7546. (defvar org-subtree-clip-folded nil
  7547. "Was the last copied subtree folded?
  7548. This is used to fold the tree back after pasting.")
  7549. (defun org-cut-subtree (&optional n)
  7550. "Cut the current subtree into the clipboard.
  7551. With prefix arg N, cut this many sequential subtrees.
  7552. This is a short-hand for marking the subtree and then cutting it."
  7553. (interactive "p")
  7554. (org-copy-subtree n 'cut))
  7555. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7556. "Copy the current subtree it in the clipboard.
  7557. With prefix arg N, copy this many sequential subtrees.
  7558. This is a short-hand for marking the subtree and then copying it.
  7559. If CUT is non-nil, actually cut the subtree.
  7560. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7561. of some markers in the region, even if CUT is non-nil. This is
  7562. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7563. (interactive "p")
  7564. (let (beg end folded (beg0 (point)))
  7565. (if (called-interactively-p 'any)
  7566. (org-back-to-heading nil) ; take what looks like a subtree
  7567. (org-back-to-heading t)) ; take what is really there
  7568. (setq beg (point))
  7569. (skip-chars-forward " \t\r\n")
  7570. (save-match-data
  7571. (if nosubtrees
  7572. (outline-next-heading)
  7573. (save-excursion (outline-end-of-heading)
  7574. (setq folded (outline-invisible-p)))
  7575. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7576. (org-end-of-subtree t t)))
  7577. ;; Include the end of an inlinetask
  7578. (when (and (featurep 'org-inlinetask)
  7579. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7580. "END[ \t]*$")))
  7581. (end-of-line))
  7582. (setq end (point))
  7583. (goto-char beg0)
  7584. (when (> end beg)
  7585. (setq org-subtree-clip-folded folded)
  7586. (when (or cut force-store-markers)
  7587. (org-save-markers-in-region beg end))
  7588. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7589. (setq org-subtree-clip (current-kill 0))
  7590. (message "%s: Subtree(s) with %d characters"
  7591. (if cut "Cut" "Copied")
  7592. (length org-subtree-clip)))))
  7593. (defun org-paste-subtree (&optional level tree for-yank remove)
  7594. "Paste the clipboard as a subtree, with modification of headline level.
  7595. The entire subtree is promoted or demoted in order to match a new headline
  7596. level.
  7597. If the cursor is at the beginning of a headline, the same level as
  7598. that headline is used to paste the tree.
  7599. If not, the new level is derived from the *visible* headings
  7600. before and after the insertion point, and taken to be the inferior headline
  7601. level of the two. So if the previous visible heading is level 3 and the
  7602. next is level 4 (or vice versa), level 4 will be used for insertion.
  7603. This makes sure that the subtree remains an independent subtree and does
  7604. not swallow low level entries.
  7605. You can also force a different level, either by using a numeric prefix
  7606. argument, or by inserting the heading marker by hand. For example, if the
  7607. cursor is after \"*****\", then the tree will be shifted to level 5.
  7608. If optional TREE is given, use this text instead of the kill ring.
  7609. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7610. move back over whitespace before inserting, and move point to the end of
  7611. the inserted text when done.
  7612. When REMOVE is non-nil, remove the subtree from the clipboard."
  7613. (interactive "P")
  7614. (setq tree (or tree (and kill-ring (current-kill 0))))
  7615. (unless (org-kill-is-subtree-p tree)
  7616. (user-error "%s"
  7617. (substitute-command-keys
  7618. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7619. (org-with-limited-levels
  7620. (let* ((visp (not (outline-invisible-p)))
  7621. (txt tree)
  7622. (^re_ "\\(\\*+\\)[ \t]*")
  7623. (old-level (if (string-match org-outline-regexp-bol txt)
  7624. (- (match-end 0) (match-beginning 0) 1)
  7625. -1))
  7626. (force-level (cond (level (prefix-numeric-value level))
  7627. ((and (looking-at "[ \t]*$")
  7628. (string-match
  7629. "^\\*+$" (buffer-substring
  7630. (point-at-bol) (point))))
  7631. (- (match-end 0) (match-beginning 0)))
  7632. ((and (bolp)
  7633. (looking-at org-outline-regexp))
  7634. (- (match-end 0) (point) 1))))
  7635. (previous-level (save-excursion
  7636. (condition-case nil
  7637. (progn
  7638. (outline-previous-visible-heading 1)
  7639. (if (looking-at ^re_)
  7640. (- (match-end 0) (match-beginning 0) 1)
  7641. 1))
  7642. (error 1))))
  7643. (next-level (save-excursion
  7644. (condition-case nil
  7645. (progn
  7646. (or (looking-at org-outline-regexp)
  7647. (outline-next-visible-heading 1))
  7648. (if (looking-at ^re_)
  7649. (- (match-end 0) (match-beginning 0) 1)
  7650. 1))
  7651. (error 1))))
  7652. (new-level (or force-level (max previous-level next-level)))
  7653. (shift (if (or (= old-level -1)
  7654. (= new-level -1)
  7655. (= old-level new-level))
  7656. 0
  7657. (- new-level old-level)))
  7658. (delta (if (> shift 0) -1 1))
  7659. (func (if (> shift 0) 'org-demote 'org-promote))
  7660. (org-odd-levels-only nil)
  7661. beg end newend)
  7662. ;; Remove the forced level indicator
  7663. (when force-level
  7664. (delete-region (point-at-bol) (point)))
  7665. ;; Paste
  7666. (beginning-of-line (if (bolp) 1 2))
  7667. (setq beg (point))
  7668. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7669. (insert-before-markers txt)
  7670. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7671. (setq newend (point))
  7672. (org-reinstall-markers-in-region beg)
  7673. (setq end (point))
  7674. (goto-char beg)
  7675. (skip-chars-forward " \t\n\r")
  7676. (setq beg (point))
  7677. (when (and (outline-invisible-p) visp)
  7678. (save-excursion (outline-show-heading)))
  7679. ;; Shift if necessary
  7680. (unless (= shift 0)
  7681. (save-restriction
  7682. (narrow-to-region beg end)
  7683. (while (not (= shift 0))
  7684. (org-map-region func (point-min) (point-max))
  7685. (setq shift (+ delta shift)))
  7686. (goto-char (point-min))
  7687. (setq newend (point-max))))
  7688. (when (or (called-interactively-p 'interactive) for-yank)
  7689. (message "Clipboard pasted as level %d subtree" new-level))
  7690. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7691. kill-ring
  7692. (eq org-subtree-clip (current-kill 0))
  7693. org-subtree-clip-folded)
  7694. ;; The tree was folded before it was killed/copied
  7695. (outline-hide-subtree))
  7696. (and for-yank (goto-char newend))
  7697. (and remove (setq kill-ring (cdr kill-ring))))))
  7698. (defun org-kill-is-subtree-p (&optional txt)
  7699. "Check if the current kill is an outline subtree, or a set of trees.
  7700. Returns nil if kill does not start with a headline, or if the first
  7701. headline level is not the largest headline level in the tree.
  7702. So this will actually accept several entries of equal levels as well,
  7703. which is OK for `org-paste-subtree'.
  7704. If optional TXT is given, check this string instead of the current kill."
  7705. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7706. (re (org-get-limited-outline-regexp))
  7707. (^re (concat "^" re))
  7708. (start-level (and kill
  7709. (string-match
  7710. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7711. kill)
  7712. (- (match-end 2) (match-beginning 2) 1)))
  7713. (start (1+ (or (match-beginning 2) -1))))
  7714. (if (not start-level)
  7715. (progn
  7716. nil) ;; does not even start with a heading
  7717. (catch 'exit
  7718. (while (setq start (string-match ^re kill (1+ start)))
  7719. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7720. (throw 'exit nil)))
  7721. t))))
  7722. (defvar org-markers-to-move nil
  7723. "Markers that should be moved with a cut-and-paste operation.
  7724. Those markers are stored together with their positions relative to
  7725. the start of the region.")
  7726. (defun org-save-markers-in-region (beg end)
  7727. "Check markers in region.
  7728. If these markers are between BEG and END, record their position relative
  7729. to BEG, so that after moving the block of text, we can put the markers back
  7730. into place.
  7731. This function gets called just before an entry or tree gets cut from the
  7732. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7733. called immediately, to move the markers with the entries."
  7734. (setq org-markers-to-move nil)
  7735. (when (featurep 'org-clock)
  7736. (org-clock-save-markers-for-cut-and-paste beg end))
  7737. (when (featurep 'org-agenda)
  7738. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7739. (defun org-check-and-save-marker (marker beg end)
  7740. "Check if MARKER is between BEG and END.
  7741. If yes, remember the marker and the distance to BEG."
  7742. (when (and (marker-buffer marker)
  7743. (equal (marker-buffer marker) (current-buffer))
  7744. (>= marker beg) (< marker end))
  7745. (push (cons marker (- marker beg)) org-markers-to-move)))
  7746. (defun org-reinstall-markers-in-region (beg)
  7747. "Move all remembered markers to their position relative to BEG."
  7748. (dolist (x org-markers-to-move)
  7749. (move-marker (car x) (+ beg (cdr x))))
  7750. (setq org-markers-to-move nil))
  7751. (defun org-narrow-to-subtree ()
  7752. "Narrow buffer to the current subtree."
  7753. (interactive)
  7754. (save-excursion
  7755. (save-match-data
  7756. (org-with-limited-levels
  7757. (narrow-to-region
  7758. (progn (org-back-to-heading t) (point))
  7759. (progn (org-end-of-subtree t t)
  7760. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7761. (point)))))))
  7762. (defun org-narrow-to-block ()
  7763. "Narrow buffer to the current block."
  7764. (interactive)
  7765. (let* ((case-fold-search t)
  7766. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7767. "^[ \t]*#\\+end_.*")))
  7768. (if blockp
  7769. (narrow-to-region (car blockp) (cdr blockp))
  7770. (user-error "Not in a block"))))
  7771. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7772. "Clone the task (subtree) at point N times.
  7773. The clones will be inserted as siblings.
  7774. In interactive use, the user will be prompted for the number of
  7775. clones to be produced. If the entry has a timestamp, the user
  7776. will also be prompted for a time shift, which may be a repeater
  7777. as used in time stamps, for example `+3d'. To disable this,
  7778. you can call the function with a universal prefix argument.
  7779. When a valid repeater is given and the entry contains any time
  7780. stamps, the clones will become a sequence in time, with time
  7781. stamps in the subtree shifted for each clone produced. If SHIFT
  7782. is nil or the empty string, time stamps will be left alone. The
  7783. ID property of the original subtree is removed.
  7784. In each clone, all the CLOCK entries will be removed. This
  7785. prevents Org from considering that the clocked times overlap.
  7786. If the original subtree did contain time stamps with a repeater,
  7787. the following will happen:
  7788. - the repeater will be removed in each clone
  7789. - an additional clone will be produced, with the current, unshifted
  7790. date(s) in the entry.
  7791. - the original entry will be placed *after* all the clones, with
  7792. repeater intact.
  7793. - the start days in the repeater in the original entry will be shifted
  7794. to past the last clone.
  7795. In this way you can spell out a number of instances of a repeating task,
  7796. and still retain the repeater to cover future instances of the task.
  7797. As described above, N+1 clones are produced when the original
  7798. subtree has a repeater. Setting N to 0, then, can be used to
  7799. remove the repeater from a subtree and create a shifted clone
  7800. with the original repeater."
  7801. (interactive "nNumber of clones to produce: ")
  7802. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7803. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7804. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7805. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7806. (shift
  7807. (or shift
  7808. (if (and (not (equal current-prefix-arg '(4)))
  7809. (save-excursion
  7810. (goto-char beg)
  7811. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7812. (read-from-minibuffer
  7813. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7814. ""))) ;No time shift
  7815. (doshift
  7816. (and (org-string-nw-p shift)
  7817. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7818. shift)
  7819. (user-error "Invalid shift specification %s" shift)))))
  7820. (goto-char end-of-tree)
  7821. (unless (bolp) (insert "\n"))
  7822. (let* ((end (point))
  7823. (template (buffer-substring beg end))
  7824. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7825. (shift-what (pcase (and doshift (match-string 2 shift))
  7826. (`nil nil)
  7827. ("d" 'day)
  7828. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7829. ("m" 'month)
  7830. ("y" 'year)
  7831. (_ (error "Unsupported time unit"))))
  7832. (nmin 1)
  7833. (nmax n)
  7834. (n-no-remove -1)
  7835. (idprop (org-entry-get nil "ID")))
  7836. (when (and doshift
  7837. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7838. template))
  7839. (delete-region beg end)
  7840. (setq end beg)
  7841. (setq nmin 0)
  7842. (setq nmax (1+ nmax))
  7843. (setq n-no-remove nmax))
  7844. (goto-char end)
  7845. (cl-loop for n from nmin to nmax do
  7846. (insert
  7847. ;; Prepare clone.
  7848. (with-temp-buffer
  7849. (insert template)
  7850. (org-mode)
  7851. (goto-char (point-min))
  7852. (org-show-subtree)
  7853. (and idprop (if org-clone-delete-id
  7854. (org-entry-delete nil "ID")
  7855. (org-id-get-create t)))
  7856. (unless (= n 0)
  7857. (while (re-search-forward org-clock-line-re nil t)
  7858. (delete-region (line-beginning-position)
  7859. (line-beginning-position 2)))
  7860. (goto-char (point-min))
  7861. (while (re-search-forward org-drawer-regexp nil t)
  7862. (org-remove-empty-drawer-at (point))))
  7863. (goto-char (point-min))
  7864. (when doshift
  7865. (while (re-search-forward org-ts-regexp-both nil t)
  7866. (org-timestamp-change (* n shift-n) shift-what))
  7867. (unless (= n n-no-remove)
  7868. (goto-char (point-min))
  7869. (while (re-search-forward org-ts-regexp nil t)
  7870. (save-excursion
  7871. (goto-char (match-beginning 0))
  7872. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7873. (delete-region (match-beginning 1) (match-end 1)))))))
  7874. (buffer-string)))))
  7875. (goto-char beg)))
  7876. ;;; Outline Sorting
  7877. (defun org-sort (&optional with-case)
  7878. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7879. Optional argument WITH-CASE means sort case-sensitively."
  7880. (interactive "P")
  7881. (org-call-with-arg
  7882. (cond ((org-at-table-p) #'org-table-sort-lines)
  7883. ((org-at-item-p) #'org-sort-list)
  7884. (t #'org-sort-entries))
  7885. with-case))
  7886. (defun org-sort-remove-invisible (s)
  7887. "Remove invisible part of links and emphasis markers from string S."
  7888. (remove-text-properties 0 (length s) org-rm-props s)
  7889. (replace-regexp-in-string
  7890. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7891. (replace-regexp-in-string
  7892. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7893. (org-link-display-format s)
  7894. t t) t t))
  7895. (defvar org-priority-regexp) ; defined later in the file
  7896. (defvar org-after-sorting-entries-or-items-hook nil
  7897. "Hook that is run after a bunch of entries or items have been sorted.
  7898. When children are sorted, the cursor is in the parent line when this
  7899. hook gets called. When a region or a plain list is sorted, the cursor
  7900. will be in the first entry of the sorted region/list.")
  7901. (defun org-sort-entries
  7902. (&optional with-case sorting-type getkey-func compare-func property
  7903. interactive?)
  7904. "Sort entries on a certain level of an outline tree.
  7905. If there is an active region, the entries in the region are sorted.
  7906. Else, if the cursor is before the first entry, sort the top-level items.
  7907. Else, the children of the entry at point are sorted.
  7908. Sorting can be alphabetically, numerically, by date/time as given by
  7909. a time stamp, by a property, by priority order, or by a custom function.
  7910. The command prompts for the sorting type unless it has been given to the
  7911. function through the SORTING-TYPE argument, which needs to be a character,
  7912. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7913. the precise meaning of each character:
  7914. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7915. c By creation time, which is assumed to be the first inactive time stamp
  7916. at the beginning of a line.
  7917. d By deadline date/time.
  7918. k By clocking time.
  7919. n Numerically, by converting the beginning of the entry/item to a number.
  7920. o By order of TODO keywords.
  7921. p By priority according to the cookie.
  7922. r By the value of a property.
  7923. s By scheduled date/time.
  7924. t By date/time, either the first active time stamp in the entry, or, if
  7925. none exist, by the first inactive one.
  7926. Capital letters will reverse the sort order.
  7927. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7928. called with point at the beginning of the record. It must return a
  7929. value that is compatible with COMPARE-FUNC, the function used to
  7930. compare entries.
  7931. Comparing entries ignores case by default. However, with an optional argument
  7932. WITH-CASE, the sorting considers case as well.
  7933. Sorting is done against the visible part of the headlines, it ignores hidden
  7934. links.
  7935. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7936. A non-nil value for INTERACTIVE? is used to signal that this
  7937. function is being called interactively."
  7938. (interactive (list current-prefix-arg nil nil nil nil t))
  7939. (let ((case-func (if with-case 'identity 'downcase))
  7940. (cmstr
  7941. ;; The clock marker is lost when using `sort-subr', let's
  7942. ;; store the clocking string.
  7943. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  7944. (save-excursion
  7945. (goto-char org-clock-marker)
  7946. (buffer-substring-no-properties (line-beginning-position)
  7947. (point)))))
  7948. start beg end stars re re2
  7949. txt what tmp)
  7950. ;; Find beginning and end of region to sort
  7951. (cond
  7952. ((org-region-active-p)
  7953. ;; we will sort the region
  7954. (setq end (region-end)
  7955. what "region")
  7956. (goto-char (region-beginning))
  7957. (unless (org-at-heading-p) (outline-next-heading))
  7958. (setq start (point)))
  7959. ((or (org-at-heading-p)
  7960. (ignore-errors (progn (org-back-to-heading) t)))
  7961. ;; we will sort the children of the current headline
  7962. (org-back-to-heading)
  7963. (setq start (point)
  7964. end (progn (org-end-of-subtree t t)
  7965. (or (bolp) (insert "\n"))
  7966. (when (>= (org-back-over-empty-lines) 1)
  7967. (forward-line 1))
  7968. (point))
  7969. what "children")
  7970. (goto-char start)
  7971. (outline-show-subtree)
  7972. (outline-next-heading))
  7973. (t
  7974. ;; we will sort the top-level entries in this file
  7975. (goto-char (point-min))
  7976. (or (org-at-heading-p) (outline-next-heading))
  7977. (setq start (point))
  7978. (goto-char (point-max))
  7979. (beginning-of-line 1)
  7980. (when (looking-at ".*?\\S-")
  7981. ;; File ends in a non-white line
  7982. (end-of-line 1)
  7983. (insert "\n"))
  7984. (setq end (point-max))
  7985. (setq what "top-level")
  7986. (goto-char start)
  7987. (outline-show-all)))
  7988. (setq beg (point))
  7989. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7990. (looking-at "\\(\\*+\\)")
  7991. (setq stars (match-string 1)
  7992. re (concat "^" (regexp-quote stars) " +")
  7993. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7994. txt (buffer-substring beg end))
  7995. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7996. (when (and (not (equal stars "*")) (string-match re2 txt))
  7997. (user-error "Region to sort contains a level above the first entry"))
  7998. (unless sorting-type
  7999. (message
  8000. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8001. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8002. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8003. what)
  8004. (setq sorting-type (read-char-exclusive)))
  8005. (unless getkey-func
  8006. (and (= (downcase sorting-type) ?f)
  8007. (setq getkey-func
  8008. (or (and interactive?
  8009. (org-read-function
  8010. "Function for extracting keys: "))
  8011. (error "Missing key extractor")))))
  8012. (and (= (downcase sorting-type) ?r)
  8013. (not property)
  8014. (setq property
  8015. (completing-read "Property: "
  8016. (mapcar #'list (org-buffer-property-keys t))
  8017. nil t)))
  8018. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8019. (message "Sorting entries...")
  8020. (save-restriction
  8021. (narrow-to-region start end)
  8022. (let ((dcst (downcase sorting-type))
  8023. (case-fold-search nil)
  8024. (now (current-time)))
  8025. (sort-subr
  8026. (/= dcst sorting-type)
  8027. ;; This function moves to the beginning character of the "record" to
  8028. ;; be sorted.
  8029. (lambda nil
  8030. (if (re-search-forward re nil t)
  8031. (goto-char (match-beginning 0))
  8032. (goto-char (point-max))))
  8033. ;; This function moves to the last character of the "record" being
  8034. ;; sorted.
  8035. (lambda nil
  8036. (save-match-data
  8037. (condition-case nil
  8038. (outline-forward-same-level 1)
  8039. (error
  8040. (goto-char (point-max))))))
  8041. ;; This function returns the value that gets sorted against.
  8042. (lambda nil
  8043. (cond
  8044. ((= dcst ?n)
  8045. (if (looking-at org-complex-heading-regexp)
  8046. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8047. nil))
  8048. ((= dcst ?a)
  8049. (if (looking-at org-complex-heading-regexp)
  8050. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8051. nil))
  8052. ((= dcst ?k)
  8053. (or (get-text-property (point) :org-clock-minutes) 0))
  8054. ((= dcst ?t)
  8055. (let ((end (save-excursion (outline-next-heading) (point))))
  8056. (if (or (re-search-forward org-ts-regexp end t)
  8057. (re-search-forward org-ts-regexp-both end t))
  8058. (org-time-string-to-seconds (match-string 0))
  8059. (float-time now))))
  8060. ((= dcst ?c)
  8061. (let ((end (save-excursion (outline-next-heading) (point))))
  8062. (if (re-search-forward
  8063. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8064. end t)
  8065. (org-time-string-to-seconds (match-string 0))
  8066. (float-time now))))
  8067. ((= dcst ?s)
  8068. (let ((end (save-excursion (outline-next-heading) (point))))
  8069. (if (re-search-forward org-scheduled-time-regexp end t)
  8070. (org-time-string-to-seconds (match-string 1))
  8071. (float-time now))))
  8072. ((= dcst ?d)
  8073. (let ((end (save-excursion (outline-next-heading) (point))))
  8074. (if (re-search-forward org-deadline-time-regexp end t)
  8075. (org-time-string-to-seconds (match-string 1))
  8076. (float-time now))))
  8077. ((= dcst ?p)
  8078. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8079. (string-to-char (match-string 2))
  8080. org-default-priority))
  8081. ((= dcst ?r)
  8082. (or (org-entry-get nil property) ""))
  8083. ((= dcst ?o)
  8084. (when (looking-at org-complex-heading-regexp)
  8085. (let* ((m (match-string 2))
  8086. (s (if (member m org-done-keywords) '- '+)))
  8087. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8088. ((= dcst ?f)
  8089. (if getkey-func
  8090. (progn
  8091. (setq tmp (funcall getkey-func))
  8092. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8093. tmp)
  8094. (error "Invalid key function `%s'" getkey-func)))
  8095. (t (error "Invalid sorting type `%c'" sorting-type))))
  8096. nil
  8097. (cond
  8098. ((= dcst ?a) 'string<)
  8099. ((= dcst ?f)
  8100. (or compare-func
  8101. (and interactive?
  8102. (org-read-function
  8103. (concat "Function for comparing keys "
  8104. "(empty for default `sort-subr' predicate): ")
  8105. 'allow-empty))))
  8106. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8107. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8108. ;; Reset the clock marker if needed
  8109. (when cmstr
  8110. (save-excursion
  8111. (goto-char start)
  8112. (search-forward cmstr nil t)
  8113. (move-marker org-clock-marker (point))))
  8114. (message "Sorting entries...done")))
  8115. ;;; The orgstruct minor mode
  8116. ;; Define a minor mode which can be used in other modes in order to
  8117. ;; integrate the Org mode structure editing commands.
  8118. ;; This is really a hack, because the Org mode structure commands use
  8119. ;; keys which normally belong to the major mode. Here is how it
  8120. ;; works: The minor mode defines all the keys necessary to operate the
  8121. ;; structure commands, but wraps the commands into a function which
  8122. ;; tests if the cursor is currently at a headline or a plain list
  8123. ;; item. If that is the case, the structure command is used,
  8124. ;; temporarily setting many Org mode variables like regular
  8125. ;; expressions for filling etc. However, when any of those keys is
  8126. ;; used at a different location, function uses `key-binding' to look
  8127. ;; up if the key has an associated command in another currently active
  8128. ;; keymap (minor modes, major mode, global), and executes that
  8129. ;; command. There might be problems if any of the keys is otherwise
  8130. ;; used as a prefix key.
  8131. (defcustom orgstruct-heading-prefix-regexp ""
  8132. "Regexp that matches the custom prefix of Org headlines in
  8133. orgstruct(++)-mode."
  8134. :group 'org
  8135. :version "24.4"
  8136. :package-version '(Org . "8.3")
  8137. :type 'regexp)
  8138. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8139. (defcustom orgstruct-setup-hook nil
  8140. "Hook run after orgstruct-mode-map is filled."
  8141. :group 'org
  8142. :version "24.4"
  8143. :package-version '(Org . "8.0")
  8144. :type 'hook)
  8145. (defvar orgstruct-initialized nil)
  8146. (defvar org-local-vars nil
  8147. "List of local variables, for use by `orgstruct-mode'.")
  8148. ;;;###autoload
  8149. (define-minor-mode orgstruct-mode
  8150. "Toggle the minor mode `orgstruct-mode'.
  8151. This mode is for using Org mode structure commands in other
  8152. modes. The following keys behave as if Org mode were active, if
  8153. the cursor is on a headline, or on a plain list item (both as
  8154. defined by Org mode)."
  8155. nil " OrgStruct" (make-sparse-keymap)
  8156. (funcall (if orgstruct-mode
  8157. 'add-to-invisibility-spec
  8158. 'remove-from-invisibility-spec)
  8159. '(outline . t))
  8160. (when orgstruct-mode
  8161. (org-load-modules-maybe)
  8162. (unless orgstruct-initialized
  8163. (orgstruct-setup)
  8164. (setq orgstruct-initialized t))))
  8165. ;;;###autoload
  8166. (defun turn-on-orgstruct ()
  8167. "Unconditionally turn on `orgstruct-mode'."
  8168. (orgstruct-mode 1))
  8169. (defvar-local orgstruct-is-++ nil
  8170. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8171. (defvar-local org-fb-vars nil)
  8172. (defun orgstruct++-mode (&optional arg)
  8173. "Toggle `orgstruct-mode', the enhanced version of it.
  8174. In addition to setting orgstruct-mode, this also exports all
  8175. indentation and autofilling variables from Org mode into the
  8176. buffer. It will also recognize item context in multiline items."
  8177. (interactive "P")
  8178. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8179. (if (< arg 1)
  8180. (progn (orgstruct-mode -1)
  8181. (dolist (v org-fb-vars)
  8182. (set (make-local-variable (car v))
  8183. (if (eq (car-safe (cadr v)) 'quote)
  8184. (cl-cadadr v)
  8185. (nth 1 v)))))
  8186. (orgstruct-mode 1)
  8187. (setq org-fb-vars nil)
  8188. (unless org-local-vars
  8189. (setq org-local-vars (org-get-local-variables)))
  8190. (let (var val)
  8191. (dolist (x org-local-vars)
  8192. (when (string-match
  8193. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8194. \\|fill-prefix\\|indent-\\)"
  8195. (symbol-name (car x)))
  8196. (setq var (car x) val (nth 1 x))
  8197. (push (list var `(quote ,(eval var))) org-fb-vars)
  8198. (set (make-local-variable var)
  8199. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8200. (setq-local orgstruct-is-++ t))))
  8201. ;;;###autoload
  8202. (defun turn-on-orgstruct++ ()
  8203. "Unconditionally turn on `orgstruct++-mode'."
  8204. (orgstruct++-mode 1))
  8205. (defun orgstruct-error ()
  8206. "Error when there is no default binding for a structure key."
  8207. (interactive)
  8208. (funcall (if (fboundp 'user-error)
  8209. 'user-error
  8210. 'error)
  8211. "This key has no function outside structure elements"))
  8212. (defun orgstruct-setup ()
  8213. "Setup orgstruct keymap."
  8214. (dolist (cell '((org-demote . t)
  8215. (org-metaleft . t)
  8216. (org-metaright . t)
  8217. (org-promote . t)
  8218. (org-shiftmetaleft . t)
  8219. (org-shiftmetaright . t)
  8220. org-backward-element
  8221. org-backward-heading-same-level
  8222. org-ctrl-c-ret
  8223. org-ctrl-c-minus
  8224. org-ctrl-c-star
  8225. org-cycle
  8226. org-force-cycle-archived
  8227. org-forward-heading-same-level
  8228. org-insert-heading
  8229. org-insert-heading-respect-content
  8230. org-kill-note-or-show-branches
  8231. org-mark-subtree
  8232. org-meta-return
  8233. org-metadown
  8234. org-metaup
  8235. org-narrow-to-subtree
  8236. org-promote-subtree
  8237. org-reveal
  8238. org-shiftdown
  8239. org-shiftleft
  8240. org-shiftmetadown
  8241. org-shiftmetaup
  8242. org-shiftright
  8243. org-shifttab
  8244. org-shifttab
  8245. org-shiftup
  8246. org-show-children
  8247. org-show-subtree
  8248. org-sort
  8249. org-up-element
  8250. outline-demote
  8251. outline-next-visible-heading
  8252. outline-previous-visible-heading
  8253. outline-promote
  8254. outline-up-heading))
  8255. (let ((f (or (car-safe cell) cell))
  8256. (disable-when-heading-prefix (cdr-safe cell)))
  8257. (when (fboundp f)
  8258. (let ((new-bindings))
  8259. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8260. (where-is-internal f outline-mode-map)))
  8261. (push binding new-bindings)
  8262. ;; TODO use local-function-key-map
  8263. (dolist (rep '(("<tab>" . "TAB")
  8264. ("<return>" . "RET")
  8265. ("<escape>" . "ESC")
  8266. ("<delete>" . "DEL")))
  8267. (setq binding (read-kbd-macro
  8268. (let ((case-fold-search))
  8269. (replace-regexp-in-string
  8270. (regexp-quote (cdr rep))
  8271. (car rep)
  8272. (key-description binding)))))
  8273. (cl-pushnew binding new-bindings :test 'equal)))
  8274. (dolist (binding new-bindings)
  8275. (let ((key (lookup-key orgstruct-mode-map binding)))
  8276. (when (or (not key) (numberp key))
  8277. (ignore-errors
  8278. (org-defkey orgstruct-mode-map
  8279. binding
  8280. (orgstruct-make-binding
  8281. f binding disable-when-heading-prefix))))))))))
  8282. (run-hooks 'orgstruct-setup-hook))
  8283. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8284. "Create a function for binding in the structure minor mode.
  8285. FUN is the command to call inside a table. KEY is the key that
  8286. should be checked in for a command to execute outside of tables.
  8287. Non-nil `disable-when-heading-prefix' means to disable the command
  8288. if `orgstruct-heading-prefix-regexp' is not empty."
  8289. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8290. (let ((nname name)
  8291. (i 0))
  8292. (while (fboundp (intern nname))
  8293. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8294. (setq name (intern nname)))
  8295. (eval
  8296. (let ((bindings '((org-heading-regexp
  8297. (concat "^"
  8298. orgstruct-heading-prefix-regexp
  8299. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8300. (org-outline-regexp
  8301. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8302. (org-outline-regexp-bol
  8303. (concat "^" org-outline-regexp))
  8304. (outline-regexp org-outline-regexp)
  8305. (outline-heading-end-regexp "\n")
  8306. (outline-level 'org-outline-level)
  8307. (outline-heading-alist))))
  8308. `(defun ,name (arg)
  8309. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8310. "Outside of structure, run the binding of `"
  8311. (key-description key) "'."
  8312. (when disable-when-heading-prefix
  8313. (concat
  8314. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8315. "back to the default binding due to limitations of Org's implementation of\n"
  8316. "`" (symbol-name fun) "'.")))
  8317. (interactive "p")
  8318. (let* ((disable
  8319. ,(and disable-when-heading-prefix
  8320. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8321. (fallback
  8322. (or disable
  8323. (not
  8324. (let* ,bindings
  8325. (org-context-p 'headline 'item
  8326. ,(when (memq fun
  8327. '(org-insert-heading
  8328. org-insert-heading-respect-content
  8329. org-meta-return))
  8330. '(when orgstruct-is-++
  8331. 'item-body))))))))
  8332. (if fallback
  8333. (let* ((orgstruct-mode)
  8334. (binding
  8335. (let ((key ,key))
  8336. (catch 'exit
  8337. (dolist
  8338. (rep
  8339. '(nil
  8340. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8341. ("<\\([^>]*\\)return>" . "\\1RET")
  8342. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8343. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8344. nil)
  8345. (when rep
  8346. (setq key (read-kbd-macro
  8347. (let ((case-fold-search))
  8348. (replace-regexp-in-string
  8349. (car rep)
  8350. (cdr rep)
  8351. (key-description key))))))
  8352. (when (key-binding key)
  8353. (throw 'exit (key-binding key))))))))
  8354. (if (keymapp binding)
  8355. (org-set-transient-map binding)
  8356. (let ((func (or binding
  8357. (unless disable
  8358. 'orgstruct-error))))
  8359. (when func
  8360. (call-interactively func)))))
  8361. (org-run-like-in-org-mode
  8362. (lambda ()
  8363. (interactive)
  8364. (let* ,bindings
  8365. (call-interactively ',fun)))))))))
  8366. name))
  8367. (defun org-contextualize-keys (alist contexts)
  8368. "Return valid elements in ALIST depending on CONTEXTS.
  8369. `org-agenda-custom-commands' or `org-capture-templates' are the
  8370. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8371. or `org-capture-templates-contexts' are the associated contexts
  8372. definitions."
  8373. (let ((contexts
  8374. ;; normalize contexts
  8375. (mapcar
  8376. (lambda(c) (cond ((listp (cadr c))
  8377. (list (car c) (car c) (nth 1 c)))
  8378. ((string= "" (cadr c))
  8379. (list (car c) (car c) (nth 2 c)))
  8380. (t c)))
  8381. contexts))
  8382. (a alist) r s)
  8383. ;; loop over all commands or templates
  8384. (dolist (c a)
  8385. (let (vrules repl)
  8386. (cond
  8387. ((not (assoc (car c) contexts))
  8388. (push c r))
  8389. ((and (assoc (car c) contexts)
  8390. (setq vrules (org-contextualize-validate-key
  8391. (car c) contexts)))
  8392. (mapc (lambda (vr)
  8393. (unless (equal (car vr) (cadr vr))
  8394. (setq repl vr)))
  8395. vrules)
  8396. (if (not repl) (push c r)
  8397. (push (cadr repl) s)
  8398. (push
  8399. (cons (car c)
  8400. (cdr (or (assoc (cadr repl) alist)
  8401. (error "Undefined key `%s' as contextual replacement for `%s'"
  8402. (cadr repl) (car c)))))
  8403. r))))))
  8404. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8405. (delq
  8406. nil
  8407. (delete-dups
  8408. (mapcar (lambda (x)
  8409. (let ((tpl (car x)))
  8410. (unless (delq
  8411. nil
  8412. (mapcar (lambda (y)
  8413. (equal y tpl))
  8414. s))
  8415. x)))
  8416. (reverse r))))))
  8417. (defun org-contextualize-validate-key (key contexts)
  8418. "Check CONTEXTS for agenda or capture KEY."
  8419. (let (res)
  8420. (dolist (r contexts)
  8421. (dolist (rr (car (last r)))
  8422. (when
  8423. (and (equal key (car r))
  8424. (if (functionp rr) (funcall rr)
  8425. (or (and (eq (car rr) 'in-file)
  8426. (buffer-file-name)
  8427. (string-match (cdr rr) (buffer-file-name)))
  8428. (and (eq (car rr) 'in-mode)
  8429. (string-match (cdr rr) (symbol-name major-mode)))
  8430. (and (eq (car rr) 'in-buffer)
  8431. (string-match (cdr rr) (buffer-name)))
  8432. (when (and (eq (car rr) 'not-in-file)
  8433. (buffer-file-name))
  8434. (not (string-match (cdr rr) (buffer-file-name))))
  8435. (when (eq (car rr) 'not-in-mode)
  8436. (not (string-match (cdr rr) (symbol-name major-mode))))
  8437. (when (eq (car rr) 'not-in-buffer)
  8438. (not (string-match (cdr rr) (buffer-name)))))))
  8439. (push r res))))
  8440. (delete-dups (delq nil res))))
  8441. (defun org-context-p (&rest contexts)
  8442. "Check if local context is any of CONTEXTS.
  8443. Possible values in the list of contexts are `table', `headline', and `item'."
  8444. (let ((pos (point)))
  8445. (goto-char (point-at-bol))
  8446. (prog1 (or (and (memq 'table contexts)
  8447. (looking-at "[ \t]*|"))
  8448. (and (memq 'headline contexts)
  8449. (looking-at org-outline-regexp))
  8450. (and (memq 'item contexts)
  8451. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8452. (and (memq 'item-body contexts)
  8453. (org-in-item-p)))
  8454. (goto-char pos))))
  8455. (defconst org-unique-local-variables
  8456. '(org-element--cache
  8457. org-element--cache-objects
  8458. org-element--cache-sync-keys
  8459. org-element--cache-sync-requests
  8460. org-element--cache-sync-timer)
  8461. "List of local variables that cannot be transferred to another buffer.")
  8462. (defun org-get-local-variables ()
  8463. "Return a list of all local variables in an Org mode buffer."
  8464. (delq nil
  8465. (mapcar
  8466. (lambda (x)
  8467. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8468. (name (car binding)))
  8469. (and (not (get name 'org-state))
  8470. (not (memq name org-unique-local-variables))
  8471. (string-match-p
  8472. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8473. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8474. (symbol-name name))
  8475. binding)))
  8476. (with-temp-buffer
  8477. (org-mode)
  8478. (buffer-local-variables)))))
  8479. (defun org-clone-local-variables (from-buffer &optional regexp)
  8480. "Clone local variables from FROM-BUFFER.
  8481. Optional argument REGEXP selects variables to clone."
  8482. (dolist (pair (buffer-local-variables from-buffer))
  8483. (let ((name (car pair)))
  8484. (when (and (symbolp name)
  8485. (not (memq name org-unique-local-variables))
  8486. (or (null regexp) (string-match regexp (symbol-name name))))
  8487. (set (make-local-variable name) (cdr pair))))))
  8488. ;;;###autoload
  8489. (defun org-run-like-in-org-mode (cmd)
  8490. "Run a command, pretending that the current buffer is in Org mode.
  8491. This will temporarily bind local variables that are typically bound in
  8492. Org mode to the values they have in Org mode, and then interactively
  8493. call CMD."
  8494. (org-load-modules-maybe)
  8495. (unless org-local-vars
  8496. (setq org-local-vars (org-get-local-variables)))
  8497. (let (binds)
  8498. (dolist (var org-local-vars)
  8499. (when (or (not (boundp (car var)))
  8500. (eq (symbol-value (car var))
  8501. (default-value (car var))))
  8502. (push (list (car var) `(quote ,(cadr var))) binds)))
  8503. (eval `(let ,binds
  8504. (call-interactively (quote ,cmd))))))
  8505. (defun org-get-category (&optional pos force-refresh)
  8506. "Get the category applying to position POS."
  8507. (save-match-data
  8508. (when force-refresh (org-refresh-category-properties))
  8509. (let ((pos (or pos (point))))
  8510. (or (get-text-property pos 'org-category)
  8511. (progn (org-refresh-category-properties)
  8512. (get-text-property pos 'org-category))))))
  8513. ;;; Refresh properties
  8514. (defun org-refresh-properties (dprop tprop)
  8515. "Refresh buffer text properties.
  8516. DPROP is the drawer property and TPROP is either the
  8517. corresponding text property to set, or an alist with each element
  8518. being a text property (as a symbol) and a function to apply to
  8519. the value of the drawer property."
  8520. (let* ((case-fold-search t)
  8521. (inhibit-read-only t)
  8522. (inherit? (org-property-inherit-p dprop))
  8523. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8524. (global (and inherit? (org--property-global-value dprop nil))))
  8525. (org-with-silent-modifications
  8526. (org-with-point-at 1
  8527. ;; Set global values (e.g., values defined through
  8528. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8529. (when global (put-text-property (point-min) (point-max) tprop global))
  8530. ;; Set local values.
  8531. (while (re-search-forward property-re nil t)
  8532. (when (org-at-property-p)
  8533. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8534. (outline-next-heading))))))
  8535. (defun org-refresh-property (tprop p &optional inherit)
  8536. "Refresh the buffer text property TPROP from the drawer property P.
  8537. The refresh happens only for the current headline, or the whole
  8538. sub-tree if optional argument INHERIT is non-nil."
  8539. (unless (org-before-first-heading-p)
  8540. (save-excursion
  8541. (org-back-to-heading t)
  8542. (let ((start (point))
  8543. (end (save-excursion
  8544. (if inherit (org-end-of-subtree t t)
  8545. (or (outline-next-heading) (point-max))))))
  8546. (if (symbolp tprop)
  8547. ;; TPROP is a text property symbol.
  8548. (put-text-property start end tprop p)
  8549. ;; TPROP is an alist with (property . function) elements.
  8550. (pcase-dolist (`(,prop . ,f) tprop)
  8551. (put-text-property start end prop (funcall f p))))))))
  8552. (defun org-refresh-category-properties ()
  8553. "Refresh category text properties in the buffer."
  8554. (let ((case-fold-search t)
  8555. (inhibit-read-only t)
  8556. (default-category
  8557. (cond ((null org-category)
  8558. (if buffer-file-name
  8559. (file-name-sans-extension
  8560. (file-name-nondirectory buffer-file-name))
  8561. "???"))
  8562. ((symbolp org-category) (symbol-name org-category))
  8563. (t org-category))))
  8564. (org-with-silent-modifications
  8565. (org-with-wide-buffer
  8566. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8567. ;; This is the default category for the buffer. If none is
  8568. ;; found, fall-back to `org-category' or buffer file name.
  8569. (put-text-property
  8570. (point-min) (point-max)
  8571. 'org-category
  8572. (catch 'buffer-category
  8573. (goto-char (point-max))
  8574. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8575. (let ((element (org-element-at-point)))
  8576. (when (eq (org-element-type element) 'keyword)
  8577. (throw 'buffer-category
  8578. (org-element-property :value element)))))
  8579. default-category))
  8580. ;; Set sub-tree specific categories.
  8581. (goto-char (point-min))
  8582. (let ((regexp (org-re-property "CATEGORY")))
  8583. (while (re-search-forward regexp nil t)
  8584. (let ((value (match-string-no-properties 3)))
  8585. (when (org-at-property-p)
  8586. (put-text-property
  8587. (save-excursion (org-back-to-heading t) (point))
  8588. (save-excursion (org-end-of-subtree t t) (point))
  8589. 'org-category
  8590. value)))))))))
  8591. (defun org-refresh-stats-properties ()
  8592. "Refresh stats text properties in the buffer."
  8593. (org-with-silent-modifications
  8594. (org-with-point-at 1
  8595. (let ((regexp (concat org-outline-regexp-bol
  8596. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8597. (while (re-search-forward regexp nil t)
  8598. (let* ((numerator (string-to-number (match-string 1)))
  8599. (denominator (and (match-end 2)
  8600. (string-to-number (match-string 2))))
  8601. (stats (cond ((not denominator) numerator) ;percent
  8602. ((= denominator 0) 0)
  8603. (t (/ (* numerator 100) denominator)))))
  8604. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8605. 'org-stats stats)))))))
  8606. (defun org-refresh-effort-properties ()
  8607. "Refresh effort properties"
  8608. (org-refresh-properties
  8609. org-effort-property
  8610. '((effort . identity)
  8611. (effort-minutes . org-duration-to-minutes))))
  8612. ;;;; Link Stuff
  8613. ;;; Link abbreviations
  8614. (defun org-link-expand-abbrev (link)
  8615. "Apply replacements as defined in `org-link-abbrev-alist'."
  8616. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8617. (let* ((key (match-string 1 link))
  8618. (as (or (assoc key org-link-abbrev-alist-local)
  8619. (assoc key org-link-abbrev-alist)))
  8620. (tag (and (match-end 2) (match-string 3 link)))
  8621. rpl)
  8622. (if (not as)
  8623. link
  8624. (setq rpl (cdr as))
  8625. (cond
  8626. ((symbolp rpl) (funcall rpl tag))
  8627. ((string-match "%(\\([^)]+\\))" rpl)
  8628. (replace-match
  8629. (save-match-data
  8630. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8631. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8632. ((string-match "%h" rpl)
  8633. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8634. (t (concat rpl tag)))))
  8635. link))
  8636. ;;; Storing and inserting links
  8637. (defvar org-insert-link-history nil
  8638. "Minibuffer history for links inserted with `org-insert-link'.")
  8639. (defvar org-stored-links nil
  8640. "Contains the links stored with `org-store-link'.")
  8641. (defvar org-store-link-plist nil
  8642. "Plist with info about the most recently link created with `org-store-link'.")
  8643. (defun org-store-link-functions ()
  8644. "Return a list of functions that are called to create and store a link.
  8645. The functions defined in the :store property of
  8646. `org-link-parameters'.
  8647. Each function will be called in turn until one returns a non-nil
  8648. value. Each function should check if it is responsible for
  8649. creating this link (for example by looking at the major mode).
  8650. If not, it must exit and return nil. If yes, it should return
  8651. a non-nil value after calling `org-store-link-props' with a list
  8652. of properties and values. Special properties are:
  8653. :type The link prefix, like \"http\". This must be given.
  8654. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8655. This is obligatory as well.
  8656. :description Optional default description for the second pair
  8657. of brackets in an Org mode link. The user can still change
  8658. this when inserting this link into an Org mode buffer.
  8659. In addition to these, any additional properties can be specified
  8660. and then used in capture templates."
  8661. (cl-loop for link in org-link-parameters
  8662. with store-func
  8663. do (setq store-func (org-link-get-parameter (car link) :store))
  8664. if store-func
  8665. collect store-func))
  8666. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8667. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8668. ;;;###autoload
  8669. (defun org-store-link (arg)
  8670. "Store an org-link to the current location.
  8671. \\<org-mode-map>
  8672. This link is added to `org-stored-links' and can later be inserted
  8673. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8674. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8675. A single
  8676. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8677. `org-gnus-prefer-web-links' for links to Usenet articles.
  8678. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8679. skipping storing functions that are not
  8680. part of Org core.
  8681. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8682. prefix ARG forces storing a link for each line in the
  8683. active region."
  8684. (interactive "P")
  8685. (org-load-modules-maybe)
  8686. (if (and (equal arg '(64)) (org-region-active-p))
  8687. (save-excursion
  8688. (let ((end (region-end)))
  8689. (goto-char (region-beginning))
  8690. (set-mark (point))
  8691. (while (< (point-at-eol) end)
  8692. (move-end-of-line 1) (activate-mark)
  8693. (let (current-prefix-arg)
  8694. (call-interactively 'org-store-link))
  8695. (move-beginning-of-line 2)
  8696. (set-mark (point)))))
  8697. (setq org-store-link-plist nil)
  8698. (let (link cpltxt desc description search
  8699. txt custom-id agenda-link sfuns sfunsn)
  8700. (cond
  8701. ;; Store a link using an external link type
  8702. ((and (not (equal arg '(16)))
  8703. (setq sfuns
  8704. (delq
  8705. nil (mapcar (lambda (f)
  8706. (let (fs) (if (funcall f) (push f fs))))
  8707. (org-store-link-functions)))
  8708. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8709. (or (and (cdr sfuns)
  8710. (funcall (intern
  8711. (completing-read
  8712. "Which function for creating the link? "
  8713. sfunsn nil t (car sfunsn)))))
  8714. (funcall (caar sfuns)))
  8715. (setq link (plist-get org-store-link-plist :link)
  8716. desc (or (plist-get org-store-link-plist
  8717. :description)
  8718. link))))
  8719. ;; Store a link from a source code buffer.
  8720. ((org-src-edit-buffer-p)
  8721. (let ((coderef-format (org-src-coderef-format)))
  8722. (cond ((save-excursion
  8723. (beginning-of-line)
  8724. (looking-at (org-src-coderef-regexp coderef-format)))
  8725. (setq link (format "(%s)" (match-string-no-properties 3))))
  8726. ((called-interactively-p 'any)
  8727. (let ((label (read-string "Code line label: ")))
  8728. (end-of-line)
  8729. (setq link (format coderef-format label))
  8730. (let ((gc (- 79 (length link))))
  8731. (if (< (current-column) gc)
  8732. (org-move-to-column gc t)
  8733. (insert " ")))
  8734. (insert link)
  8735. (setq link (concat "(" label ")"))
  8736. (setq desc nil)))
  8737. (t (setq link nil)))))
  8738. ;; We are in the agenda, link to referenced location
  8739. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8740. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8741. (get-text-property (point) 'org-marker))))
  8742. (when m
  8743. (org-with-point-at m
  8744. (setq agenda-link
  8745. (if (called-interactively-p 'any)
  8746. (call-interactively 'org-store-link)
  8747. (org-store-link nil)))))))
  8748. ((eq major-mode 'calendar-mode)
  8749. (let ((cd (calendar-cursor-to-date)))
  8750. (setq link
  8751. (format-time-string
  8752. (car org-time-stamp-formats)
  8753. (apply 'encode-time
  8754. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8755. nil nil nil))))
  8756. (org-store-link-props :type "calendar" :date cd)))
  8757. ((eq major-mode 'help-mode)
  8758. (setq link (concat "help:" (save-excursion
  8759. (goto-char (point-min))
  8760. (looking-at "^[^ ]+")
  8761. (match-string 0))))
  8762. (org-store-link-props :type "help"))
  8763. ((eq major-mode 'w3-mode)
  8764. (setq cpltxt (if (and (buffer-name)
  8765. (not (string-match "Untitled" (buffer-name))))
  8766. (buffer-name)
  8767. (url-view-url t))
  8768. link (url-view-url t))
  8769. (org-store-link-props :type "w3" :url (url-view-url t)))
  8770. ((eq major-mode 'image-mode)
  8771. (setq cpltxt (concat "file:"
  8772. (abbreviate-file-name buffer-file-name))
  8773. link cpltxt)
  8774. (org-store-link-props :type "image" :file buffer-file-name))
  8775. ;; In dired, store a link to the file of the current line
  8776. ((derived-mode-p 'dired-mode)
  8777. (let ((file (dired-get-filename nil t)))
  8778. (setq file (if file
  8779. (abbreviate-file-name
  8780. (expand-file-name (dired-get-filename nil t)))
  8781. ;; otherwise, no file so use current directory.
  8782. default-directory))
  8783. (setq cpltxt (concat "file:" file)
  8784. link cpltxt)))
  8785. ((setq search (run-hook-with-args-until-success
  8786. 'org-create-file-search-functions))
  8787. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8788. "::" search))
  8789. (setq cpltxt (or description link)))
  8790. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8791. (org-with-limited-levels
  8792. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8793. (cond
  8794. ;; Store a link using the target at point
  8795. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8796. (setq cpltxt
  8797. (concat "file:"
  8798. (abbreviate-file-name
  8799. (buffer-file-name (buffer-base-buffer)))
  8800. "::" (match-string 1))
  8801. link cpltxt))
  8802. ((and (featurep 'org-id)
  8803. (or (eq org-id-link-to-org-use-id t)
  8804. (and (called-interactively-p 'any)
  8805. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8806. (and (eq org-id-link-to-org-use-id
  8807. 'create-if-interactive-and-no-custom-id)
  8808. (not custom-id))))
  8809. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8810. ;; Store a link using the ID at point
  8811. (setq link (condition-case nil
  8812. (prog1 (org-id-store-link)
  8813. (setq desc (or (plist-get org-store-link-plist
  8814. :description)
  8815. "")))
  8816. (error
  8817. ;; Probably before first headline, link only to file
  8818. (concat "file:"
  8819. (abbreviate-file-name
  8820. (buffer-file-name (buffer-base-buffer))))))))
  8821. (t
  8822. ;; Just link to current headline
  8823. (setq cpltxt (concat "file:"
  8824. (abbreviate-file-name
  8825. (buffer-file-name (buffer-base-buffer)))))
  8826. ;; Add a context search string
  8827. (when (org-xor org-context-in-file-links
  8828. (equal arg '(4)))
  8829. (let* ((element (org-element-at-point))
  8830. (name (org-element-property :name element)))
  8831. (setq txt (cond
  8832. ((org-at-heading-p) nil)
  8833. (name)
  8834. ((org-region-active-p)
  8835. (buffer-substring (region-beginning) (region-end)))))
  8836. (when (or (null txt) (string-match "\\S-" txt))
  8837. (setq cpltxt
  8838. (concat cpltxt "::"
  8839. (condition-case nil
  8840. (org-make-org-heading-search-string txt)
  8841. (error "")))
  8842. desc (or name
  8843. (nth 4 (ignore-errors (org-heading-components)))
  8844. "NONE")))))
  8845. (when (string-match "::\\'" cpltxt)
  8846. (setq cpltxt (substring cpltxt 0 -2)))
  8847. (setq link cpltxt)))))
  8848. ((buffer-file-name (buffer-base-buffer))
  8849. ;; Just link to this file here.
  8850. (setq cpltxt (concat "file:"
  8851. (abbreviate-file-name
  8852. (buffer-file-name (buffer-base-buffer)))))
  8853. ;; Add a context string.
  8854. (when (org-xor org-context-in-file-links
  8855. (equal arg '(4)))
  8856. (setq txt (if (org-region-active-p)
  8857. (buffer-substring (region-beginning) (region-end))
  8858. (buffer-substring (point-at-bol) (point-at-eol))))
  8859. ;; Only use search option if there is some text.
  8860. (when (string-match "\\S-" txt)
  8861. (setq cpltxt
  8862. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8863. desc "NONE")))
  8864. (setq link cpltxt))
  8865. ((called-interactively-p 'interactive)
  8866. (user-error "No method for storing a link from this buffer"))
  8867. (t (setq link nil)))
  8868. ;; We're done setting link and desc, clean up
  8869. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8870. (setq link (or link cpltxt)
  8871. desc (or desc cpltxt))
  8872. (cond ((not desc))
  8873. ((equal desc "NONE") (setq desc nil))
  8874. (t (setq desc
  8875. (replace-regexp-in-string
  8876. org-bracket-link-analytic-regexp
  8877. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8878. desc))))
  8879. ;; Return the link
  8880. (if (not (and (or (called-interactively-p 'any)
  8881. executing-kbd-macro)
  8882. link))
  8883. (or agenda-link (and link (org-make-link-string link desc)))
  8884. (push (list link desc) org-stored-links)
  8885. (message "Stored: %s" (or desc link))
  8886. (when custom-id
  8887. (setq link (concat "file:" (abbreviate-file-name
  8888. (buffer-file-name)) "::#" custom-id))
  8889. (push (list link desc) org-stored-links))
  8890. (car org-stored-links)))))
  8891. (defun org-store-link-props (&rest plist)
  8892. "Store link properties, extract names, addresses and dates."
  8893. (let ((x (plist-get plist :from)))
  8894. (when x
  8895. (let ((adr (mail-extract-address-components x)))
  8896. (setq plist (plist-put plist :fromname (car adr)))
  8897. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8898. (let ((x (plist-get plist :to)))
  8899. (when x
  8900. (let ((adr (mail-extract-address-components x)))
  8901. (setq plist (plist-put plist :toname (car adr)))
  8902. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8903. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8904. (when x
  8905. (setq plist (plist-put plist :date-timestamp
  8906. (format-time-string
  8907. (org-time-stamp-format t) x)))
  8908. (setq plist (plist-put plist :date-timestamp-inactive
  8909. (format-time-string
  8910. (org-time-stamp-format t t) x)))))
  8911. (let ((from (plist-get plist :from))
  8912. (to (plist-get plist :to)))
  8913. (when (and from to org-from-is-user-regexp)
  8914. (setq plist
  8915. (plist-put plist :fromto
  8916. (if (string-match org-from-is-user-regexp from)
  8917. (concat "to %t")
  8918. (concat "from %f"))))))
  8919. (setq org-store-link-plist plist))
  8920. (defun org-add-link-props (&rest plist)
  8921. "Add these properties to the link property list."
  8922. (let (key value)
  8923. (while plist
  8924. (setq key (pop plist) value (pop plist))
  8925. (setq org-store-link-plist
  8926. (plist-put org-store-link-plist key value)))))
  8927. (defun org-email-link-description (&optional fmt)
  8928. "Return the description part of an email link.
  8929. This takes information from `org-store-link-plist' and formats it
  8930. according to FMT (default from `org-email-link-description-format')."
  8931. (setq fmt (or fmt org-email-link-description-format))
  8932. (let* ((p org-store-link-plist)
  8933. (to (plist-get p :toaddress))
  8934. (from (plist-get p :fromaddress))
  8935. (table
  8936. (list
  8937. (cons "%c" (plist-get p :fromto))
  8938. (cons "%F" (plist-get p :from))
  8939. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8940. (cons "%T" (plist-get p :to))
  8941. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8942. (cons "%s" (plist-get p :subject))
  8943. (cons "%d" (plist-get p :date))
  8944. (cons "%m" (plist-get p :message-id)))))
  8945. (when (string-match "%c" fmt)
  8946. ;; Check if the user wrote this message
  8947. (if (and org-from-is-user-regexp from to
  8948. (save-match-data (string-match org-from-is-user-regexp from)))
  8949. (setq fmt (replace-match "to %t" t t fmt))
  8950. (setq fmt (replace-match "from %f" t t fmt))))
  8951. (org-replace-escapes fmt table)))
  8952. (defun org-make-org-heading-search-string (&optional string)
  8953. "Make search string for the current headline or STRING."
  8954. (let ((s (or string
  8955. (and (derived-mode-p 'org-mode)
  8956. (save-excursion
  8957. (org-back-to-heading t)
  8958. (org-element-property :raw-value (org-element-at-point))))))
  8959. (lines org-context-in-file-links))
  8960. (or string (setq s (concat "*" s))) ; Add * for headlines
  8961. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8962. (when (and string (integerp lines) (> lines 0))
  8963. (let ((slines (org-split-string s "\n")))
  8964. (when (< lines (length slines))
  8965. (setq s (mapconcat
  8966. 'identity
  8967. (reverse (nthcdr (- (length slines) lines)
  8968. (reverse slines))) "\n")))))
  8969. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  8970. (defun org-make-link-string (link &optional description)
  8971. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8972. (unless (org-string-nw-p link) (error "Empty link"))
  8973. (let ((uri (cond ((string-match org-link-types-re link)
  8974. (concat (match-string 1 link)
  8975. (org-link-escape (substring link (match-end 1)))))
  8976. ;; For readability, url-encode internal links only
  8977. ;; when absolutely needed (i.e, when they contain
  8978. ;; square brackets). File links however, are
  8979. ;; encoded since, e.g., spaces are significant.
  8980. ((or (file-name-absolute-p link)
  8981. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8982. (org-link-escape link))
  8983. (t link)))
  8984. (description
  8985. (and (org-string-nw-p description)
  8986. ;; Remove brackets from description, as they are fatal.
  8987. (replace-regexp-in-string
  8988. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8989. (org-trim description)))))
  8990. (format "[[%s]%s]"
  8991. uri
  8992. (if description (format "[%s]" description) ""))))
  8993. (defconst org-link-escape-chars
  8994. ;;%20 %5B %5D %25
  8995. '(?\s ?\[ ?\] ?%)
  8996. "List of characters that should be escaped in a link when stored to Org.
  8997. This is the list that is used for internal purposes.")
  8998. (defun org-link-escape (text &optional table merge)
  8999. "Return percent escaped representation of TEXT.
  9000. TEXT is a string with the text to escape.
  9001. Optional argument TABLE is a list with characters that should be
  9002. escaped. When nil, `org-link-escape-chars' is used.
  9003. If optional argument MERGE is set, merge TABLE into
  9004. `org-link-escape-chars'."
  9005. (let ((characters-to-encode
  9006. (cond ((null table) org-link-escape-chars)
  9007. (merge (append org-link-escape-chars table))
  9008. (t table))))
  9009. (mapconcat
  9010. (lambda (c)
  9011. (if (or (memq c characters-to-encode)
  9012. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9013. (mapconcat (lambda (e) (format "%%%.2X" e))
  9014. (or (encode-coding-char c 'utf-8)
  9015. (error "Unable to percent escape character: %c" c))
  9016. "")
  9017. (char-to-string c)))
  9018. text "")))
  9019. (defun org-link-unescape (str)
  9020. "Unhex hexified Unicode parts in string STR.
  9021. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9022. reciprocal of `org-link-escape', which see."
  9023. (if (org-string-nw-p str)
  9024. (replace-regexp-in-string
  9025. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9026. str))
  9027. (defun org-link-unescape-compound (hex)
  9028. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9029. Note: this function also decodes single byte encodings like
  9030. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9031. (save-match-data
  9032. (let* ((bytes (cdr (split-string hex "%")))
  9033. (ret "")
  9034. (eat 0)
  9035. (sum 0))
  9036. (while bytes
  9037. (let* ((val (string-to-number (pop bytes) 16))
  9038. (shift-xor
  9039. (if (= 0 eat)
  9040. (cond
  9041. ((>= val 252) (cons 6 252))
  9042. ((>= val 248) (cons 5 248))
  9043. ((>= val 240) (cons 4 240))
  9044. ((>= val 224) (cons 3 224))
  9045. ((>= val 192) (cons 2 192))
  9046. (t (cons 0 0)))
  9047. (cons 6 128))))
  9048. (when (>= val 192) (setq eat (car shift-xor)))
  9049. (setq val (logxor val (cdr shift-xor)))
  9050. (setq sum (+ (lsh sum (car shift-xor)) val))
  9051. (when (> eat 0) (setq eat (- eat 1)))
  9052. (cond
  9053. ((= 0 eat) ;multi byte
  9054. (setq ret (concat ret (char-to-string sum)))
  9055. (setq sum 0))
  9056. ((not bytes) ; single byte(s)
  9057. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9058. ret)))
  9059. (defun org-link-unescape-single-byte-sequence (hex)
  9060. "Unhexify hex-encoded single byte character sequences."
  9061. (mapconcat (lambda (byte)
  9062. (char-to-string (string-to-number byte 16)))
  9063. (cdr (split-string hex "%")) ""))
  9064. (defun org-xor (a b)
  9065. "Exclusive or."
  9066. (if a (not b) b))
  9067. (defun org-fixup-message-id-for-http (s)
  9068. "Replace special characters in a message id, so it can be used in an http query."
  9069. (when (string-match "%" s)
  9070. (setq s (mapconcat (lambda (c)
  9071. (if (eq c ?%)
  9072. "%25"
  9073. (char-to-string c)))
  9074. s "")))
  9075. (while (string-match "<" s)
  9076. (setq s (replace-match "%3C" t t s)))
  9077. (while (string-match ">" s)
  9078. (setq s (replace-match "%3E" t t s)))
  9079. (while (string-match "@" s)
  9080. (setq s (replace-match "%40" t t s)))
  9081. s)
  9082. (defun org-link-prettify (link)
  9083. "Return a human-readable representation of LINK.
  9084. The car of LINK must be a raw link.
  9085. The cdr of LINK must be either a link description or nil."
  9086. (let ((desc (or (cadr link) "<no description>")))
  9087. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9088. "<" (car link) ">")))
  9089. ;;;###autoload
  9090. (defun org-insert-link-global ()
  9091. "Insert a link like Org mode does.
  9092. This command can be called in any mode to insert a link in Org syntax."
  9093. (interactive)
  9094. (org-load-modules-maybe)
  9095. (org-run-like-in-org-mode 'org-insert-link))
  9096. (defun org-insert-all-links (arg &optional pre post)
  9097. "Insert all links in `org-stored-links'.
  9098. When a universal prefix, do not delete the links from `org-stored-links'.
  9099. When `ARG' is a number, insert the last N link(s).
  9100. `PRE' and `POST' are optional arguments to define a string to
  9101. prepend or to append."
  9102. (interactive "P")
  9103. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9104. (links (copy-sequence org-stored-links))
  9105. (pr (or pre "- "))
  9106. (po (or post "\n"))
  9107. (cnt 1) l)
  9108. (if (null org-stored-links)
  9109. (message "No link to insert")
  9110. (while (and (or (listp arg) (>= arg cnt))
  9111. (setq l (if (listp arg)
  9112. (pop links)
  9113. (pop org-stored-links))))
  9114. (setq cnt (1+ cnt))
  9115. (insert pr)
  9116. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9117. (insert po)))))
  9118. (defun org-insert-last-stored-link (arg)
  9119. "Insert the last link stored in `org-stored-links'."
  9120. (interactive "p")
  9121. (org-insert-all-links arg "" "\n"))
  9122. (defun org-link-fontify-links-to-this-file ()
  9123. "Fontify links to the current file in `org-stored-links'."
  9124. (let ((f (buffer-file-name)) a b)
  9125. (setq a (mapcar (lambda(l)
  9126. (let ((ll (car l)))
  9127. (when (and (string-match "^file:\\(.+\\)::" ll)
  9128. (equal f (expand-file-name (match-string 1 ll))))
  9129. ll)))
  9130. org-stored-links))
  9131. (when (featurep 'org-id)
  9132. (setq b (mapcar (lambda(l)
  9133. (let ((ll (car l)))
  9134. (when (and (string-match "^id:\\(.+\\)$" ll)
  9135. (equal f (expand-file-name
  9136. (or (org-id-find-id-file
  9137. (match-string 1 ll)) ""))))
  9138. ll)))
  9139. org-stored-links)))
  9140. (mapcar (lambda(l)
  9141. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9142. (delq nil (append a b)))))
  9143. (defvar org--links-history nil)
  9144. (defun org-insert-link (&optional complete-file link-location default-description)
  9145. "Insert a link. At the prompt, enter the link.
  9146. Completion can be used to insert any of the link protocol prefixes in use.
  9147. The history can be used to select a link previously stored with
  9148. `org-store-link'. When the empty string is entered (i.e. if you just
  9149. press `RET' at the prompt), the link defaults to the most recently
  9150. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9151. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9152. You will also be prompted for a description, and if one is given, it will
  9153. be displayed in the buffer instead of the link.
  9154. If there is already a link at point, this command will allow you to edit
  9155. link and description parts.
  9156. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9157. file name can be
  9158. selected using completion. The path to the file will be relative to the
  9159. current directory if the file is in the current directory or a subdirectory.
  9160. Otherwise, the link will be the absolute path as completed in the minibuffer
  9161. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9162. option `org-link-file-path-type'.
  9163. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9164. absolute path even if the file is in
  9165. the current directory or below.
  9166. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9167. prefix negates `org-keep-stored-link-after-insertion'.
  9168. If `org-make-link-description-function' is non-nil, this function will be
  9169. called with the link target, and the result will be the default
  9170. link description.
  9171. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9172. the link location instead of reading one interactively.
  9173. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9174. as the default description."
  9175. (interactive "P")
  9176. (let* ((wcf (current-window-configuration))
  9177. (origbuf (current-buffer))
  9178. (region (when (org-region-active-p)
  9179. (buffer-substring (region-beginning) (region-end))))
  9180. (remove (and region (list (region-beginning) (region-end))))
  9181. (desc region)
  9182. (link link-location)
  9183. (abbrevs org-link-abbrev-alist-local)
  9184. entry all-prefixes auto-desc)
  9185. (cond
  9186. (link-location) ; specified by arg, just use it.
  9187. ((org-in-regexp org-bracket-link-regexp 1)
  9188. ;; We do have a link at point, and we are going to edit it.
  9189. (setq remove (list (match-beginning 0) (match-end 0)))
  9190. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9191. (setq link (read-string "Link: "
  9192. (org-link-unescape
  9193. (match-string-no-properties 1)))))
  9194. ((or (org-in-regexp org-angle-link-re)
  9195. (org-in-regexp org-plain-link-re))
  9196. ;; Convert to bracket link
  9197. (setq remove (list (match-beginning 0) (match-end 0))
  9198. link (read-string "Link: "
  9199. (org-unbracket-string "<" ">" (match-string 0)))))
  9200. ((member complete-file '((4) (16)))
  9201. ;; Completing read for file names.
  9202. (setq link (org-file-complete-link complete-file)))
  9203. (t
  9204. ;; Read link, with completion for stored links.
  9205. (org-link-fontify-links-to-this-file)
  9206. (org-switch-to-buffer-other-window "*Org Links*")
  9207. (with-current-buffer "*Org Links*"
  9208. (erase-buffer)
  9209. (insert "Insert a link.
  9210. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9211. (when org-stored-links
  9212. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9213. (insert (mapconcat 'org-link-prettify
  9214. (reverse org-stored-links) "\n")))
  9215. (goto-char (point-min)))
  9216. (let ((cw (selected-window)))
  9217. (select-window (get-buffer-window "*Org Links*" 'visible))
  9218. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9219. (unless (pos-visible-in-window-p (point-max))
  9220. (org-fit-window-to-buffer))
  9221. (and (window-live-p cw) (select-window cw)))
  9222. (setq all-prefixes (append (mapcar 'car abbrevs)
  9223. (mapcar 'car org-link-abbrev-alist)
  9224. (org-link-types)))
  9225. (unwind-protect
  9226. ;; Fake a link history, containing the stored links.
  9227. (let ((org--links-history
  9228. (append (mapcar #'car org-stored-links)
  9229. org-insert-link-history)))
  9230. (setq link
  9231. (org-completing-read
  9232. "Link: "
  9233. (append
  9234. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9235. (mapcar #'car org-stored-links))
  9236. nil nil nil
  9237. 'org--links-history
  9238. (caar org-stored-links)))
  9239. (unless (org-string-nw-p link) (user-error "No link selected"))
  9240. (dolist (l org-stored-links)
  9241. (when (equal link (cadr l))
  9242. (setq link (car l))
  9243. (setq auto-desc t)))
  9244. (when (or (member link all-prefixes)
  9245. (and (equal ":" (substring link -1))
  9246. (member (substring link 0 -1) all-prefixes)
  9247. (setq link (substring link 0 -1))))
  9248. (setq link (with-current-buffer origbuf
  9249. (org-link-try-special-completion link)))))
  9250. (set-window-configuration wcf)
  9251. (kill-buffer "*Org Links*"))
  9252. (setq entry (assoc link org-stored-links))
  9253. (or entry (push link org-insert-link-history))
  9254. (setq desc (or desc (nth 1 entry)))))
  9255. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9256. (not org-keep-stored-link-after-insertion))
  9257. (setq org-stored-links (delq (assoc link org-stored-links)
  9258. org-stored-links)))
  9259. (when (and (string-match org-plain-link-re link)
  9260. (not (string-match org-ts-regexp link)))
  9261. ;; URL-like link, normalize the use of angular brackets.
  9262. (setq link (org-unbracket-string "<" ">" link)))
  9263. ;; Check if we are linking to the current file with a search
  9264. ;; option If yes, simplify the link by using only the search
  9265. ;; option.
  9266. (when (and buffer-file-name
  9267. (let ((case-fold-search nil))
  9268. (string-match "\\`file:\\(.+?\\)::" link)))
  9269. (let ((path (match-string-no-properties 1 link))
  9270. (search (substring-no-properties link (match-end 0))))
  9271. (save-match-data
  9272. (when (equal (file-truename buffer-file-name) (file-truename path))
  9273. ;; We are linking to this same file, with a search option
  9274. (setq link search)))))
  9275. ;; Check if we can/should use a relative path. If yes, simplify the link
  9276. (let ((case-fold-search nil))
  9277. (when (string-match "\\`\\(file\\|docview\\):" link)
  9278. (let* ((type (match-string-no-properties 0 link))
  9279. (path (substring-no-properties link (match-end 0)))
  9280. (origpath path))
  9281. (cond
  9282. ((or (eq org-link-file-path-type 'absolute)
  9283. (equal complete-file '(16)))
  9284. (setq path (abbreviate-file-name (expand-file-name path))))
  9285. ((eq org-link-file-path-type 'noabbrev)
  9286. (setq path (expand-file-name path)))
  9287. ((eq org-link-file-path-type 'relative)
  9288. (setq path (file-relative-name path)))
  9289. (t
  9290. (save-match-data
  9291. (if (string-match (concat "^" (regexp-quote
  9292. (expand-file-name
  9293. (file-name-as-directory
  9294. default-directory))))
  9295. (expand-file-name path))
  9296. ;; We are linking a file with relative path name.
  9297. (setq path (substring (expand-file-name path)
  9298. (match-end 0)))
  9299. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9300. (setq link (concat type path))
  9301. (when (equal desc origpath)
  9302. (setq desc path)))))
  9303. (if org-make-link-description-function
  9304. (setq desc
  9305. (or (condition-case nil
  9306. (funcall org-make-link-description-function link desc)
  9307. (error (progn (message "Can't get link description from `%s'"
  9308. (symbol-name org-make-link-description-function))
  9309. (sit-for 2) nil)))
  9310. (read-string "Description: " default-description)))
  9311. (if default-description (setq desc default-description)
  9312. (setq desc (or (and auto-desc desc)
  9313. (read-string "Description: " desc)))))
  9314. (unless (string-match "\\S-" desc) (setq desc nil))
  9315. (when remove (apply 'delete-region remove))
  9316. (insert (org-make-link-string link desc))
  9317. ;; Redisplay so as the new link has proper invisible characters.
  9318. (sit-for 0)))
  9319. (defun org-link-try-special-completion (type)
  9320. "If there is completion support for link type TYPE, offer it."
  9321. (let ((fun (org-link-get-parameter type :complete)))
  9322. (if (functionp fun)
  9323. (funcall fun)
  9324. (read-string "Link (no completion support): " (concat type ":")))))
  9325. (defun org-file-complete-link (&optional arg)
  9326. "Create a file link using completion."
  9327. (let ((file (read-file-name "File: "))
  9328. (pwd (file-name-as-directory (expand-file-name ".")))
  9329. (pwd1 (file-name-as-directory (abbreviate-file-name
  9330. (expand-file-name ".")))))
  9331. (cond ((equal arg '(16))
  9332. (concat "file:"
  9333. (abbreviate-file-name (expand-file-name file))))
  9334. ((string-match
  9335. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9336. (concat "file:" (match-string 1 file)))
  9337. ((string-match
  9338. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9339. (expand-file-name file))
  9340. (concat "file:"
  9341. (match-string 1 (expand-file-name file))))
  9342. (t (concat "file:" file)))))
  9343. (defun org-completing-read (&rest args)
  9344. "Completing-read with SPACE being a normal character."
  9345. (let ((enable-recursive-minibuffers t)
  9346. (minibuffer-local-completion-map
  9347. (copy-keymap minibuffer-local-completion-map)))
  9348. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9349. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9350. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9351. 'org-time-stamp-inactive)
  9352. (apply #'completing-read args)))
  9353. ;;; Opening/following a link
  9354. (defvar org-link-search-failed nil)
  9355. (defvar org-open-link-functions nil
  9356. "Hook for functions finding a plain text link.
  9357. These functions must take a single argument, the link content.
  9358. They will be called for links that look like [[link text][description]]
  9359. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9360. like a filename (e.g. \"./blue.png\").
  9361. These functions will be called *before* Org attempts to resolve the
  9362. link by doing text searches in the current buffer - so if you want a
  9363. link \"[[target]]\" to still find \"<<target>>\", your function should
  9364. handle this as a special case.
  9365. When the function does handle the link, it must return a non-nil value.
  9366. If it decides that it is not responsible for this link, it must return
  9367. nil to indicate that that Org can continue with other options like
  9368. exact and fuzzy text search.")
  9369. (defun org-next-link (&optional search-backward)
  9370. "Move forward to the next link.
  9371. If the link is in hidden text, expose it."
  9372. (interactive "P")
  9373. (when (and org-link-search-failed (eq this-command last-command))
  9374. (goto-char (point-min))
  9375. (message "Link search wrapped back to beginning of buffer"))
  9376. (setq org-link-search-failed nil)
  9377. (let* ((pos (point))
  9378. (ct (org-context))
  9379. (a (assq :link ct))
  9380. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9381. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9382. ((looking-at org-any-link-re)
  9383. ;; Don't stay stuck at link without an org-link face
  9384. (forward-char (if search-backward -1 1))))
  9385. (if (funcall srch-fun org-any-link-re nil t)
  9386. (progn
  9387. (goto-char (match-beginning 0))
  9388. (when (outline-invisible-p) (org-show-context)))
  9389. (goto-char pos)
  9390. (setq org-link-search-failed t)
  9391. (message "No further link found"))))
  9392. (defun org-previous-link ()
  9393. "Move backward to the previous link.
  9394. If the link is in hidden text, expose it."
  9395. (interactive)
  9396. (funcall 'org-next-link t))
  9397. (defun org-translate-link (s)
  9398. "Translate a link string if a translation function has been defined."
  9399. (with-temp-buffer
  9400. (insert (org-trim s))
  9401. (org-trim (org-element-interpret-data (org-element-context)))))
  9402. (defun org-translate-link-from-planner (type path)
  9403. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9404. This is still an experimental function, your mileage may vary."
  9405. (cond
  9406. ((member type '("http" "https" "news" "ftp"))
  9407. ;; standard Internet links are the same.
  9408. nil)
  9409. ((and (equal type "irc") (string-match "^//" path))
  9410. ;; Planner has two / at the beginning of an irc link, we have 1.
  9411. ;; We should have zero, actually....
  9412. (setq path (substring path 1)))
  9413. ((and (equal type "lisp") (string-match "^/" path))
  9414. ;; Planner has a slash, we do not.
  9415. (setq type "elisp" path (substring path 1)))
  9416. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9417. ;; A typical message link. Planner has the id after the final slash,
  9418. ;; we separate it with a hash mark
  9419. (setq path (concat (match-string 1 path) "#"
  9420. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9421. (cons type path))
  9422. (defun org-find-file-at-mouse (ev)
  9423. "Open file link or URL at mouse."
  9424. (interactive "e")
  9425. (mouse-set-point ev)
  9426. (org-open-at-point 'in-emacs))
  9427. (defun org-open-at-mouse (ev)
  9428. "Open file link or URL at mouse.
  9429. See the docstring of `org-open-file' for details."
  9430. (interactive "e")
  9431. (mouse-set-point ev)
  9432. (when (eq major-mode 'org-agenda-mode)
  9433. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9434. (org-open-at-point))
  9435. (defvar org-window-config-before-follow-link nil
  9436. "The window configuration before following a link.
  9437. This is saved in case the need arises to restore it.")
  9438. ;;;###autoload
  9439. (defun org-open-at-point-global ()
  9440. "Follow a link or time-stamp like Org mode does.
  9441. This command can be called in any mode to follow an external link
  9442. or a time-stamp that has Org mode syntax. Its behavior is
  9443. undefined when called on internal links (e.g., fuzzy links).
  9444. Raise an error when there is nothing to follow. "
  9445. (interactive)
  9446. (cond ((org-in-regexp org-any-link-re)
  9447. (org-open-link-from-string (match-string-no-properties 0)))
  9448. ((or (org-in-regexp org-ts-regexp-both nil t)
  9449. (org-in-regexp org-tsr-regexp-both nil t))
  9450. (org-follow-timestamp-link))
  9451. (t (user-error "No link found"))))
  9452. ;;;###autoload
  9453. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9454. "Open a link in the string S, as if it was in Org mode."
  9455. (interactive "sLink: \nP")
  9456. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9457. (with-temp-buffer
  9458. (let ((org-inhibit-startup (not reference-buffer)))
  9459. (org-mode)
  9460. (insert s)
  9461. (goto-char (point-min))
  9462. (when reference-buffer
  9463. (setq org-link-abbrev-alist-local
  9464. (with-current-buffer reference-buffer
  9465. org-link-abbrev-alist-local)))
  9466. (org-open-at-point arg reference-buffer)))))
  9467. (defvar org-open-at-point-functions nil
  9468. "Hook that is run when following a link at point.
  9469. Functions in this hook must return t if they identify and follow
  9470. a link at point. If they don't find anything interesting at point,
  9471. they must return nil.")
  9472. (defvar org-link-search-inhibit-query nil)
  9473. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9474. (defun org--open-doi-link (path)
  9475. "Open a \"doi\" type link.
  9476. PATH is a the path to search for, as a string."
  9477. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9478. (defun org--open-elisp-link (path)
  9479. "Open a \"elisp\" type link.
  9480. PATH is the sexp to evaluate, as a string."
  9481. (let ((cmd path))
  9482. (if (or (and (org-string-nw-p
  9483. org-confirm-elisp-link-not-regexp)
  9484. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9485. (not org-confirm-elisp-link-function)
  9486. (funcall org-confirm-elisp-link-function
  9487. (format "Execute \"%s\" as elisp? "
  9488. (org-add-props cmd nil 'face 'org-warning))))
  9489. (message "%s => %s" cmd
  9490. (if (eq (string-to-char cmd) ?\()
  9491. (eval (read cmd))
  9492. (call-interactively (read cmd))))
  9493. (user-error "Abort"))))
  9494. (defun org--open-help-link (path)
  9495. "Open a \"help\" type link.
  9496. PATH is a symbol name, as a string."
  9497. (pcase (intern path)
  9498. ((and (pred fboundp) variable) (describe-function variable))
  9499. ((and (pred boundp) function) (describe-variable function))
  9500. (name (user-error "Unknown function or variable: %s" name))))
  9501. (defun org--open-shell-link (path)
  9502. "Open a \"shell\" type link.
  9503. PATH is the command to execute, as a string."
  9504. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9505. (cmd path))
  9506. (if (or (and (org-string-nw-p
  9507. org-confirm-shell-link-not-regexp)
  9508. (string-match
  9509. org-confirm-shell-link-not-regexp cmd))
  9510. (not org-confirm-shell-link-function)
  9511. (funcall org-confirm-shell-link-function
  9512. (format "Execute \"%s\" in shell? "
  9513. (org-add-props cmd nil
  9514. 'face 'org-warning))))
  9515. (progn
  9516. (message "Executing %s" cmd)
  9517. (shell-command cmd buf)
  9518. (when (featurep 'midnight)
  9519. (setq clean-buffer-list-kill-buffer-names
  9520. (cons (buffer-name buf)
  9521. clean-buffer-list-kill-buffer-names))))
  9522. (user-error "Abort"))))
  9523. (defun org-open-at-point (&optional arg reference-buffer)
  9524. "Open link, timestamp, footnote or tags at point.
  9525. When point is on a link, follow it. Normally, files will be
  9526. opened by an appropriate application. If the optional prefix
  9527. argument ARG is non-nil, Emacs will visit the file. With
  9528. a double prefix argument, try to open outside of Emacs, in the
  9529. application the system uses for this file type.
  9530. When point is on a timestamp, open the agenda at the day
  9531. specified.
  9532. When point is a footnote definition, move to the first reference
  9533. found. If it is on a reference, move to the associated
  9534. definition.
  9535. When point is on a headline, display a list of every link in the
  9536. entry, so it is possible to pick one, or all, of them. If point
  9537. is on a tag, call `org-tags-view' instead.
  9538. When optional argument REFERENCE-BUFFER is non-nil, it should
  9539. specify a buffer from where the link search should happen. This
  9540. is used internally by `org-open-link-from-string'.
  9541. On top of syntactically correct links, this function will open
  9542. the link at point in comments or comment blocks and the first
  9543. link in a property drawer line."
  9544. (interactive "P")
  9545. ;; On a code block, open block's results.
  9546. (unless (call-interactively 'org-babel-open-src-block-result)
  9547. (org-load-modules-maybe)
  9548. (setq org-window-config-before-follow-link (current-window-configuration))
  9549. (org-remove-occur-highlights nil nil t)
  9550. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9551. (let* ((context
  9552. ;; Only consider supported types, even if they are not
  9553. ;; the closest one.
  9554. (org-element-lineage
  9555. (org-element-context)
  9556. '(clock comment comment-block footnote-definition
  9557. footnote-reference headline inlinetask keyword link
  9558. node-property timestamp)
  9559. t))
  9560. (type (org-element-type context))
  9561. (value (org-element-property :value context)))
  9562. (cond
  9563. ((not context) (user-error "No link found"))
  9564. ;; Exception: open timestamps and links in properties
  9565. ;; drawers, keywords and comments.
  9566. ((memq type '(comment comment-block keyword node-property))
  9567. (call-interactively #'org-open-at-point-global))
  9568. ;; On a headline or an inlinetask, but not on a timestamp,
  9569. ;; a link, a footnote reference or on tags.
  9570. ((and (memq type '(headline inlinetask))
  9571. ;; Not on tags.
  9572. (let ((case-fold-search nil))
  9573. (save-excursion
  9574. (beginning-of-line)
  9575. (looking-at org-complex-heading-regexp))
  9576. (or (not (match-beginning 5))
  9577. (< (point) (match-beginning 5)))))
  9578. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9579. (links (car data))
  9580. (links-end (cdr data)))
  9581. (if links
  9582. (dolist (link (if (stringp links) (list links) links))
  9583. (search-forward link nil links-end)
  9584. (goto-char (match-beginning 0))
  9585. (org-open-at-point))
  9586. (require 'org-attach)
  9587. (org-attach-reveal 'if-exists))))
  9588. ;; On a clock line, make sure point is on the timestamp
  9589. ;; before opening it.
  9590. ((and (eq type 'clock)
  9591. value
  9592. (>= (point) (org-element-property :begin value))
  9593. (<= (point) (org-element-property :end value)))
  9594. (org-follow-timestamp-link))
  9595. ;; Do nothing on white spaces after an object.
  9596. ((>= (point)
  9597. (save-excursion
  9598. (goto-char (org-element-property :end context))
  9599. (skip-chars-backward " \t")
  9600. (point)))
  9601. (user-error "No link found"))
  9602. ((eq type 'timestamp) (org-follow-timestamp-link))
  9603. ;; On tags within a headline or an inlinetask.
  9604. ((and (memq type '(headline inlinetask))
  9605. (let ((case-fold-search nil))
  9606. (save-excursion (beginning-of-line)
  9607. (looking-at org-complex-heading-regexp))
  9608. (and (match-beginning 5)
  9609. (>= (point) (match-beginning 5)))))
  9610. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9611. ((eq type 'link)
  9612. (let ((type (org-element-property :type context))
  9613. (path (org-link-unescape (org-element-property :path context))))
  9614. ;; Switch back to REFERENCE-BUFFER needed when called in
  9615. ;; a temporary buffer through `org-open-link-from-string'.
  9616. (with-current-buffer (or reference-buffer (current-buffer))
  9617. (cond
  9618. ((equal type "file")
  9619. (if (string-match "[*?{]" (file-name-nondirectory path))
  9620. (dired path)
  9621. ;; Look into `org-link-parameters' in order to find
  9622. ;; a DEDICATED-FUNCTION to open file. The function
  9623. ;; will be applied on raw link instead of parsed
  9624. ;; link due to the limitation in `org-add-link-type'
  9625. ;; ("open" function called with a single argument).
  9626. ;; If no such function is found, fallback to
  9627. ;; `org-open-file'.
  9628. (let* ((option (org-element-property :search-option context))
  9629. (app (org-element-property :application context))
  9630. (dedicated-function
  9631. (org-link-get-parameter
  9632. (if app (concat type "+" app) type)
  9633. :follow)))
  9634. (if dedicated-function
  9635. (funcall dedicated-function
  9636. (concat path
  9637. (and option (concat "::" option))))
  9638. (apply #'org-open-file
  9639. path
  9640. (cond (arg)
  9641. ((equal app "emacs") 'emacs)
  9642. ((equal app "sys") 'system))
  9643. (cond ((not option) nil)
  9644. ((string-match-p "\\`[0-9]+\\'" option)
  9645. (list (string-to-number option)))
  9646. (t (list nil
  9647. (org-link-unescape option)))))))))
  9648. ((functionp (org-link-get-parameter type :follow))
  9649. (funcall (org-link-get-parameter type :follow) path))
  9650. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9651. (unless (run-hook-with-args-until-success
  9652. 'org-open-link-functions path)
  9653. (if (not arg) (org-mark-ring-push)
  9654. (switch-to-buffer-other-window
  9655. (org-get-buffer-for-internal-link (current-buffer))))
  9656. (let ((destination
  9657. (org-with-wide-buffer
  9658. (if (equal type "radio")
  9659. (org-search-radio-target
  9660. (org-element-property :path context))
  9661. (org-link-search
  9662. (if (member type '("custom-id" "coderef"))
  9663. (org-element-property :raw-link context)
  9664. path)
  9665. ;; Prevent fuzzy links from matching
  9666. ;; themselves.
  9667. (and (equal type "fuzzy")
  9668. (+ 2 (org-element-property :begin context)))))
  9669. (point))))
  9670. (unless (and (<= (point-min) destination)
  9671. (>= (point-max) destination))
  9672. (widen))
  9673. (goto-char destination))))
  9674. (t (browse-url-at-point))))))
  9675. ;; On a footnote reference or at a footnote definition's label.
  9676. ((or (eq type 'footnote-reference)
  9677. (and (eq type 'footnote-definition)
  9678. (save-excursion
  9679. ;; Do not validate action when point is on the
  9680. ;; spaces right after the footnote label, in
  9681. ;; order to be on par with behaviour on links.
  9682. (skip-chars-forward " \t")
  9683. (let ((begin
  9684. (org-element-property :contents-begin context)))
  9685. (if begin (< (point) begin)
  9686. (= (org-element-property :post-affiliated context)
  9687. (line-beginning-position)))))))
  9688. (org-footnote-action))
  9689. (t (user-error "No link found")))))
  9690. (run-hook-with-args 'org-follow-link-hook)))
  9691. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9692. "Offer links in the current entry and return the selected link.
  9693. If there is only one link, return it.
  9694. If NTH is an integer, return the NTH link found.
  9695. If ZERO is a string, check also this string for a link, and if
  9696. there is one, return it."
  9697. (with-current-buffer buffer
  9698. (org-with-wide-buffer
  9699. (goto-char marker)
  9700. (let ((cnt ?0)
  9701. have-zero end links link c)
  9702. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9703. (push (match-string 0 zero) links)
  9704. (setq cnt (1- cnt) have-zero t))
  9705. (save-excursion
  9706. (org-back-to-heading t)
  9707. (setq end (save-excursion (outline-next-heading) (point)))
  9708. (while (re-search-forward org-any-link-re end t)
  9709. (push (match-string 0) links))
  9710. (setq links (org-uniquify (reverse links))))
  9711. (cond
  9712. ((null links)
  9713. (message "No links"))
  9714. ((equal (length links) 1)
  9715. (setq link (car links)))
  9716. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9717. (setq link (nth (if have-zero nth (1- nth)) links)))
  9718. (t ; we have to select a link
  9719. (save-excursion
  9720. (save-window-excursion
  9721. (delete-other-windows)
  9722. (with-output-to-temp-buffer "*Select Link*"
  9723. (dolist (l links)
  9724. (cond
  9725. ((not (string-match org-bracket-link-regexp l))
  9726. (princ (format "[%c] %s\n" (cl-incf cnt)
  9727. (org-unbracket-string "<" ">" l))))
  9728. ((match-end 3)
  9729. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9730. (match-string 3 l) (match-string 1 l))))
  9731. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9732. (match-string 1 l)))))))
  9733. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9734. (message "Select link to open, RET to open all:")
  9735. (setq c (read-char-exclusive))
  9736. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9737. (when (equal c ?q) (user-error "Abort"))
  9738. (if (equal c ?\C-m)
  9739. (setq link links)
  9740. (setq nth (- c ?0))
  9741. (when have-zero (setq nth (1+ nth)))
  9742. (unless (and (integerp nth) (>= (length links) nth))
  9743. (user-error "Invalid link selection"))
  9744. (setq link (nth (1- nth) links)))))
  9745. (cons link end)))))
  9746. ;; TODO: These functions are deprecated since `org-open-at-point'
  9747. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9748. (defun org-open-file-with-system (path)
  9749. "Open file at PATH using the system way of opening it."
  9750. (org-open-file path 'system))
  9751. (defun org-open-file-with-emacs (path)
  9752. "Open file at PATH in Emacs."
  9753. (org-open-file path 'emacs))
  9754. ;;; File search
  9755. (defvar org-create-file-search-functions nil
  9756. "List of functions to construct the right search string for a file link.
  9757. These functions are called in turn with point at the location to
  9758. which the link should point.
  9759. A function in the hook should first test if it would like to
  9760. handle this file type, for example by checking the `major-mode'
  9761. or the file extension. If it decides not to handle this file, it
  9762. should just return nil to give other functions a chance. If it
  9763. does handle the file, it must return the search string to be used
  9764. when following the link. The search string will be part of the
  9765. file link, given after a double colon, and `org-open-at-point'
  9766. will automatically search for it. If special measures must be
  9767. taken to make the search successful, another function should be
  9768. added to the companion hook `org-execute-file-search-functions',
  9769. which see.
  9770. A function in this hook may also use `setq' to set the variable
  9771. `description' to provide a suggestion for the descriptive text to
  9772. be used for this link when it gets inserted into an Org buffer
  9773. with \\[org-insert-link].")
  9774. (defvar org-execute-file-search-functions nil
  9775. "List of functions to execute a file search triggered by a link.
  9776. Functions added to this hook must accept a single argument, the
  9777. search string that was part of the file link, the part after the
  9778. double colon. The function must first check if it would like to
  9779. handle this search, for example by checking the `major-mode' or
  9780. the file extension. If it decides not to handle this search, it
  9781. should just return nil to give other functions a chance. If it
  9782. does handle the search, it must return a non-nil value to keep
  9783. other functions from trying.
  9784. Each function can access the current prefix argument through the
  9785. variable `current-prefix-arg'. Note that a single prefix is used
  9786. to force opening a link in Emacs, so it may be good to only use a
  9787. numeric or double prefix to guide the search function.
  9788. In case this is needed, a function in this hook can also restore
  9789. the window configuration before `org-open-at-point' was called using:
  9790. (set-window-configuration org-window-config-before-follow-link)")
  9791. (defun org-search-radio-target (target)
  9792. "Search a radio target matching TARGET in current buffer.
  9793. White spaces are not significant."
  9794. (let ((re (format "<<<%s>>>"
  9795. (mapconcat #'regexp-quote
  9796. (org-split-string target "[ \t\n]+")
  9797. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9798. (origin (point)))
  9799. (goto-char (point-min))
  9800. (catch :radio-match
  9801. (while (re-search-forward re nil t)
  9802. (backward-char)
  9803. (let ((object (org-element-context)))
  9804. (when (eq (org-element-type object) 'radio-target)
  9805. (goto-char (org-element-property :begin object))
  9806. (org-show-context 'link-search)
  9807. (throw :radio-match nil))))
  9808. (goto-char origin)
  9809. (user-error "No match for radio target: %s" target))))
  9810. (defun org-link-search (s &optional avoid-pos stealth)
  9811. "Search for a search string S.
  9812. If S starts with \"#\", it triggers a custom ID search.
  9813. If S is enclosed within parenthesis, it initiates a coderef
  9814. search.
  9815. If S is surrounded by forward slashes, it is interpreted as
  9816. a regular expression. In Org mode files, this will create an
  9817. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9818. to list matches. If the current buffer is in `dired-mode', grep
  9819. will be used to search in all files.
  9820. When AVOID-POS is given, ignore matches near that position.
  9821. When optional argument STEALTH is non-nil, do not modify
  9822. visibility around point, thus ignoring `org-show-context-detail'
  9823. variable.
  9824. Search is case-insensitive and ignores white spaces. Return type
  9825. of matched result, which is either `dedicated' or `fuzzy'."
  9826. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9827. (let* ((case-fold-search t)
  9828. (origin (point))
  9829. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9830. (starred (eq (string-to-char normalized) ?*))
  9831. (words (split-string (if starred (substring s 1) s)))
  9832. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9833. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9834. type)
  9835. (cond
  9836. ;; Check if there are any special search functions.
  9837. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9838. ((eq (string-to-char s) ?#)
  9839. ;; Look for a custom ID S if S starts with "#".
  9840. (let* ((id (substring normalized 1))
  9841. (match (org-find-property "CUSTOM_ID" id)))
  9842. (if match (progn (goto-char match) (setf type 'dedicated))
  9843. (error "No match for custom ID: %s" id))))
  9844. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9845. ;; Look for coderef targets if S is enclosed within parenthesis.
  9846. (let ((coderef (match-string-no-properties 1 normalized))
  9847. (re (substring s-single-re 1 -1)))
  9848. (goto-char (point-min))
  9849. (catch :coderef-match
  9850. (while (re-search-forward re nil t)
  9851. (let ((element (org-element-at-point)))
  9852. (when (and (memq (org-element-type element)
  9853. '(example-block src-block))
  9854. ;; Build proper regexp according to current
  9855. ;; block's label format.
  9856. (let ((label-fmt
  9857. (regexp-quote
  9858. (or (org-element-property :label-fmt element)
  9859. org-coderef-label-format))))
  9860. (save-excursion
  9861. (beginning-of-line)
  9862. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9863. (format label-fmt coderef))))))
  9864. (setq type 'dedicated)
  9865. (goto-char (match-beginning 1))
  9866. (throw :coderef-match nil))))
  9867. (goto-char origin)
  9868. (error "No match for coderef: %s" coderef))))
  9869. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9870. ;; Look for a regular expression.
  9871. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9872. (match-string 1 s)))
  9873. ;; From here, we handle fuzzy links.
  9874. ;;
  9875. ;; Look for targets, only if not in a headline search.
  9876. ((and (not starred)
  9877. (let ((target (format "<<%s>>" s-multi-re)))
  9878. (catch :target-match
  9879. (goto-char (point-min))
  9880. (while (re-search-forward target nil t)
  9881. (backward-char)
  9882. (let ((context (org-element-context)))
  9883. (when (eq (org-element-type context) 'target)
  9884. (setq type 'dedicated)
  9885. (goto-char (org-element-property :begin context))
  9886. (throw :target-match t))))
  9887. nil))))
  9888. ;; Look for elements named after S, only if not in a headline
  9889. ;; search.
  9890. ((and (not starred)
  9891. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9892. (catch :name-match
  9893. (goto-char (point-min))
  9894. (while (re-search-forward name nil t)
  9895. (let ((element (org-element-at-point)))
  9896. (when (equal words
  9897. (split-string
  9898. (org-element-property :name element)))
  9899. (setq type 'dedicated)
  9900. (beginning-of-line)
  9901. (throw :name-match t))))
  9902. nil))))
  9903. ;; Regular text search. Prefer headlines in Org mode buffers.
  9904. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9905. ;; statistics cookies and tags.
  9906. ((and (derived-mode-p 'org-mode)
  9907. (let ((title-re
  9908. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9909. org-outline-regexp-bol
  9910. org-comment-string
  9911. (mapconcat #'regexp-quote words ".+")))
  9912. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9913. (comment-re (eval-when-compile
  9914. (format "\\`%s[ \t]+" org-comment-string))))
  9915. (goto-char (point-min))
  9916. (catch :found
  9917. (while (re-search-forward title-re nil t)
  9918. (when (equal words
  9919. (split-string
  9920. (replace-regexp-in-string
  9921. cookie-re ""
  9922. (replace-regexp-in-string
  9923. comment-re "" (org-get-heading t t t)))))
  9924. (throw :found t)))
  9925. nil)))
  9926. (beginning-of-line)
  9927. (setq type 'dedicated))
  9928. ;; Offer to create non-existent headline depending on
  9929. ;; `org-link-search-must-match-exact-headline'.
  9930. ((and (derived-mode-p 'org-mode)
  9931. (not org-link-search-inhibit-query)
  9932. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9933. (yes-or-no-p "No match - create this as a new heading? "))
  9934. (goto-char (point-max))
  9935. (unless (bolp) (newline))
  9936. (org-insert-heading nil t t)
  9937. (insert s "\n")
  9938. (beginning-of-line 0))
  9939. ;; Only headlines are looked after. No need to process
  9940. ;; further: throw an error.
  9941. ((and (derived-mode-p 'org-mode)
  9942. (or starred org-link-search-must-match-exact-headline))
  9943. (goto-char origin)
  9944. (error "No match for fuzzy expression: %s" normalized))
  9945. ;; Regular text search.
  9946. ((catch :fuzzy-match
  9947. (goto-char (point-min))
  9948. (while (re-search-forward s-multi-re nil t)
  9949. ;; Skip match if it contains AVOID-POS or it is included in
  9950. ;; a link with a description but outside the description.
  9951. (unless (or (and avoid-pos
  9952. (<= (match-beginning 0) avoid-pos)
  9953. (> (match-end 0) avoid-pos))
  9954. (and (save-match-data
  9955. (org-in-regexp org-bracket-link-regexp))
  9956. (match-beginning 3)
  9957. (or (> (match-beginning 3) (point))
  9958. (<= (match-end 3) (point)))
  9959. (org-element-lineage
  9960. (save-match-data (org-element-context))
  9961. '(link) t)))
  9962. (goto-char (match-beginning 0))
  9963. (setq type 'fuzzy)
  9964. (throw :fuzzy-match t)))
  9965. nil))
  9966. ;; All failed. Throw an error.
  9967. (t (goto-char origin)
  9968. (error "No match for fuzzy expression: %s" normalized)))
  9969. ;; Disclose surroundings of match, if appropriate.
  9970. (when (and (derived-mode-p 'org-mode) (not stealth))
  9971. (org-show-context 'link-search))
  9972. type))
  9973. (defun org-get-buffer-for-internal-link (buffer)
  9974. "Return a buffer to be used for displaying the link target of internal links."
  9975. (cond
  9976. ((not org-display-internal-link-with-indirect-buffer)
  9977. buffer)
  9978. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9979. (message "Buffer is already a clone, not making another one")
  9980. ;; we also do not modify visibility in this case
  9981. buffer)
  9982. (t ; make a new indirect buffer for displaying the link
  9983. (let* ((bn (buffer-name buffer))
  9984. (ibn (concat bn "(Clone)"))
  9985. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9986. (with-current-buffer ib (org-overview))
  9987. ib))))
  9988. (defun org-do-occur (regexp &optional cleanup)
  9989. "Call the Emacs command `occur'.
  9990. If CLEANUP is non-nil, remove the printout of the regular expression
  9991. in the *Occur* buffer. This is useful if the regex is long and not useful
  9992. to read."
  9993. (occur regexp)
  9994. (when cleanup
  9995. (let ((cwin (selected-window)) win beg end)
  9996. (when (setq win (get-buffer-window "*Occur*"))
  9997. (select-window win))
  9998. (goto-char (point-min))
  9999. (when (re-search-forward "match[a-z]+" nil t)
  10000. (setq beg (match-end 0))
  10001. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10002. (setq end (1- (match-beginning 0)))))
  10003. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10004. (goto-char (point-min))
  10005. (select-window cwin))))
  10006. ;;; The mark ring for links jumps
  10007. (defvar org-mark-ring nil
  10008. "Mark ring for positions before jumps in Org mode.")
  10009. (defvar org-mark-ring-last-goto nil
  10010. "Last position in the mark ring used to go back.")
  10011. ;; Fill and close the ring
  10012. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10013. (dotimes (_ org-mark-ring-length)
  10014. (push (make-marker) org-mark-ring))
  10015. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10016. org-mark-ring)
  10017. (defun org-mark-ring-push (&optional pos buffer)
  10018. "Put the current position or POS into the mark ring and rotate it."
  10019. (interactive)
  10020. (setq pos (or pos (point)))
  10021. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10022. (move-marker (car org-mark-ring)
  10023. (or pos (point))
  10024. (or buffer (current-buffer)))
  10025. (message "%s"
  10026. (substitute-command-keys
  10027. "Position saved to mark ring, go back with \
  10028. `\\[org-mark-ring-goto]'.")))
  10029. (defun org-mark-ring-goto (&optional n)
  10030. "Jump to the previous position in the mark ring.
  10031. With prefix arg N, jump back that many stored positions. When
  10032. called several times in succession, walk through the entire ring.
  10033. Org mode commands jumping to a different position in the current file,
  10034. or to another Org file, automatically push the old position onto the ring."
  10035. (interactive "p")
  10036. (let (p m)
  10037. (if (eq last-command this-command)
  10038. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10039. (setq p org-mark-ring))
  10040. (setq org-mark-ring-last-goto p)
  10041. (setq m (car p))
  10042. (pop-to-buffer-same-window (marker-buffer m))
  10043. (goto-char m)
  10044. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10045. (defun org-add-angle-brackets (s)
  10046. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10047. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10048. s)
  10049. ;;; Following specific links
  10050. (defvar org-agenda-buffer-tmp-name)
  10051. (defvar org-agenda-start-on-weekday)
  10052. (defun org-follow-timestamp-link ()
  10053. "Open an agenda view for the time-stamp date/range at point."
  10054. (cond
  10055. ((org-at-date-range-p t)
  10056. (let ((org-agenda-start-on-weekday)
  10057. (t1 (match-string 1))
  10058. (t2 (match-string 2)) tt1 tt2)
  10059. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10060. tt2 (time-to-days (org-time-string-to-time t2)))
  10061. (let ((org-agenda-buffer-tmp-name
  10062. (format "*Org Agenda(a:%s)"
  10063. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10064. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10065. ((org-at-timestamp-p 'lax)
  10066. (let ((org-agenda-buffer-tmp-name
  10067. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10068. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10069. (substring (match-string 1) 0 10)))
  10070. 1)))
  10071. (t (error "This should not happen"))))
  10072. ;;; Following file links
  10073. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10074. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10075. (declare-function mailcap-mime-info
  10076. "mailcap" (string &optional request no-decode))
  10077. (defvar org-wait nil)
  10078. (defun org-open-file (path &optional in-emacs line search)
  10079. "Open the file at PATH.
  10080. First, this expands any special file name abbreviations. Then the
  10081. configuration variable `org-file-apps' is checked if it contains an
  10082. entry for this file type, and if yes, the corresponding command is launched.
  10083. If no application is found, Emacs simply visits the file.
  10084. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10085. With a double \\[universal-argument] \\[universal-argument] \
  10086. prefix arg, Org tries to avoid opening in Emacs
  10087. and to use an external application to visit the file.
  10088. Optional LINE specifies a line to go to, optional SEARCH a string
  10089. to search for. If LINE or SEARCH is given, the file will be
  10090. opened in Emacs, unless an entry from org-file-apps that makes
  10091. use of groups in a regexp matches.
  10092. If you want to change the way frames are used when following a
  10093. link, please customize `org-link-frame-setup'.
  10094. If the file does not exist, an error is thrown."
  10095. (let* ((file (if (equal path "")
  10096. buffer-file-name
  10097. (substitute-in-file-name (expand-file-name path))))
  10098. (file-apps (append org-file-apps (org-default-apps)))
  10099. (apps (cl-remove-if
  10100. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10101. (apps-dlink (cl-remove-if-not
  10102. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10103. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10104. (dirp (unless remp (file-directory-p file)))
  10105. (file (if (and dirp org-open-directory-means-index-dot-org)
  10106. (concat (file-name-as-directory file) "index.org")
  10107. file))
  10108. (a-m-a-p (assq 'auto-mode apps))
  10109. (dfile (downcase file))
  10110. ;; Reconstruct the original link from the PATH, LINE and
  10111. ;; SEARCH args.
  10112. (link (cond (line (concat file "::" (number-to-string line)))
  10113. (search (concat file "::" search))
  10114. (t file)))
  10115. (dlink (downcase link))
  10116. (ext
  10117. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10118. (match-string 1 dfile)))
  10119. (save-position-maybe
  10120. (let ((old-buffer (current-buffer))
  10121. (old-pos (point))
  10122. (old-mode major-mode))
  10123. (lambda ()
  10124. (and (derived-mode-p 'org-mode)
  10125. (eq old-mode 'org-mode)
  10126. (or (not (eq old-buffer (current-buffer)))
  10127. (not (eq old-pos (point))))
  10128. (org-mark-ring-push old-pos old-buffer)))))
  10129. cmd link-match-data)
  10130. (cond
  10131. ((member in-emacs '((16) system))
  10132. (setq cmd (cdr (assq 'system apps))))
  10133. (in-emacs (setq cmd 'emacs))
  10134. (t
  10135. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10136. (and dirp (cdr (assq 'directory apps)))
  10137. ;; First, try matching against apps-dlink if we
  10138. ;; get a match here, store the match data for
  10139. ;; later.
  10140. (let ((match (assoc-default dlink apps-dlink
  10141. 'string-match)))
  10142. (if match
  10143. (progn (setq link-match-data (match-data))
  10144. match)
  10145. (progn (setq in-emacs (or in-emacs line search))
  10146. nil))) ; if we have no match in apps-dlink,
  10147. ; always open the file in emacs if line or search
  10148. ; is given (for backwards compatibility)
  10149. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10150. 'string-match)
  10151. (cdr (assoc ext apps))
  10152. (cdr (assq t apps))))))
  10153. (when (eq cmd 'system)
  10154. (setq cmd (cdr (assq 'system apps))))
  10155. (when (eq cmd 'default)
  10156. (setq cmd (cdr (assoc t apps))))
  10157. (when (eq cmd 'mailcap)
  10158. (require 'mailcap)
  10159. (mailcap-parse-mailcaps)
  10160. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10161. (command (mailcap-mime-info mime-type)))
  10162. (if (stringp command)
  10163. (setq cmd command)
  10164. (setq cmd 'emacs))))
  10165. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10166. (not (file-exists-p file))
  10167. (not org-open-non-existing-files))
  10168. (user-error "No such file: %s" file))
  10169. (cond
  10170. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10171. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10172. (while (string-match "['\"]%s['\"]" cmd)
  10173. (setq cmd (replace-match "%s" t t cmd)))
  10174. (setq cmd (replace-regexp-in-string
  10175. "%s"
  10176. (shell-quote-argument (convert-standard-filename file))
  10177. cmd
  10178. nil t))
  10179. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10180. (save-match-data
  10181. (let ((match-index 1)
  10182. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10183. (set-match-data link-match-data)
  10184. (while (<= match-index number-of-groups)
  10185. (let ((regex (concat "%" (number-to-string match-index)))
  10186. (replace-with (match-string match-index dlink)))
  10187. (while (string-match regex cmd)
  10188. (setq cmd (replace-match replace-with t t cmd))))
  10189. (setq match-index (+ match-index 1)))))
  10190. (save-window-excursion
  10191. (message "Running %s...done" cmd)
  10192. (start-process-shell-command cmd nil cmd)
  10193. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10194. ((or (stringp cmd)
  10195. (eq cmd 'emacs))
  10196. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10197. (widen)
  10198. (cond (line (org-goto-line line)
  10199. (when (derived-mode-p 'org-mode) (org-reveal)))
  10200. (search (condition-case err
  10201. (org-link-search search)
  10202. ;; Save position before error-ing out so user
  10203. ;; can easily move back to the original buffer.
  10204. (error (funcall save-position-maybe)
  10205. (error (nth 1 err)))))))
  10206. ((functionp cmd)
  10207. (save-match-data
  10208. (set-match-data link-match-data)
  10209. (condition-case nil
  10210. (funcall cmd file link)
  10211. ;; FIXME: Remove this check when most default installations
  10212. ;; of Emacs have at least Org 9.0.
  10213. ((debug wrong-number-of-arguments wrong-type-argument
  10214. invalid-function)
  10215. (user-error "Please see Org News for version 9.0 about \
  10216. `org-file-apps'--Lisp error: %S" cmd)))))
  10217. ((consp cmd)
  10218. ;; FIXME: Remove this check when most default installations of
  10219. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  10220. ;; fall back to `org-link-frame-setup' for an old usage of
  10221. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  10222. (user-error "Please see Org News for version 9.0 about \
  10223. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10224. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10225. (funcall save-position-maybe)))
  10226. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10227. "This function returns non-nil if `entry' uses a regular
  10228. expression which should be matched against the whole link by
  10229. org-open-file.
  10230. It assumes that is the case when the entry uses a regular
  10231. expression which has at least one grouping construct and the
  10232. action is either a lisp form or a command string containing
  10233. `%1', i.e. using at least one subexpression match as a
  10234. parameter."
  10235. (let ((selector (car entry))
  10236. (action (cdr entry)))
  10237. (if (stringp selector)
  10238. (and (> (regexp-opt-depth selector) 0)
  10239. (or (and (stringp action)
  10240. (string-match "%[0-9]" action))
  10241. (consp action)))
  10242. nil)))
  10243. (defun org-default-apps ()
  10244. "Return the default applications for this operating system."
  10245. (cond
  10246. ((eq system-type 'darwin)
  10247. org-file-apps-defaults-macosx)
  10248. ((eq system-type 'windows-nt)
  10249. org-file-apps-defaults-windowsnt)
  10250. (t org-file-apps-defaults-gnu)))
  10251. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10252. "Convert extensions to regular expressions in the cars of LIST.
  10253. Also, weed out any non-string entries, because the return value is used
  10254. only for regexp matching.
  10255. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10256. point to the symbol `emacs', indicating that the file should
  10257. be opened in Emacs."
  10258. (append
  10259. (delq nil
  10260. (mapcar (lambda (x)
  10261. (unless (not (stringp (car x)))
  10262. (if (string-match "\\W" (car x))
  10263. x
  10264. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10265. list))
  10266. (when add-auto-mode
  10267. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10268. (defvar ange-ftp-name-format)
  10269. (defun org-file-remote-p (file)
  10270. "Test whether FILE specifies a location on a remote system.
  10271. Return non-nil if the location is indeed remote.
  10272. For example, the filename \"/user@host:/foo\" specifies a location
  10273. on the system \"/user@host:\"."
  10274. (cond ((fboundp 'file-remote-p)
  10275. (file-remote-p file))
  10276. ((fboundp 'tramp-handle-file-remote-p)
  10277. (tramp-handle-file-remote-p file))
  10278. ((and (boundp 'ange-ftp-name-format)
  10279. (string-match (car ange-ftp-name-format) file))
  10280. t)))
  10281. ;;;; Refiling
  10282. (defun org-get-org-file ()
  10283. "Read a filename, with default directory `org-directory'."
  10284. (let ((default (or org-default-notes-file remember-data-file)))
  10285. (read-file-name (format "File name [%s]: " default)
  10286. (file-name-as-directory org-directory)
  10287. default)))
  10288. (defun org-notes-order-reversed-p ()
  10289. "Check if the current file should receive notes in reversed order."
  10290. (cond
  10291. ((not org-reverse-note-order) nil)
  10292. ((eq t org-reverse-note-order) t)
  10293. ((not (listp org-reverse-note-order)) nil)
  10294. (t (catch 'exit
  10295. (dolist (entry org-reverse-note-order)
  10296. (when (string-match (car entry) buffer-file-name)
  10297. (throw 'exit (cdr entry))))))))
  10298. (defvar org-refile-target-table nil
  10299. "The list of refile targets, created by `org-refile'.")
  10300. (defvar org-agenda-new-buffers nil
  10301. "Buffers created to visit agenda files.")
  10302. (defvar org-refile-cache nil
  10303. "Cache for refile targets.")
  10304. (defvar org-refile-markers nil
  10305. "All the markers used for caching refile locations.")
  10306. (defun org-refile-marker (pos)
  10307. "Get a new refile marker, but only if caching is in use."
  10308. (if (not org-refile-use-cache)
  10309. pos
  10310. (let ((m (make-marker)))
  10311. (move-marker m pos)
  10312. (push m org-refile-markers)
  10313. m)))
  10314. (defun org-refile-cache-clear ()
  10315. "Clear the refile cache and disable all the markers."
  10316. (dolist (m org-refile-markers) (move-marker m nil))
  10317. (setq org-refile-markers nil)
  10318. (setq org-refile-cache nil)
  10319. (message "Refile cache has been cleared"))
  10320. (defun org-refile-cache-check-set (set)
  10321. "Check if all the markers in the cache still have live buffers."
  10322. (let (marker)
  10323. (catch 'exit
  10324. (while (and set (setq marker (nth 3 (pop set))))
  10325. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10326. (when (and marker (null (marker-buffer marker)))
  10327. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10328. (sit-for 3)
  10329. (throw 'exit nil)))
  10330. t)))
  10331. (defun org-refile-cache-put (set &rest identifiers)
  10332. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10333. (let* ((key (sha1 (prin1-to-string identifiers)))
  10334. (entry (assoc key org-refile-cache)))
  10335. (if entry
  10336. (setcdr entry set)
  10337. (push (cons key set) org-refile-cache))))
  10338. (defun org-refile-cache-get (&rest identifiers)
  10339. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10340. (cond
  10341. ((not org-refile-cache) nil)
  10342. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10343. (t
  10344. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10345. org-refile-cache))))
  10346. (and set (org-refile-cache-check-set set) set)))))
  10347. (defvar org-outline-path-cache nil
  10348. "Alist between buffer positions and outline paths.
  10349. It value is an alist (POSITION . PATH) where POSITION is the
  10350. buffer position at the beginning of an entry and PATH is a list
  10351. of strings describing the outline path for that entry, in reverse
  10352. order.")
  10353. (defun org-refile-get-targets (&optional default-buffer)
  10354. "Produce a table with refile targets."
  10355. (let ((case-fold-search nil)
  10356. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10357. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10358. targets tgs files desc descre)
  10359. (message "Getting targets...")
  10360. (with-current-buffer (or default-buffer (current-buffer))
  10361. (dolist (entry entries)
  10362. (setq files (car entry) desc (cdr entry))
  10363. (cond
  10364. ((null files) (setq files (list (current-buffer))))
  10365. ((eq files 'org-agenda-files)
  10366. (setq files (org-agenda-files 'unrestricted)))
  10367. ((and (symbolp files) (fboundp files))
  10368. (setq files (funcall files)))
  10369. ((and (symbolp files) (boundp files))
  10370. (setq files (symbol-value files))))
  10371. (when (stringp files) (setq files (list files)))
  10372. (cond
  10373. ((eq (car desc) :tag)
  10374. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10375. ((eq (car desc) :todo)
  10376. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10377. ((eq (car desc) :regexp)
  10378. (setq descre (cdr desc)))
  10379. ((eq (car desc) :level)
  10380. (setq descre (concat "^\\*\\{" (number-to-string
  10381. (if org-odd-levels-only
  10382. (1- (* 2 (cdr desc)))
  10383. (cdr desc)))
  10384. "\\}[ \t]")))
  10385. ((eq (car desc) :maxlevel)
  10386. (setq descre (concat "^\\*\\{1," (number-to-string
  10387. (if org-odd-levels-only
  10388. (1- (* 2 (cdr desc)))
  10389. (cdr desc)))
  10390. "\\}[ \t]")))
  10391. (t (error "Bad refiling target description %s" desc)))
  10392. (dolist (f files)
  10393. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10394. (or
  10395. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10396. (progn
  10397. (when (bufferp f)
  10398. (setq f (buffer-file-name (buffer-base-buffer f))))
  10399. (setq f (and f (expand-file-name f)))
  10400. (when (eq org-refile-use-outline-path 'file)
  10401. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10402. (when (eq org-refile-use-outline-path 'buffer-name)
  10403. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10404. (when (eq org-refile-use-outline-path 'full-file-path)
  10405. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10406. (org-with-wide-buffer
  10407. (goto-char (point-min))
  10408. (setq org-outline-path-cache nil)
  10409. (while (re-search-forward descre nil t)
  10410. (beginning-of-line)
  10411. (let ((case-fold-search nil))
  10412. (looking-at org-complex-heading-regexp))
  10413. (let ((begin (point))
  10414. (heading (match-string-no-properties 4)))
  10415. (unless (or (and
  10416. org-refile-target-verify-function
  10417. (not
  10418. (funcall org-refile-target-verify-function)))
  10419. (not heading))
  10420. (let ((re (format org-complex-heading-regexp-format
  10421. (regexp-quote heading)))
  10422. (target
  10423. (if (not org-refile-use-outline-path) heading
  10424. (mapconcat
  10425. #'identity
  10426. (append
  10427. (pcase org-refile-use-outline-path
  10428. (`file (list (file-name-nondirectory
  10429. (buffer-file-name
  10430. (buffer-base-buffer)))))
  10431. (`full-file-path
  10432. (list (buffer-file-name
  10433. (buffer-base-buffer))))
  10434. (`buffer-name
  10435. (list (buffer-name
  10436. (buffer-base-buffer))))
  10437. (_ nil))
  10438. (mapcar #'org-protect-slash
  10439. (org-get-outline-path t t)))
  10440. "/"))))
  10441. (push (list target f re (org-refile-marker (point)))
  10442. tgs)))
  10443. (when (= (point) begin)
  10444. ;; Verification function has not moved point.
  10445. (end-of-line)))))))
  10446. (when org-refile-use-cache
  10447. (org-refile-cache-put tgs (buffer-file-name) descre))
  10448. (setq targets (append tgs targets))))))
  10449. (message "Getting targets...done")
  10450. (delete-dups (nreverse targets))))
  10451. (defun org-protect-slash (s)
  10452. (replace-regexp-in-string "/" "\\/" s nil t))
  10453. (defun org--get-outline-path-1 (&optional use-cache)
  10454. "Return outline path to current headline.
  10455. Outline path is a list of strings, in reverse order. When
  10456. optional argument USE-CACHE is non-nil, make use of a cache. See
  10457. `org-get-outline-path' for details.
  10458. Assume buffer is widened and point is on a headline."
  10459. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10460. (let ((p (point))
  10461. (heading (let ((case-fold-search nil))
  10462. (looking-at org-complex-heading-regexp)
  10463. (if (not (match-end 4)) ""
  10464. ;; Remove statistics cookies.
  10465. (org-trim
  10466. (org-link-display-format
  10467. (replace-regexp-in-string
  10468. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10469. (match-string-no-properties 4))))))))
  10470. (if (org-up-heading-safe)
  10471. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10472. (when use-cache
  10473. (push (cons p path) org-outline-path-cache))
  10474. path)
  10475. ;; This is a new root node. Since we assume we are moving
  10476. ;; forward, we can drop previous cache so as to limit number
  10477. ;; of associations there.
  10478. (let ((path (list heading)))
  10479. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10480. path)))))
  10481. (defun org-get-outline-path (&optional with-self use-cache)
  10482. "Return the outline path to the current entry.
  10483. An outline path is a list of ancestors for current headline, as
  10484. a list of strings. Statistics cookies are removed and links are
  10485. replaced with their description, if any, or their path otherwise.
  10486. When optional argument WITH-SELF is non-nil, the path also
  10487. includes the current headline.
  10488. When optional argument USE-CACHE is non-nil, cache outline paths
  10489. between calls to this function so as to avoid backtracking. This
  10490. argument is useful when planning to find more than one outline
  10491. path in the same document. In that case, there are two
  10492. conditions to satisfy:
  10493. - `org-outline-path-cache' is set to nil before starting the
  10494. process;
  10495. - outline paths are computed by increasing buffer positions."
  10496. (org-with-wide-buffer
  10497. (and (or (and with-self (org-back-to-heading t))
  10498. (org-up-heading-safe))
  10499. (reverse (org--get-outline-path-1 use-cache)))))
  10500. (defun org-format-outline-path (path &optional width prefix separator)
  10501. "Format the outline path PATH for display.
  10502. WIDTH is the maximum number of characters that is available.
  10503. PREFIX is a prefix to be included in the returned string,
  10504. such as the file name.
  10505. SEPARATOR is inserted between the different parts of the path,
  10506. the default is \"/\"."
  10507. (setq width (or width 79))
  10508. (setq path (delq nil path))
  10509. (unless (> width 0)
  10510. (user-error "Argument `width' must be positive"))
  10511. (setq separator (or separator "/"))
  10512. (let* ((org-odd-levels-only nil)
  10513. (fpath (concat
  10514. prefix (and prefix path separator)
  10515. (mapconcat
  10516. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10517. (cl-loop for head in path
  10518. for n from 0
  10519. collect (org-add-props
  10520. head nil 'face
  10521. (nth (% n org-n-level-faces) org-level-faces)))
  10522. separator))))
  10523. (when (> (length fpath) width)
  10524. (if (< width 7)
  10525. ;; It's unlikely that `width' will be this small, but don't
  10526. ;; waste characters by adding ".." if it is.
  10527. (setq fpath (substring fpath 0 width))
  10528. (setf (substring fpath (- width 2)) "..")))
  10529. fpath))
  10530. (defun org-display-outline-path (&optional file current separator just-return-string)
  10531. "Display the current outline path in the echo area.
  10532. If FILE is non-nil, prepend the output with the file name.
  10533. If CURRENT is non-nil, append the current heading to the output.
  10534. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10535. the different parts of the path and defaults to \"/\".
  10536. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10537. (interactive "P")
  10538. (let* (case-fold-search
  10539. (bfn (buffer-file-name (buffer-base-buffer)))
  10540. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10541. res)
  10542. (when current (setq path (append path
  10543. (save-excursion
  10544. (org-back-to-heading t)
  10545. (when (looking-at org-complex-heading-regexp)
  10546. (list (match-string 4)))))))
  10547. (setq res
  10548. (org-format-outline-path
  10549. path
  10550. (1- (frame-width))
  10551. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10552. separator))
  10553. (if just-return-string
  10554. (org-no-properties res)
  10555. (org-unlogged-message "%s" res))))
  10556. (defvar org-refile-history nil
  10557. "History for refiling operations.")
  10558. (defvar org-after-refile-insert-hook nil
  10559. "Hook run after `org-refile' has inserted its stuff at the new location.
  10560. Note that this is still *before* the stuff will be removed from
  10561. the *old* location.")
  10562. (defvar org-capture-last-stored-marker)
  10563. (defvar org-refile-keep nil
  10564. "Non-nil means `org-refile' will copy instead of refile.")
  10565. (defun org-copy ()
  10566. "Like `org-refile', but copy."
  10567. (interactive)
  10568. (let ((org-refile-keep t))
  10569. (funcall 'org-refile nil nil nil "Copy")))
  10570. (defun org-refile (&optional arg default-buffer rfloc msg)
  10571. "Move the entry or entries at point to another heading.
  10572. The list of target headings is compiled using the information in
  10573. `org-refile-targets', which see.
  10574. At the target location, the entry is filed as a subitem of the
  10575. target heading. Depending on `org-reverse-note-order', the new
  10576. subitem will either be the first or the last subitem.
  10577. If there is an active region, all entries in that region will be
  10578. refiled. However, the region must fulfill the requirement that
  10579. the first heading sets the top-level of the moved text.
  10580. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10581. location
  10582. and not actually move anything.
  10583. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10584. location where the last
  10585. refiling operation has put the subtree.
  10586. With a numeric prefix argument of `2', refile to the running clock.
  10587. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10588. being set to t and copy to the target location, don't move it.
  10589. Beware that keeping refiled entries may result in duplicated ID
  10590. properties.
  10591. RFLOC can be a refile location obtained in a different way.
  10592. MSG is a string to replace \"Refile\" in the default prompt with
  10593. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10594. See also `org-refile-use-outline-path'.
  10595. If you are using target caching (see `org-refile-use-cache'), you
  10596. have to clear the target cache in order to find new targets.
  10597. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10598. prefix argument (`C-u C-u C-u C-c C-w')."
  10599. (interactive "P")
  10600. (if (member arg '(0 (64)))
  10601. (org-refile-cache-clear)
  10602. (let* ((actionmsg (cond (msg msg)
  10603. ((equal arg 3) "Refile (and keep)")
  10604. (t "Refile")))
  10605. (regionp (org-region-active-p))
  10606. (region-start (and regionp (region-beginning)))
  10607. (region-end (and regionp (region-end)))
  10608. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10609. pos it nbuf file level reversed)
  10610. (setq last-command nil)
  10611. (when regionp
  10612. (goto-char region-start)
  10613. (or (bolp) (goto-char (point-at-bol)))
  10614. (setq region-start (point))
  10615. (unless (or (org-kill-is-subtree-p
  10616. (buffer-substring region-start region-end))
  10617. (prog1 org-refile-active-region-within-subtree
  10618. (let ((s (point-at-eol)))
  10619. (org-toggle-heading)
  10620. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10621. (user-error "The region is not a (sequence of) subtree(s)")))
  10622. (if (equal arg '(16))
  10623. (org-refile-goto-last-stored)
  10624. (when (or
  10625. (and (equal arg 2)
  10626. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10627. (prog1
  10628. (setq it (list (or org-clock-heading "running clock")
  10629. (buffer-file-name
  10630. (marker-buffer org-clock-hd-marker))
  10631. ""
  10632. (marker-position org-clock-hd-marker)))
  10633. (setq arg nil)))
  10634. (setq it
  10635. (or rfloc
  10636. (let (heading-text)
  10637. (save-excursion
  10638. (unless (and arg (listp arg))
  10639. (org-back-to-heading t)
  10640. (setq heading-text
  10641. (replace-regexp-in-string
  10642. org-bracket-link-regexp
  10643. "\\3"
  10644. (or (nth 4 (org-heading-components))
  10645. ""))))
  10646. (org-refile-get-location
  10647. (cond ((and arg (listp arg)) "Goto")
  10648. (regionp (concat actionmsg " region to"))
  10649. (t (concat actionmsg " subtree \""
  10650. heading-text "\" to")))
  10651. default-buffer
  10652. (and (not (equal '(4) arg))
  10653. org-refile-allow-creating-parent-nodes)))))))
  10654. (setq file (nth 1 it)
  10655. pos (nth 3 it))
  10656. (when (and (not arg)
  10657. pos
  10658. (equal (buffer-file-name) file)
  10659. (if regionp
  10660. (and (>= pos region-start)
  10661. (<= pos region-end))
  10662. (and (>= pos (point))
  10663. (< pos (save-excursion
  10664. (org-end-of-subtree t t))))))
  10665. (error "Cannot refile to position inside the tree or region"))
  10666. (setq nbuf (or (find-buffer-visiting file)
  10667. (find-file-noselect file)))
  10668. (if (and arg (not (equal arg 3)))
  10669. (progn
  10670. (pop-to-buffer-same-window nbuf)
  10671. (goto-char pos)
  10672. (org-show-context 'org-goto))
  10673. (if regionp
  10674. (progn
  10675. (org-kill-new (buffer-substring region-start region-end))
  10676. (org-save-markers-in-region region-start region-end))
  10677. (org-copy-subtree 1 nil t))
  10678. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10679. (find-file-noselect file)))
  10680. (setq reversed (org-notes-order-reversed-p))
  10681. (org-with-wide-buffer
  10682. (if pos
  10683. (progn
  10684. (goto-char pos)
  10685. (setq level (org-get-valid-level (funcall outline-level) 1))
  10686. (goto-char
  10687. (if reversed
  10688. (or (outline-next-heading) (point-max))
  10689. (or (save-excursion (org-get-next-sibling))
  10690. (org-end-of-subtree t t)
  10691. (point-max)))))
  10692. (setq level 1)
  10693. (if (not reversed)
  10694. (goto-char (point-max))
  10695. (goto-char (point-min))
  10696. (or (outline-next-heading) (goto-char (point-max)))))
  10697. (unless (bolp) (newline))
  10698. (org-paste-subtree level nil nil t)
  10699. (when org-log-refile
  10700. (org-add-log-setup 'refile nil nil org-log-refile)
  10701. (unless (eq org-log-refile 'note)
  10702. (save-excursion (org-add-log-note))))
  10703. (and org-auto-align-tags
  10704. (let ((org-loop-over-headlines-in-active-region nil))
  10705. (org-set-tags nil t)))
  10706. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10707. :last-refile)))
  10708. (when bookmark-name
  10709. (with-demoted-errors
  10710. (bookmark-set bookmark-name))))
  10711. ;; If we are refiling for capture, make sure that the
  10712. ;; last-capture pointers point here
  10713. (when (bound-and-true-p org-capture-is-refiling)
  10714. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10715. :last-capture-marker)))
  10716. (when bookmark-name
  10717. (with-demoted-errors
  10718. (bookmark-set bookmark-name))))
  10719. (move-marker org-capture-last-stored-marker (point)))
  10720. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10721. (run-hooks 'org-after-refile-insert-hook)))
  10722. (unless org-refile-keep
  10723. (if regionp
  10724. (delete-region (point) (+ (point) (- region-end region-start)))
  10725. (delete-region
  10726. (and (org-back-to-heading t) (point))
  10727. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10728. (when (featurep 'org-inlinetask)
  10729. (org-inlinetask-remove-END-maybe))
  10730. (setq org-markers-to-move nil)
  10731. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10732. (defun org-refile-goto-last-stored ()
  10733. "Go to the location where the last refile was stored."
  10734. (interactive)
  10735. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10736. (message "This is the location of the last refile"))
  10737. (defun org-refile--get-location (refloc tbl)
  10738. "When user refile to REFLOC, find the associated target in TBL.
  10739. Also check `org-refile-target-table'."
  10740. (car (delq
  10741. nil
  10742. (mapcar
  10743. (lambda (r) (or (assoc r tbl)
  10744. (assoc r org-refile-target-table)))
  10745. (list (replace-regexp-in-string "/$" "" refloc)
  10746. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10747. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10748. "Prompt the user for a refile location, using PROMPT.
  10749. PROMPT should not be suffixed with a colon and a space, because
  10750. this function appends the default value from
  10751. `org-refile-history' automatically, if that is not empty."
  10752. (let ((org-refile-targets org-refile-targets)
  10753. (org-refile-use-outline-path org-refile-use-outline-path))
  10754. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10755. (unless org-refile-target-table
  10756. (user-error "No refile targets"))
  10757. (let* ((cbuf (current-buffer))
  10758. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10759. (cfunc (if (and org-refile-use-outline-path
  10760. org-outline-path-complete-in-steps)
  10761. #'org-olpath-completing-read
  10762. #'completing-read))
  10763. (extra (if org-refile-use-outline-path "/" ""))
  10764. (cbnex (concat (buffer-name) extra))
  10765. (filename (and cfn (expand-file-name cfn)))
  10766. (tbl (mapcar
  10767. (lambda (x)
  10768. (if (and (not (member org-refile-use-outline-path
  10769. '(file full-file-path)))
  10770. (not (equal filename (nth 1 x))))
  10771. (cons (concat (car x) extra " ("
  10772. (file-name-nondirectory (nth 1 x)) ")")
  10773. (cdr x))
  10774. (cons (concat (car x) extra) (cdr x))))
  10775. org-refile-target-table))
  10776. (completion-ignore-case t)
  10777. cdef
  10778. (prompt (concat prompt
  10779. (or (and (car org-refile-history)
  10780. (concat " (default " (car org-refile-history) ")"))
  10781. (and (assoc cbnex tbl) (setq cdef cbnex)
  10782. (concat " (default " cbnex ")"))) ": "))
  10783. pa answ parent-target child parent old-hist)
  10784. (setq old-hist org-refile-history)
  10785. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10786. nil 'org-refile-history (or cdef (car org-refile-history))))
  10787. (if (setq pa (org-refile--get-location answ tbl))
  10788. (progn
  10789. (org-refile-check-position pa)
  10790. (when (or (not org-refile-history)
  10791. (not (eq old-hist org-refile-history))
  10792. (not (equal (car pa) (car org-refile-history))))
  10793. (setq org-refile-history
  10794. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10795. org-refile-history
  10796. (cdr org-refile-history))))
  10797. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10798. (pop org-refile-history)))
  10799. pa)
  10800. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10801. (progn
  10802. (setq parent (match-string 1 answ)
  10803. child (match-string 2 answ))
  10804. (setq parent-target (org-refile--get-location parent tbl))
  10805. (when (and parent-target
  10806. (or (eq new-nodes t)
  10807. (and (eq new-nodes 'confirm)
  10808. (y-or-n-p (format "Create new node \"%s\"? "
  10809. child)))))
  10810. (org-refile-new-child parent-target child)))
  10811. (user-error "Invalid target location")))))
  10812. (declare-function org-string-nw-p "org-macs" (s))
  10813. (defun org-refile-check-position (refile-pointer)
  10814. "Check if the refile pointer matches the headline to which it points."
  10815. (let* ((file (nth 1 refile-pointer))
  10816. (re (nth 2 refile-pointer))
  10817. (pos (nth 3 refile-pointer))
  10818. buffer)
  10819. (if (and (not (markerp pos)) (not file))
  10820. (user-error "Please indicate a target file in the refile path")
  10821. (when (org-string-nw-p re)
  10822. (setq buffer (if (markerp pos)
  10823. (marker-buffer pos)
  10824. (or (find-buffer-visiting file)
  10825. (find-file-noselect file))))
  10826. (with-current-buffer buffer
  10827. (org-with-wide-buffer
  10828. (goto-char pos)
  10829. (beginning-of-line 1)
  10830. (unless (looking-at-p re)
  10831. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10832. (defun org-refile-new-child (parent-target child)
  10833. "Use refile target PARENT-TARGET to add new CHILD below it."
  10834. (unless parent-target
  10835. (error "Cannot find parent for new node"))
  10836. (let ((file (nth 1 parent-target))
  10837. (pos (nth 3 parent-target))
  10838. level)
  10839. (with-current-buffer (or (find-buffer-visiting file)
  10840. (find-file-noselect file))
  10841. (org-with-wide-buffer
  10842. (if pos
  10843. (goto-char pos)
  10844. (goto-char (point-max))
  10845. (unless (bolp) (newline)))
  10846. (when (looking-at org-outline-regexp)
  10847. (setq level (funcall outline-level))
  10848. (org-end-of-subtree t t))
  10849. (org-back-over-empty-lines)
  10850. (insert "\n" (make-string
  10851. (if pos (org-get-valid-level level 1) 1) ?*)
  10852. " " child "\n")
  10853. (beginning-of-line 0)
  10854. (list (concat (car parent-target) "/" child) file "" (point))))))
  10855. (defun org-olpath-completing-read (prompt collection &rest args)
  10856. "Read an outline path like a file name."
  10857. (let ((thetable collection))
  10858. (apply #'completing-read
  10859. prompt
  10860. (lambda (string predicate &optional flag)
  10861. (cond
  10862. ((eq flag nil) (try-completion string thetable))
  10863. ((eq flag t)
  10864. (let ((l (length string)))
  10865. (mapcar (lambda (x)
  10866. (let ((r (substring x l))
  10867. (f (if (string-match " ([^)]*)$" x)
  10868. (match-string 0 x)
  10869. "")))
  10870. (if (string-match "/" r)
  10871. (concat string (substring r 0 (match-end 0)) f)
  10872. x)))
  10873. (all-completions string thetable predicate))))
  10874. ;; Exact match?
  10875. ((eq flag 'lambda) (assoc string thetable))))
  10876. args)))
  10877. ;;;; Dynamic blocks
  10878. (defun org-find-dblock (name)
  10879. "Find the first dynamic block with name NAME in the buffer.
  10880. If not found, stay at current position and return nil."
  10881. (let ((case-fold-search t) pos)
  10882. (save-excursion
  10883. (goto-char (point-min))
  10884. (setq pos (and (re-search-forward
  10885. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10886. (match-beginning 0))))
  10887. (when pos (goto-char pos))
  10888. pos))
  10889. (defun org-create-dblock (plist)
  10890. "Create a dynamic block section, with parameters taken from PLIST.
  10891. PLIST must contain a :name entry which is used as the name of the block."
  10892. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10893. (end-of-line 1)
  10894. (newline))
  10895. (let ((col (current-column))
  10896. (name (plist-get plist :name)))
  10897. (insert "#+BEGIN: " name)
  10898. (while plist
  10899. (if (eq (car plist) :name)
  10900. (setq plist (cddr plist))
  10901. (insert " " (prin1-to-string (pop plist)))))
  10902. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10903. (beginning-of-line -2)))
  10904. (defun org-prepare-dblock ()
  10905. "Prepare dynamic block for refresh.
  10906. This empties the block, puts the cursor at the insert position and returns
  10907. the property list including an extra property :name with the block name."
  10908. (unless (looking-at org-dblock-start-re)
  10909. (user-error "Not at a dynamic block"))
  10910. (let* ((begdel (1+ (match-end 0)))
  10911. (name (org-no-properties (match-string 1)))
  10912. (params (append (list :name name)
  10913. (read (concat "(" (match-string 3) ")")))))
  10914. (save-excursion
  10915. (beginning-of-line 1)
  10916. (skip-chars-forward " \t")
  10917. (setq params (plist-put params :indentation-column (current-column))))
  10918. (unless (re-search-forward org-dblock-end-re nil t)
  10919. (error "Dynamic block not terminated"))
  10920. (setq params
  10921. (append params
  10922. (list :content (buffer-substring
  10923. begdel (match-beginning 0)))))
  10924. (delete-region begdel (match-beginning 0))
  10925. (goto-char begdel)
  10926. (open-line 1)
  10927. params))
  10928. (defun org-map-dblocks (&optional command)
  10929. "Apply COMMAND to all dynamic blocks in the current buffer.
  10930. If COMMAND is not given, use `org-update-dblock'."
  10931. (let ((cmd (or command 'org-update-dblock)))
  10932. (save-excursion
  10933. (goto-char (point-min))
  10934. (while (re-search-forward org-dblock-start-re nil t)
  10935. (goto-char (match-beginning 0))
  10936. (save-excursion
  10937. (condition-case nil
  10938. (funcall cmd)
  10939. (error (message "Error during update of dynamic block"))))
  10940. (unless (re-search-forward org-dblock-end-re nil t)
  10941. (error "Dynamic block not terminated"))))))
  10942. (defun org-dblock-update (&optional arg)
  10943. "User command for updating dynamic blocks.
  10944. Update the dynamic block at point. With prefix ARG, update all dynamic
  10945. blocks in the buffer."
  10946. (interactive "P")
  10947. (if arg
  10948. (org-update-all-dblocks)
  10949. (or (looking-at org-dblock-start-re)
  10950. (org-beginning-of-dblock))
  10951. (org-update-dblock)))
  10952. (defun org-update-dblock ()
  10953. "Update the dynamic block at point.
  10954. This means to empty the block, parse for parameters and then call
  10955. the correct writing function."
  10956. (interactive)
  10957. (save-excursion
  10958. (let* ((win (selected-window))
  10959. (pos (point))
  10960. (line (org-current-line))
  10961. (params (org-prepare-dblock))
  10962. (name (plist-get params :name))
  10963. (indent (plist-get params :indentation-column))
  10964. (cmd (intern (concat "org-dblock-write:" name))))
  10965. (message "Updating dynamic block `%s' at line %d..." name line)
  10966. (funcall cmd params)
  10967. (message "Updating dynamic block `%s' at line %d...done" name line)
  10968. (goto-char pos)
  10969. (when (and indent (> indent 0))
  10970. (setq indent (make-string indent ?\ ))
  10971. (save-excursion
  10972. (select-window win)
  10973. (org-beginning-of-dblock)
  10974. (forward-line 1)
  10975. (while (not (looking-at org-dblock-end-re))
  10976. (insert indent)
  10977. (beginning-of-line 2))
  10978. (when (looking-at org-dblock-end-re)
  10979. (and (looking-at "[ \t]+")
  10980. (replace-match ""))
  10981. (insert indent)))))))
  10982. (defun org-beginning-of-dblock ()
  10983. "Find the beginning of the dynamic block at point.
  10984. Error if there is no such block at point."
  10985. (let ((pos (point))
  10986. beg)
  10987. (end-of-line 1)
  10988. (if (and (re-search-backward org-dblock-start-re nil t)
  10989. (setq beg (match-beginning 0))
  10990. (re-search-forward org-dblock-end-re nil t)
  10991. (> (match-end 0) pos))
  10992. (goto-char beg)
  10993. (goto-char pos)
  10994. (error "Not in a dynamic block"))))
  10995. (defun org-update-all-dblocks ()
  10996. "Update all dynamic blocks in the buffer.
  10997. This function can be used in a hook."
  10998. (interactive)
  10999. (when (derived-mode-p 'org-mode)
  11000. (org-map-dblocks 'org-update-dblock)))
  11001. ;;;; Completion
  11002. (declare-function org-export-backend-options "ox" (cl-x) t)
  11003. (defun org-get-export-keywords ()
  11004. "Return a list of all currently understood export keywords.
  11005. Export keywords include options, block names, attributes and
  11006. keywords relative to each registered export back-end."
  11007. (let (keywords)
  11008. (dolist (backend
  11009. (bound-and-true-p org-export-registered-backends)
  11010. (delq nil keywords))
  11011. ;; Back-end name (for keywords, like #+LATEX:)
  11012. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11013. (dolist (option-entry (org-export-backend-options backend))
  11014. ;; Back-end options.
  11015. (push (nth 1 option-entry) keywords)))))
  11016. (defconst org-options-keywords
  11017. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11018. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11019. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11020. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11021. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11022. (defcustom org-structure-template-alist
  11023. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11024. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11025. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11026. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11027. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11028. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11029. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11030. ("L" "#+LaTeX: ")
  11031. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11032. ("H" "#+HTML: ")
  11033. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11034. ("A" "#+ASCII: ")
  11035. ("i" "#+INDEX: ?")
  11036. ("I" "#+INCLUDE: %file ?"))
  11037. "Structure completion elements.
  11038. This is a list of abbreviation keys and values. The value gets inserted
  11039. if you type `<' followed by the key and then press the completion key,
  11040. usually `TAB'. %file will be replaced by a file name after prompting
  11041. for the file using completion. The cursor will be placed at the position
  11042. of the `?' in the template.
  11043. There are two templates for each key, the first uses the original Org syntax,
  11044. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11045. the default when the /org-mtags.el/ module has been loaded. See also the
  11046. variable `org-mtags-prefer-muse-templates'."
  11047. :group 'org-completion
  11048. :type '(repeat
  11049. (list
  11050. (string :tag "Key")
  11051. (string :tag "Template")))
  11052. :version "26.1"
  11053. :package-version '(Org . "8.3"))
  11054. (defun org-try-structure-completion ()
  11055. "Try to complete a structure template before point.
  11056. This looks for strings like \"<e\" on an otherwise empty line and
  11057. expands them."
  11058. (let ((l (buffer-substring (point-at-bol) (point)))
  11059. a)
  11060. (when (and (looking-at "[ \t]*$")
  11061. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11062. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11063. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11064. (match-beginning 1)) a)
  11065. t)))
  11066. (defun org-complete-expand-structure-template (start cell)
  11067. "Expand a structure template."
  11068. (let ((rpl (nth 1 cell))
  11069. (ind ""))
  11070. (delete-region start (point))
  11071. (when (string-match "\\`[ \t]*#\\+" rpl)
  11072. (cond
  11073. ((bolp))
  11074. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11075. (setq ind (buffer-substring (point-at-bol) (point))))
  11076. (t (newline))))
  11077. (setq start (point))
  11078. (when (string-match "%file" rpl)
  11079. (setq rpl (replace-match
  11080. (concat
  11081. "\""
  11082. (save-match-data
  11083. (abbreviate-file-name (read-file-name "Include file: ")))
  11084. "\"")
  11085. t t rpl)))
  11086. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11087. (concat "\n" ind)))
  11088. (insert rpl)
  11089. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11090. ;;;; TODO, DEADLINE, Comments
  11091. (defun org-toggle-comment ()
  11092. "Change the COMMENT state of an entry."
  11093. (interactive)
  11094. (save-excursion
  11095. (org-back-to-heading)
  11096. (let ((case-fold-search nil))
  11097. (looking-at org-complex-heading-regexp))
  11098. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11099. (skip-chars-forward " \t")
  11100. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11101. (if (org-in-commented-heading-p t)
  11102. (delete-region (point)
  11103. (progn (search-forward " " (line-end-position) 'move)
  11104. (skip-chars-forward " \t")
  11105. (point)))
  11106. (insert org-comment-string)
  11107. (unless (eolp) (insert " ")))))
  11108. (defvar org-last-todo-state-is-todo nil
  11109. "This is non-nil when the last TODO state change led to a TODO state.
  11110. If the last change removed the TODO tag or switched to DONE, then
  11111. this is nil.")
  11112. (defvar org-setting-tags nil) ; dynamically skipped
  11113. (defvar org-todo-setup-filter-hook nil
  11114. "Hook for functions that pre-filter todo specs.
  11115. Each function takes a todo spec and returns either nil or the spec
  11116. transformed into canonical form." )
  11117. (defvar org-todo-get-default-hook nil
  11118. "Hook for functions that get a default item for todo.
  11119. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11120. nil or a string to be used for the todo mark." )
  11121. (defvar org-agenda-headline-snapshot-before-repeat)
  11122. (defun org-current-effective-time ()
  11123. "Return current time adjusted for `org-extend-today-until' variable."
  11124. (let* ((ct (org-current-time))
  11125. (dct (decode-time ct))
  11126. (ct1
  11127. (cond
  11128. (org-use-last-clock-out-time-as-effective-time
  11129. (or (org-clock-get-last-clock-out-time) ct))
  11130. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11131. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11132. (t ct))))
  11133. ct1))
  11134. (defun org-todo-yesterday (&optional arg)
  11135. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11136. (interactive "P")
  11137. (if (eq major-mode 'org-agenda-mode)
  11138. (apply 'org-agenda-todo-yesterday arg)
  11139. (let* ((org-use-effective-time t)
  11140. (hour (nth 2 (decode-time (org-current-time))))
  11141. (org-extend-today-until (1+ hour)))
  11142. (org-todo arg))))
  11143. (defvar org-block-entry-blocking ""
  11144. "First entry preventing the TODO state change.")
  11145. (defun org-cancel-repeater ()
  11146. "Cancel a repeater by setting its numeric value to zero."
  11147. (interactive)
  11148. (save-excursion
  11149. (org-back-to-heading t)
  11150. (let ((bound1 (point))
  11151. (bound0 (save-excursion (outline-next-heading) (point))))
  11152. (when (and (re-search-forward
  11153. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11154. org-deadline-time-regexp "\\)\\|\\("
  11155. org-ts-regexp "\\)")
  11156. bound0 t)
  11157. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11158. bound1 t))
  11159. (replace-match "0" t nil nil 1)))))
  11160. (defvar org-state)
  11161. (defvar org-blocked-by-checkboxes)
  11162. (defun org-todo (&optional arg)
  11163. "Change the TODO state of an item.
  11164. The state of an item is given by a keyword at the start of the heading,
  11165. like
  11166. *** TODO Write paper
  11167. *** DONE Call mom
  11168. The different keywords are specified in the variable `org-todo-keywords'.
  11169. By default the available states are \"TODO\" and \"DONE\". So, for this
  11170. example: when the item starts with TODO, it is changed to DONE.
  11171. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11172. DONE are present, add TODO at the beginning of the heading.
  11173. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11174. state.
  11175. With numeric prefix ARG, switch to that state.
  11176. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11177. next set of TODO \
  11178. keywords (nextset).
  11179. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11180. prefix, circumvent any state blocking.
  11181. With a numeric prefix arg of 0, inhibit note taking for the change.
  11182. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11183. When called through ELisp, arg is also interpreted in the following way:
  11184. `none' -> empty state
  11185. \"\" -> switch to empty state
  11186. `done' -> switch to DONE
  11187. `nextset' -> switch to the next set of keywords
  11188. `previousset' -> switch to the previous set of keywords
  11189. \"WAITING\" -> switch to the specified keyword, but only if it
  11190. really is a member of `org-todo-keywords'."
  11191. (interactive "P")
  11192. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11193. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11194. 'region-start-level 'region))
  11195. org-loop-over-headlines-in-active-region)
  11196. (org-map-entries
  11197. `(org-todo ,arg)
  11198. org-loop-over-headlines-in-active-region
  11199. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11200. (when (equal arg '(16)) (setq arg 'nextset))
  11201. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11202. (let ((org-blocker-hook org-blocker-hook)
  11203. commentp
  11204. case-fold-search)
  11205. (when (equal arg '(64))
  11206. (setq arg nil org-blocker-hook nil))
  11207. (when (and org-blocker-hook
  11208. (or org-inhibit-blocking
  11209. (org-entry-get nil "NOBLOCKING")))
  11210. (setq org-blocker-hook nil))
  11211. (save-excursion
  11212. (catch 'exit
  11213. (org-back-to-heading t)
  11214. (when (org-in-commented-heading-p t)
  11215. (org-toggle-comment)
  11216. (setq commentp t))
  11217. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11218. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11219. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11220. (let* ((match-data (match-data))
  11221. (startpos (point-at-bol))
  11222. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11223. (org-log-done org-log-done)
  11224. (org-log-repeat org-log-repeat)
  11225. (org-todo-log-states org-todo-log-states)
  11226. (org-inhibit-logging
  11227. (if (equal arg 0)
  11228. (progn (setq arg nil) 'note) org-inhibit-logging))
  11229. (this (match-string 1))
  11230. (hl-pos (match-beginning 0))
  11231. (head (org-get-todo-sequence-head this))
  11232. (ass (assoc head org-todo-kwd-alist))
  11233. (interpret (nth 1 ass))
  11234. (done-word (nth 3 ass))
  11235. (final-done-word (nth 4 ass))
  11236. (org-last-state (or this ""))
  11237. (completion-ignore-case t)
  11238. (member (member this org-todo-keywords-1))
  11239. (tail (cdr member))
  11240. (org-state (cond
  11241. ((and org-todo-key-trigger
  11242. (or (and (equal arg '(4))
  11243. (eq org-use-fast-todo-selection 'prefix))
  11244. (and (not arg) org-use-fast-todo-selection
  11245. (not (eq org-use-fast-todo-selection
  11246. 'prefix)))))
  11247. ;; Use fast selection.
  11248. (org-fast-todo-selection))
  11249. ((and (equal arg '(4))
  11250. (or (not org-use-fast-todo-selection)
  11251. (not org-todo-key-trigger)))
  11252. ;; Read a state with completion.
  11253. (completing-read
  11254. "State: " (mapcar #'list org-todo-keywords-1)
  11255. nil t))
  11256. ((eq arg 'right)
  11257. (if this
  11258. (if tail (car tail) nil)
  11259. (car org-todo-keywords-1)))
  11260. ((eq arg 'left)
  11261. (unless (equal member org-todo-keywords-1)
  11262. (if this
  11263. (nth (- (length org-todo-keywords-1)
  11264. (length tail) 2)
  11265. org-todo-keywords-1)
  11266. (org-last org-todo-keywords-1))))
  11267. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11268. (setq arg nil))) ;hack to fall back to cycling
  11269. (arg
  11270. ;; User or caller requests a specific state.
  11271. (cond
  11272. ((equal arg "") nil)
  11273. ((eq arg 'none) nil)
  11274. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11275. ((eq arg 'nextset)
  11276. (or (car (cdr (member head org-todo-heads)))
  11277. (car org-todo-heads)))
  11278. ((eq arg 'previousset)
  11279. (let ((org-todo-heads (reverse org-todo-heads)))
  11280. (or (car (cdr (member head org-todo-heads)))
  11281. (car org-todo-heads))))
  11282. ((car (member arg org-todo-keywords-1)))
  11283. ((stringp arg)
  11284. (user-error "State `%s' not valid in this file" arg))
  11285. ((nth (1- (prefix-numeric-value arg))
  11286. org-todo-keywords-1))))
  11287. ((null member) (or head (car org-todo-keywords-1)))
  11288. ((equal this final-done-word) nil) ;-> make empty
  11289. ((null tail) nil) ;-> first entry
  11290. ((memq interpret '(type priority))
  11291. (if (eq this-command last-command)
  11292. (car tail)
  11293. (if (> (length tail) 0)
  11294. (or done-word (car org-done-keywords))
  11295. nil)))
  11296. (t
  11297. (car tail))))
  11298. (org-state (or
  11299. (run-hook-with-args-until-success
  11300. 'org-todo-get-default-hook org-state org-last-state)
  11301. org-state))
  11302. (next (if org-state (concat " " org-state " ") " "))
  11303. (change-plist (list :type 'todo-state-change :from this :to org-state
  11304. :position startpos))
  11305. dolog now-done-p)
  11306. (when org-blocker-hook
  11307. (let (org-blocked-by-checkboxes block-reason)
  11308. (setq org-last-todo-state-is-todo
  11309. (not (member this org-done-keywords)))
  11310. (unless (save-excursion
  11311. (save-match-data
  11312. (org-with-wide-buffer
  11313. (run-hook-with-args-until-failure
  11314. 'org-blocker-hook change-plist))))
  11315. (setq block-reason (if org-blocked-by-checkboxes
  11316. "contained checkboxes"
  11317. (format "\"%s\"" org-block-entry-blocking)))
  11318. (if (called-interactively-p 'interactive)
  11319. (user-error "TODO state change from %s to %s blocked (by %s)"
  11320. this org-state block-reason)
  11321. ;; Fail silently.
  11322. (message "TODO state change from %s to %s blocked (by %s)"
  11323. this org-state block-reason)
  11324. (throw 'exit nil)))))
  11325. (store-match-data match-data)
  11326. (replace-match next t t)
  11327. (cond ((equal this org-state)
  11328. (message "TODO state was already %s" (org-trim next)))
  11329. ((pos-visible-in-window-p hl-pos)
  11330. (message "TODO state changed to %s" (org-trim next))))
  11331. (unless head
  11332. (setq head (org-get-todo-sequence-head org-state)
  11333. ass (assoc head org-todo-kwd-alist)
  11334. interpret (nth 1 ass)
  11335. done-word (nth 3 ass)
  11336. final-done-word (nth 4 ass)))
  11337. (when (memq arg '(nextset previousset))
  11338. (message "Keyword-Set %d/%d: %s"
  11339. (- (length org-todo-sets) -1
  11340. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11341. (length org-todo-sets)
  11342. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11343. (setq org-last-todo-state-is-todo
  11344. (not (member org-state org-done-keywords)))
  11345. (setq now-done-p (and (member org-state org-done-keywords)
  11346. (not (member this org-done-keywords))))
  11347. (and logging (org-local-logging logging))
  11348. (when (and (or org-todo-log-states org-log-done)
  11349. (not (eq org-inhibit-logging t))
  11350. (not (memq arg '(nextset previousset))))
  11351. ;; We need to look at recording a time and note.
  11352. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11353. (nth 2 (assoc this org-todo-log-states))))
  11354. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11355. (setq dolog 'time))
  11356. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11357. (and org-state
  11358. (member org-state org-not-done-keywords)
  11359. (not (member this org-not-done-keywords))))
  11360. ;; This is now a todo state and was not one before
  11361. ;; If there was a CLOSED time stamp, get rid of it.
  11362. (org-add-planning-info nil nil 'closed))
  11363. (when (and now-done-p org-log-done)
  11364. ;; It is now done, and it was not done before.
  11365. (org-add-planning-info 'closed (org-current-effective-time))
  11366. (when (and (not dolog) (eq 'note org-log-done))
  11367. (org-add-log-setup 'done org-state this 'note)))
  11368. (when (and org-state dolog)
  11369. ;; This is a non-nil state, and we need to log it.
  11370. (org-add-log-setup 'state org-state this dolog)))
  11371. ;; Fixup tag positioning.
  11372. (org-todo-trigger-tag-changes org-state)
  11373. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11374. (when org-provide-todo-statistics
  11375. (org-update-parent-todo-statistics))
  11376. (run-hooks 'org-after-todo-state-change-hook)
  11377. (when (and arg (not (member org-state org-done-keywords)))
  11378. (setq head (org-get-todo-sequence-head org-state)))
  11379. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11380. ;; Do we need to trigger a repeat?
  11381. (when now-done-p
  11382. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11383. ;; This is for the agenda, take a snapshot of the headline.
  11384. (save-match-data
  11385. (setq org-agenda-headline-snapshot-before-repeat
  11386. (org-get-heading))))
  11387. (org-auto-repeat-maybe org-state))
  11388. ;; Fixup cursor location if close to the keyword.
  11389. (when (and (outline-on-heading-p)
  11390. (not (bolp))
  11391. (save-excursion (beginning-of-line 1)
  11392. (looking-at org-todo-line-regexp))
  11393. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11394. (goto-char (or (match-end 2) (match-end 1)))
  11395. (and (looking-at " ") (just-one-space)))
  11396. (when org-trigger-hook
  11397. (save-excursion
  11398. (run-hook-with-args 'org-trigger-hook change-plist)))
  11399. (when commentp (org-toggle-comment))))))))
  11400. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11401. "Block turning an entry into a TODO, using the hierarchy.
  11402. This checks whether the current task should be blocked from state
  11403. changes. Such blocking occurs when:
  11404. 1. The task has children which are not all in a completed state.
  11405. 2. A task has a parent with the property :ORDERED:, and there
  11406. are siblings prior to the current task with incomplete
  11407. status.
  11408. 3. The parent of the task is blocked because it has siblings that should
  11409. be done first, or is child of a block grandparent TODO entry."
  11410. (if (not org-enforce-todo-dependencies)
  11411. t ; if locally turned off don't block
  11412. (catch 'dont-block
  11413. ;; If this is not a todo state change, or if this entry is already DONE,
  11414. ;; do not block
  11415. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11416. (member (plist-get change-plist :from)
  11417. (cons 'done org-done-keywords))
  11418. (member (plist-get change-plist :to)
  11419. (cons 'todo org-not-done-keywords))
  11420. (not (plist-get change-plist :to)))
  11421. (throw 'dont-block t))
  11422. ;; If this task has children, and any are undone, it's blocked
  11423. (save-excursion
  11424. (org-back-to-heading t)
  11425. (let ((this-level (funcall outline-level)))
  11426. (outline-next-heading)
  11427. (let ((child-level (funcall outline-level)))
  11428. (while (and (not (eobp))
  11429. (> child-level this-level))
  11430. ;; this todo has children, check whether they are all
  11431. ;; completed
  11432. (when (and (not (org-entry-is-done-p))
  11433. (org-entry-is-todo-p))
  11434. (setq org-block-entry-blocking (org-get-heading))
  11435. (throw 'dont-block nil))
  11436. (outline-next-heading)
  11437. (setq child-level (funcall outline-level))))))
  11438. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11439. ;; any previous siblings are undone, it's blocked
  11440. (save-excursion
  11441. (org-back-to-heading t)
  11442. (let* ((pos (point))
  11443. (parent-pos (and (org-up-heading-safe) (point)))
  11444. (case-fold-search nil))
  11445. (unless parent-pos (throw 'dont-block t)) ; no parent
  11446. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11447. (forward-line 1)
  11448. (re-search-forward org-not-done-heading-regexp pos t))
  11449. (setq org-block-entry-blocking (match-string 0))
  11450. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11451. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11452. (while t
  11453. (goto-char parent-pos)
  11454. (unless (looking-at org-not-done-heading-regexp)
  11455. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11456. (setq pos (point))
  11457. (setq parent-pos (and (org-up-heading-safe) (point)))
  11458. (unless parent-pos (throw 'dont-block t)) ; no parent
  11459. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11460. (forward-line 1)
  11461. (re-search-forward org-not-done-heading-regexp pos t)
  11462. (setq org-block-entry-blocking (org-get-heading)))
  11463. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11464. (defcustom org-track-ordered-property-with-tag nil
  11465. "Should the ORDERED property also be shown as a tag?
  11466. The ORDERED property decides if an entry should require subtasks to be
  11467. completed in sequence. Since a property is not very visible, setting
  11468. this option means that toggling the ORDERED property with the command
  11469. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11470. not relevant for the behavior, but it makes things more visible.
  11471. Note that toggling the tag with tags commands will not change the property
  11472. and therefore not influence behavior!
  11473. This can be t, meaning the tag ORDERED should be used, It can also be a
  11474. string to select a different tag for this task."
  11475. :group 'org-todo
  11476. :type '(choice
  11477. (const :tag "No tracking" nil)
  11478. (const :tag "Track with ORDERED tag" t)
  11479. (string :tag "Use other tag")))
  11480. (defun org-toggle-ordered-property ()
  11481. "Toggle the ORDERED property of the current entry.
  11482. For better visibility, you can track the value of this property with a tag.
  11483. See variable `org-track-ordered-property-with-tag'."
  11484. (interactive)
  11485. (let* ((t1 org-track-ordered-property-with-tag)
  11486. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11487. (save-excursion
  11488. (org-back-to-heading)
  11489. (if (org-entry-get nil "ORDERED")
  11490. (progn
  11491. (org-delete-property "ORDERED")
  11492. (and tag (org-toggle-tag tag 'off))
  11493. (message "Subtasks can be completed in arbitrary order"))
  11494. (org-entry-put nil "ORDERED" "t")
  11495. (and tag (org-toggle-tag tag 'on))
  11496. (message "Subtasks must be completed in sequence")))))
  11497. (defun org-block-todo-from-checkboxes (change-plist)
  11498. "Block turning an entry into a TODO, using checkboxes.
  11499. This checks whether the current task should be blocked from state
  11500. changes because there are unchecked boxes in this entry."
  11501. (if (not org-enforce-todo-checkbox-dependencies)
  11502. t ; if locally turned off don't block
  11503. (catch 'dont-block
  11504. ;; If this is not a todo state change, or if this entry is already DONE,
  11505. ;; do not block
  11506. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11507. (member (plist-get change-plist :from)
  11508. (cons 'done org-done-keywords))
  11509. (member (plist-get change-plist :to)
  11510. (cons 'todo org-not-done-keywords))
  11511. (not (plist-get change-plist :to)))
  11512. (throw 'dont-block t))
  11513. ;; If this task has checkboxes that are not checked, it's blocked
  11514. (save-excursion
  11515. (org-back-to-heading t)
  11516. (let ((beg (point)) end)
  11517. (outline-next-heading)
  11518. (setq end (point))
  11519. (goto-char beg)
  11520. (when (org-list-search-forward
  11521. (concat (org-item-beginning-re)
  11522. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11523. "\\[[- ]\\]")
  11524. end t)
  11525. (when (boundp 'org-blocked-by-checkboxes)
  11526. (setq org-blocked-by-checkboxes t))
  11527. (throw 'dont-block nil))))
  11528. t))) ; do not block
  11529. (defun org-entry-blocked-p ()
  11530. "Non-nil if entry at point is blocked."
  11531. (and (not (org-entry-get nil "NOBLOCKING"))
  11532. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11533. (not (run-hook-with-args-until-failure
  11534. 'org-blocker-hook
  11535. (list :type 'todo-state-change
  11536. :position (point)
  11537. :from 'todo
  11538. :to 'done)))))
  11539. (defun org-update-statistics-cookies (all)
  11540. "Update the statistics cookie, either from TODO or from checkboxes.
  11541. This should be called with the cursor in a line with a statistics
  11542. cookie. When called with a \\[universal-argument] prefix, update
  11543. all statistics cookies in the buffer."
  11544. (interactive "P")
  11545. (if all
  11546. (progn
  11547. (org-update-checkbox-count 'all)
  11548. (org-map-entries 'org-update-parent-todo-statistics))
  11549. (if (not (org-at-heading-p))
  11550. (org-update-checkbox-count)
  11551. (let ((pos (point-marker))
  11552. end l1 l2)
  11553. (ignore-errors (org-back-to-heading t))
  11554. (if (not (org-at-heading-p))
  11555. (org-update-checkbox-count)
  11556. (setq l1 (org-outline-level))
  11557. (setq end (save-excursion
  11558. (outline-next-heading)
  11559. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11560. (point)))
  11561. (if (and (save-excursion
  11562. (re-search-forward
  11563. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11564. (not (save-excursion (re-search-forward
  11565. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11566. (org-update-checkbox-count)
  11567. (if (and l2 (> l2 l1))
  11568. (progn
  11569. (goto-char end)
  11570. (org-update-parent-todo-statistics))
  11571. (goto-char pos)
  11572. (beginning-of-line 1)
  11573. (while (re-search-forward
  11574. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11575. (point-at-eol) t)
  11576. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11577. (goto-char pos)
  11578. (move-marker pos nil)))))
  11579. (defvar org-entry-property-inherited-from) ;; defined below
  11580. (defun org-update-parent-todo-statistics ()
  11581. "Update any statistics cookie in the parent of the current headline.
  11582. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11583. the entire subtree and this will travel up the hierarchy and update
  11584. statistics everywhere."
  11585. (let* ((prop (save-excursion (org-up-heading-safe)
  11586. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11587. (recursive (or (not org-hierarchical-todo-statistics)
  11588. (and prop (string-match "\\<recursive\\>" prop))))
  11589. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11590. 0))
  11591. (first t)
  11592. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11593. level ltoggle l1 new ndel
  11594. (cnt-all 0) (cnt-done 0) is-percent kwd
  11595. checkbox-beg cookie-present)
  11596. (catch 'exit
  11597. (save-excursion
  11598. (beginning-of-line 1)
  11599. (setq ltoggle (funcall outline-level))
  11600. ;; Three situations are to consider:
  11601. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11602. ;; to the top-level ancestor on the headline;
  11603. ;; 2. If parent has "recursive" property, repeat up to the
  11604. ;; headline setting that property, taking inheritance into
  11605. ;; account;
  11606. ;; 3. Else, move up to direct parent and proceed only once.
  11607. (while (and (setq level (org-up-heading-safe))
  11608. (or recursive first)
  11609. (>= (point) lim))
  11610. (setq first nil cookie-present nil)
  11611. (unless (and level
  11612. (not (string-match
  11613. "\\<checkbox\\>"
  11614. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11615. "")))))
  11616. (throw 'exit nil))
  11617. (while (re-search-forward box-re (point-at-eol) t)
  11618. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11619. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11620. (save-match-data
  11621. (unless (outline-next-heading) (throw 'exit nil))
  11622. (while (and (looking-at org-complex-heading-regexp)
  11623. (> (setq l1 (length (match-string 1))) level))
  11624. (setq kwd (and (or recursive (= l1 ltoggle))
  11625. (match-string 2)))
  11626. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11627. (and (eq org-provide-todo-statistics t)
  11628. (or (member kwd org-done-keywords)))
  11629. (and (listp org-provide-todo-statistics)
  11630. (stringp (car org-provide-todo-statistics))
  11631. (or (member kwd org-provide-todo-statistics)
  11632. (member kwd org-done-keywords)))
  11633. (and (listp org-provide-todo-statistics)
  11634. (listp (car org-provide-todo-statistics))
  11635. (or (member kwd (car org-provide-todo-statistics))
  11636. (and (member kwd org-done-keywords)
  11637. (member kwd (cadr org-provide-todo-statistics))))))
  11638. (setq cnt-all (1+ cnt-all))
  11639. (and (eq org-provide-todo-statistics t)
  11640. kwd
  11641. (setq cnt-all (1+ cnt-all))))
  11642. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11643. (member kwd org-done-keywords))
  11644. (and (listp org-provide-todo-statistics)
  11645. (listp (car org-provide-todo-statistics))
  11646. (member kwd org-done-keywords)
  11647. (member kwd (cadr org-provide-todo-statistics)))
  11648. (and (listp org-provide-todo-statistics)
  11649. (stringp (car org-provide-todo-statistics))
  11650. (member kwd org-done-keywords)))
  11651. (setq cnt-done (1+ cnt-done)))
  11652. (outline-next-heading)))
  11653. (setq new
  11654. (if is-percent
  11655. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11656. (max 1 cnt-all)))
  11657. (format "[%d/%d]" cnt-done cnt-all))
  11658. ndel (- (match-end 0) checkbox-beg))
  11659. (goto-char checkbox-beg)
  11660. (insert new)
  11661. (delete-region (point) (+ (point) ndel))
  11662. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11663. (when cookie-present
  11664. (run-hook-with-args 'org-after-todo-statistics-hook
  11665. cnt-done (- cnt-all cnt-done))))))
  11666. (run-hooks 'org-todo-statistics-hook)))
  11667. (defvar org-after-todo-statistics-hook nil
  11668. "Hook that is called after a TODO statistics cookie has been updated.
  11669. Each function is called with two arguments: the number of not-done entries
  11670. and the number of done entries.
  11671. For example, the following function, when added to this hook, will switch
  11672. an entry to DONE when all children are done, and back to TODO when new
  11673. entries are set to a TODO status. Note that this hook is only called
  11674. when there is a statistics cookie in the headline!
  11675. (defun org-summary-todo (n-done n-not-done)
  11676. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11677. (let (org-log-done org-log-states) ; turn off logging
  11678. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11679. ")
  11680. (defvar org-todo-statistics-hook nil
  11681. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11682. This hook runs even if there is no statistics cookie present, in which case
  11683. `org-after-todo-statistics-hook' would not run.")
  11684. (defun org-todo-trigger-tag-changes (state)
  11685. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11686. (let ((l org-todo-state-tags-triggers)
  11687. changes)
  11688. (when (or (not state) (equal state ""))
  11689. (setq changes (append changes (cdr (assoc "" l)))))
  11690. (when (and (stringp state) (> (length state) 0))
  11691. (setq changes (append changes (cdr (assoc state l)))))
  11692. (when (member state org-not-done-keywords)
  11693. (setq changes (append changes (cdr (assq 'todo l)))))
  11694. (when (member state org-done-keywords)
  11695. (setq changes (append changes (cdr (assq 'done l)))))
  11696. (dolist (c changes)
  11697. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11698. (defun org-local-logging (value)
  11699. "Get logging settings from a property VALUE."
  11700. ;; Directly set the variables, they are already local.
  11701. (setq org-log-done nil
  11702. org-log-repeat nil
  11703. org-todo-log-states nil)
  11704. (dolist (w (org-split-string value))
  11705. (let (a)
  11706. (cond
  11707. ((setq a (assoc w org-startup-options))
  11708. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11709. (set (nth 1 a) (nth 2 a))))
  11710. ((setq a (org-extract-log-state-settings w))
  11711. (and (member (car a) org-todo-keywords-1)
  11712. (push a org-todo-log-states)))))))
  11713. (defun org-get-todo-sequence-head (kwd)
  11714. "Return the head of the TODO sequence to which KWD belongs.
  11715. If KWD is not set, check if there is a text property remembering the
  11716. right sequence."
  11717. (let (p)
  11718. (cond
  11719. ((not kwd)
  11720. (or (get-text-property (point-at-bol) 'org-todo-head)
  11721. (progn
  11722. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11723. nil (point-at-eol)))
  11724. (get-text-property p 'org-todo-head))))
  11725. ((not (member kwd org-todo-keywords-1))
  11726. (car org-todo-keywords-1))
  11727. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11728. (defun org-fast-todo-selection ()
  11729. "Fast TODO keyword selection with single keys.
  11730. Returns the new TODO keyword, or nil if no state change should occur."
  11731. (let* ((fulltable org-todo-key-alist)
  11732. (done-keywords org-done-keywords) ;; needed for the faces.
  11733. (maxlen (apply 'max (mapcar
  11734. (lambda (x)
  11735. (if (stringp (car x)) (string-width (car x)) 0))
  11736. fulltable)))
  11737. (expert nil)
  11738. (fwidth (+ maxlen 3 1 3))
  11739. (ncol (/ (- (window-width) 4) fwidth))
  11740. tg cnt e c tbl
  11741. groups ingroup)
  11742. (save-excursion
  11743. (save-window-excursion
  11744. (if expert
  11745. (set-buffer (get-buffer-create " *Org todo*"))
  11746. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11747. (erase-buffer)
  11748. (setq-local org-done-keywords done-keywords)
  11749. (setq tbl fulltable cnt 0)
  11750. (while (setq e (pop tbl))
  11751. (cond
  11752. ((equal e '(:startgroup))
  11753. (push '() groups) (setq ingroup t)
  11754. (unless (= cnt 0)
  11755. (setq cnt 0)
  11756. (insert "\n"))
  11757. (insert "{ "))
  11758. ((equal e '(:endgroup))
  11759. (setq ingroup nil cnt 0)
  11760. (insert "}\n"))
  11761. ((equal e '(:newline))
  11762. (unless (= cnt 0)
  11763. (setq cnt 0)
  11764. (insert "\n")
  11765. (setq e (car tbl))
  11766. (while (equal (car tbl) '(:newline))
  11767. (insert "\n")
  11768. (setq tbl (cdr tbl)))))
  11769. (t
  11770. (setq tg (car e) c (cdr e))
  11771. (when ingroup (push tg (car groups)))
  11772. (setq tg (org-add-props tg nil 'face
  11773. (org-get-todo-face tg)))
  11774. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11775. (insert "[" c "] " tg (make-string
  11776. (- fwidth 4 (length tg)) ?\ ))
  11777. (when (= (setq cnt (1+ cnt)) ncol)
  11778. (insert "\n")
  11779. (when ingroup (insert " "))
  11780. (setq cnt 0)))))
  11781. (insert "\n")
  11782. (goto-char (point-min))
  11783. (unless expert (org-fit-window-to-buffer))
  11784. (message "[a-z..]:Set [SPC]:clear")
  11785. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11786. (cond
  11787. ((or (= c ?\C-g)
  11788. (and (= c ?q) (not (rassoc c fulltable))))
  11789. (setq quit-flag t))
  11790. ((= c ?\ ) nil)
  11791. ((setq e (rassoc c fulltable) tg (car e))
  11792. tg)
  11793. (t (setq quit-flag t)))))))
  11794. (defun org-entry-is-todo-p ()
  11795. (member (org-get-todo-state) org-not-done-keywords))
  11796. (defun org-entry-is-done-p ()
  11797. (member (org-get-todo-state) org-done-keywords))
  11798. (defun org-get-todo-state ()
  11799. "Return the TODO keyword of the current subtree."
  11800. (save-excursion
  11801. (org-back-to-heading t)
  11802. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11803. (match-end 2)
  11804. (match-string 2))))
  11805. (defun org-at-date-range-p (&optional inactive-ok)
  11806. "Non-nil if point is inside a date range.
  11807. When optional argument INACTIVE-OK is non-nil, also consider
  11808. inactive time ranges.
  11809. When this function returns a non-nil value, match data is set
  11810. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11811. on INACTIVE-OK."
  11812. (interactive)
  11813. (save-excursion
  11814. (catch 'exit
  11815. (let ((pos (point)))
  11816. (skip-chars-backward "^[<\r\n")
  11817. (skip-chars-backward "<[")
  11818. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11819. (>= (match-end 0) pos)
  11820. (throw 'exit t))
  11821. (skip-chars-backward "^<[\r\n")
  11822. (skip-chars-backward "<[")
  11823. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11824. (>= (match-end 0) pos)
  11825. (throw 'exit t)))
  11826. nil)))
  11827. (defun org-get-repeat (&optional timestamp)
  11828. "Check if there is a time-stamp with repeater in this entry.
  11829. Return the repeater, as a string, or nil. Also return nil when
  11830. this function is called before first heading.
  11831. When optional argument TIMESTAMP is a string, extract the
  11832. repeater from there instead."
  11833. (save-match-data
  11834. (cond (timestamp
  11835. (and (string-match org-repeat-re timestamp)
  11836. (match-string-no-properties 1 timestamp)))
  11837. ((org-before-first-heading-p) nil)
  11838. (t
  11839. (save-excursion
  11840. (org-back-to-heading t)
  11841. (let ((end (org-entry-end-position)))
  11842. (catch :repeat
  11843. (while (re-search-forward org-repeat-re end t)
  11844. (when (save-match-data (org-at-timestamp-p 'agenda))
  11845. (throw :repeat (match-string-no-properties 1)))))))))))
  11846. (defvar org-last-changed-timestamp)
  11847. (defvar org-last-inserted-timestamp)
  11848. (defvar org-log-post-message)
  11849. (defvar org-log-note-purpose)
  11850. (defvar org-log-note-how nil)
  11851. (defvar org-log-note-extra)
  11852. (defun org-auto-repeat-maybe (done-word)
  11853. "Check if the current headline contains a repeated time-stamp.
  11854. If yes, set TODO state back to what it was and change the base date
  11855. of repeating deadline/scheduled time stamps to new date.
  11856. This function is run automatically after each state change to a DONE state."
  11857. (let* ((repeat (org-get-repeat))
  11858. (aa (assoc org-last-state org-todo-kwd-alist))
  11859. (interpret (nth 1 aa))
  11860. (head (nth 2 aa))
  11861. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11862. (msg "Entry repeats: ")
  11863. (org-log-done nil)
  11864. (org-todo-log-states nil)
  11865. (end (copy-marker (org-entry-end-position))))
  11866. (unwind-protect
  11867. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11868. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11869. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11870. org-todo-repeat-to-state)))
  11871. (org-todo (cond
  11872. ((and to-state (member to-state org-todo-keywords-1))
  11873. to-state)
  11874. ((eq interpret 'type) org-last-state)
  11875. (head)
  11876. (t 'none))))
  11877. (org-back-to-heading t)
  11878. (org-add-planning-info nil nil 'closed)
  11879. ;; When `org-log-repeat' is non-nil or entry contains
  11880. ;; a clock, set LAST_REPEAT property.
  11881. (when (or org-log-repeat
  11882. (catch :clock
  11883. (while (re-search-forward org-clock-line-re end t)
  11884. (when (org-at-clock-log-p) (throw :clock t)))))
  11885. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11886. (org-time-stamp-format t t)
  11887. (current-time))))
  11888. (when org-log-repeat
  11889. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11890. (memq 'org-add-log-note post-command-hook))
  11891. ;; We are already setup for some record.
  11892. (when (eq org-log-repeat 'note)
  11893. ;; Make sure we take a note, not only a time stamp.
  11894. (setq org-log-note-how 'note))
  11895. ;; Set up for taking a record.
  11896. (org-add-log-setup 'state
  11897. (or done-word (car org-done-keywords))
  11898. org-last-state
  11899. org-log-repeat)))
  11900. (let ((planning-re (regexp-opt
  11901. (list org-scheduled-string org-deadline-string))))
  11902. (while (re-search-forward org-ts-regexp end t)
  11903. (let* ((ts (match-string 0))
  11904. (planning? (org-at-planning-p))
  11905. (type (if (not planning?) "Plain:"
  11906. (save-excursion
  11907. (re-search-backward
  11908. planning-re (line-beginning-position) t)
  11909. (match-string 0)))))
  11910. (cond
  11911. ;; Ignore fake time-stamps (e.g., within comments).
  11912. ((not (org-at-timestamp-p 'agenda)))
  11913. ;; Time-stamps without a repeater are usually
  11914. ;; skipped. However, a SCHEDULED time-stamp without
  11915. ;; one is removed, as they are no longer relevant.
  11916. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11917. ts))
  11918. (when (equal type org-scheduled-string)
  11919. (org-remove-timestamp-with-keyword type)))
  11920. (t
  11921. (let ((n (string-to-number (match-string 2 ts)))
  11922. (what (match-string 3 ts)))
  11923. (when (equal what "w") (setq n (* n 7) what "d"))
  11924. (when (and (equal what "h")
  11925. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11926. ts)))
  11927. (user-error
  11928. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11929. has been set"
  11930. n))
  11931. ;; Preparation, see if we need to modify the start
  11932. ;; date for the change.
  11933. (when (match-end 1)
  11934. (let ((time (save-match-data
  11935. (org-time-string-to-time ts))))
  11936. (cond
  11937. ((equal (match-string 1 ts) ".")
  11938. ;; Shift starting date to today
  11939. (org-timestamp-change
  11940. (- (org-today) (time-to-days time))
  11941. 'day))
  11942. ((equal (match-string 1 ts) "+")
  11943. (let ((nshiftmax 10)
  11944. (nshift 0))
  11945. (while (or (= nshift 0)
  11946. (not (time-less-p (current-time) time)))
  11947. (when (= (cl-incf nshift) nshiftmax)
  11948. (or (y-or-n-p
  11949. (format "%d repeater intervals were not \
  11950. enough to shift date past today. Continue? "
  11951. nshift))
  11952. (user-error "Abort")))
  11953. (org-timestamp-change n (cdr (assoc what whata)))
  11954. (org-in-regexp org-ts-regexp3)
  11955. (setq ts (match-string 1))
  11956. (setq time
  11957. (save-match-data
  11958. (org-time-string-to-time ts)))))
  11959. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11960. ;; Rematch, so that we have everything in place
  11961. ;; for the real shift.
  11962. (org-in-regexp org-ts-regexp3)
  11963. (setq ts (match-string 1))
  11964. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11965. ts)))))
  11966. (save-excursion
  11967. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11968. (setq msg
  11969. (concat
  11970. msg type " " org-last-changed-timestamp " "))))))))
  11971. (setq org-log-post-message msg)
  11972. (message "%s" msg))
  11973. (set-marker end nil))))
  11974. (defun org-show-todo-tree (arg)
  11975. "Make a compact tree which shows all headlines marked with TODO.
  11976. The tree will show the lines where the regexp matches, and all higher
  11977. headlines above the match.
  11978. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11979. With a numeric prefix N, construct a sparse tree for the Nth element
  11980. of `org-todo-keywords-1'."
  11981. (interactive "P")
  11982. (let ((case-fold-search nil)
  11983. (kwd-re
  11984. (cond ((null arg) org-not-done-regexp)
  11985. ((equal arg '(4))
  11986. (let ((kwd
  11987. (completing-read "Keyword (or KWD1|KWD2|...): "
  11988. (mapcar #'list org-todo-keywords-1))))
  11989. (concat "\\("
  11990. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11991. "\\)\\>")))
  11992. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11993. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11994. org-todo-keywords-1)))
  11995. (t (user-error "Invalid prefix argument: %s" arg)))))
  11996. (message "%d TODO entries found"
  11997. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11998. (defun org--deadline-or-schedule (arg type time)
  11999. "Insert DEADLINE or SCHEDULE information in current entry.
  12000. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  12001. `org-schedule' for information about ARG and TIME arguments."
  12002. (let* ((deadline? (eq type 'deadline))
  12003. (keyword (if deadline? org-deadline-string org-scheduled-string))
  12004. (log (if deadline? org-log-redeadline org-log-reschedule))
  12005. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  12006. (old-date-time (and old-date (org-time-string-to-time old-date)))
  12007. ;; Save repeater cookie from either TIME or current scheduled
  12008. ;; time stamp. We are going to insert it back at the end of
  12009. ;; the process.
  12010. (repeater (or (and (org-string-nw-p time)
  12011. ;; We use `org-repeat-re' because we need
  12012. ;; to tell the difference between a real
  12013. ;; repeater and a time delta, e.g. "+2d".
  12014. (string-match org-repeat-re time)
  12015. (match-string 1 time))
  12016. (and (org-string-nw-p old-date)
  12017. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  12018. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  12019. old-date)
  12020. (match-string 1 old-date)))))
  12021. (pcase arg
  12022. (`(4)
  12023. (when (and old-date log)
  12024. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  12025. nil old-date log))
  12026. (org-remove-timestamp-with-keyword keyword)
  12027. (message (if deadline? "Item no longer has a deadline."
  12028. "Item is no longer scheduled.")))
  12029. (`(16)
  12030. (save-excursion
  12031. (org-back-to-heading t)
  12032. (let ((regexp (if deadline? org-deadline-time-regexp
  12033. org-scheduled-time-regexp)))
  12034. (if (not (re-search-forward regexp (line-end-position 2) t))
  12035. (user-error (if deadline? "No deadline information to update"
  12036. "No scheduled information to update"))
  12037. (let* ((rpl0 (match-string 1))
  12038. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  12039. (msg (if deadline? "Warn starting from" "Delay until")))
  12040. (replace-match
  12041. (concat keyword
  12042. " <" rpl
  12043. (format " -%dd"
  12044. (abs (- (time-to-days
  12045. (save-match-data
  12046. (org-read-date
  12047. nil t nil msg old-date-time)))
  12048. (time-to-days old-date-time))))
  12049. ">") t t))))))
  12050. (_
  12051. (org-add-planning-info type time 'closed)
  12052. (when (and old-date
  12053. log
  12054. (not (equal old-date org-last-inserted-timestamp)))
  12055. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  12056. org-last-inserted-timestamp
  12057. old-date
  12058. log))
  12059. (when repeater
  12060. (save-excursion
  12061. (org-back-to-heading t)
  12062. (when (re-search-forward
  12063. (concat keyword " " org-last-inserted-timestamp)
  12064. (line-end-position 2)
  12065. t)
  12066. (goto-char (1- (match-end 0)))
  12067. (insert " " repeater)
  12068. (setq org-last-inserted-timestamp
  12069. (concat (substring org-last-inserted-timestamp 0 -1)
  12070. " " repeater
  12071. (substring org-last-inserted-timestamp -1))))))
  12072. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  12073. org-last-inserted-timestamp)))))
  12074. (defun org-deadline (arg &optional time)
  12075. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12076. With one universal prefix argument, remove any deadline from the item.
  12077. With two universal prefix arguments, prompt for a warning delay.
  12078. With argument TIME, set the deadline at the corresponding date. TIME
  12079. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12080. (interactive "P")
  12081. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12082. (org-map-entries
  12083. (lambda () (org--deadline-or-schedule arg 'deadline time))
  12084. nil
  12085. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12086. 'region-start-level
  12087. 'region)
  12088. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12089. (org--deadline-or-schedule arg 'deadline time)))
  12090. (defun org-schedule (arg &optional time)
  12091. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12092. With one universal prefix argument, remove any scheduling date from the item.
  12093. With two universal prefix arguments, prompt for a delay cookie.
  12094. With argument TIME, scheduled at the corresponding date. TIME can
  12095. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12096. (interactive "P")
  12097. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12098. (org-map-entries
  12099. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12100. nil
  12101. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12102. 'region-start-level
  12103. 'region)
  12104. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12105. (org--deadline-or-schedule arg 'scheduled time)))
  12106. (defun org-get-scheduled-time (pom &optional inherit)
  12107. "Get the scheduled time as a time tuple, of a format suitable
  12108. for calling org-schedule with, or if there is no scheduling,
  12109. returns nil."
  12110. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12111. (when time
  12112. (apply 'encode-time (org-parse-time-string time)))))
  12113. (defun org-get-deadline-time (pom &optional inherit)
  12114. "Get the deadline as a time tuple, of a format suitable for
  12115. calling org-deadline with, or if there is no scheduling, returns
  12116. nil."
  12117. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12118. (when time
  12119. (apply 'encode-time (org-parse-time-string time)))))
  12120. (defun org-remove-timestamp-with-keyword (keyword)
  12121. "Remove all time stamps with KEYWORD in the current entry."
  12122. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12123. beg)
  12124. (save-excursion
  12125. (org-back-to-heading t)
  12126. (setq beg (point))
  12127. (outline-next-heading)
  12128. (while (re-search-backward re beg t)
  12129. (replace-match "")
  12130. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12131. (equal (char-before) ?\ ))
  12132. (backward-delete-char 1)
  12133. (when (string-match "^[ \t]*$" (buffer-substring
  12134. (point-at-bol) (point-at-eol)))
  12135. (delete-region (point-at-bol)
  12136. (min (point-max) (1+ (point-at-eol))))))))))
  12137. (defvar org-time-was-given) ; dynamically scoped parameter
  12138. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12139. (defun org-at-planning-p ()
  12140. "Non-nil when point is on a planning info line."
  12141. ;; This is as accurate and faster than `org-element-at-point' since
  12142. ;; planning info location is fixed in the section.
  12143. (org-with-wide-buffer
  12144. (beginning-of-line)
  12145. (and (looking-at-p org-planning-line-re)
  12146. (eq (point)
  12147. (ignore-errors
  12148. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12149. (org-back-to-heading t)
  12150. (org-with-limited-levels (org-back-to-heading t)))
  12151. (line-beginning-position 2))))))
  12152. (defun org-add-planning-info (what &optional time &rest remove)
  12153. "Insert new timestamp with keyword in the planning line.
  12154. WHAT indicates what kind of time stamp to add. It is a symbol
  12155. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12156. the time to use. If none is given, the user is prompted for
  12157. a date. REMOVE indicates what kind of entries to remove. An old
  12158. WHAT entry will also be removed."
  12159. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12160. (catch 'exit
  12161. (when (and (memq what '(scheduled deadline))
  12162. (or (not time)
  12163. (and (stringp time)
  12164. (string-match "^[-+]+[0-9]" time))))
  12165. ;; Try to get a default date/time from existing timestamp
  12166. (save-excursion
  12167. (org-back-to-heading t)
  12168. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12169. (when (re-search-forward (if (eq what 'scheduled)
  12170. org-scheduled-time-regexp
  12171. org-deadline-time-regexp)
  12172. end t)
  12173. (setq ts (match-string 1)
  12174. default-time (apply 'encode-time (org-parse-time-string ts))
  12175. default-input (and ts (org-get-compact-tod ts)))))))
  12176. (when what
  12177. (setq time
  12178. (if (stringp time)
  12179. ;; This is a string (relative or absolute), set
  12180. ;; proper date.
  12181. (apply #'encode-time
  12182. (org-read-date-analyze
  12183. time default-time (decode-time default-time)))
  12184. ;; If necessary, get the time from the user
  12185. (or time (org-read-date nil 'to-time nil nil
  12186. default-time default-input)))))
  12187. (org-with-wide-buffer
  12188. (org-back-to-heading t)
  12189. (forward-line)
  12190. (unless (bolp) (insert "\n"))
  12191. (cond ((looking-at-p org-planning-line-re)
  12192. ;; Move to current indentation.
  12193. (skip-chars-forward " \t")
  12194. ;; Check if we have to remove something.
  12195. (dolist (type (if what (cons what remove) remove))
  12196. (save-excursion
  12197. (when (re-search-forward
  12198. (cl-case type
  12199. (closed org-closed-time-regexp)
  12200. (deadline org-deadline-time-regexp)
  12201. (scheduled org-scheduled-time-regexp)
  12202. (otherwise
  12203. (error "Invalid planning type: %s" type)))
  12204. (line-end-position) t)
  12205. ;; Delete until next keyword or end of line.
  12206. (delete-region
  12207. (match-beginning 0)
  12208. (if (re-search-forward org-keyword-time-not-clock-regexp
  12209. (line-end-position)
  12210. t)
  12211. (match-beginning 0)
  12212. (line-end-position))))))
  12213. ;; If there is nothing more to add and no more keyword
  12214. ;; is left, remove the line completely.
  12215. (if (and (looking-at-p "[ \t]*$") (not what))
  12216. (delete-region (line-beginning-position)
  12217. (line-beginning-position 2))
  12218. ;; If we removed last keyword, do not leave trailing
  12219. ;; white space at the end of line.
  12220. (let ((p (point)))
  12221. (save-excursion
  12222. (end-of-line)
  12223. (unless (= (skip-chars-backward " \t" p) 0)
  12224. (delete-region (point) (line-end-position)))))))
  12225. ((not what) (throw 'exit nil)) ; Nothing to do.
  12226. (t (insert-before-markers "\n")
  12227. (backward-char 1)
  12228. (when org-adapt-indentation
  12229. (indent-to-column (1+ (org-outline-level))))))
  12230. (when what
  12231. ;; Insert planning keyword.
  12232. (insert (cl-case what
  12233. (closed org-closed-string)
  12234. (deadline org-deadline-string)
  12235. (scheduled org-scheduled-string)
  12236. (otherwise (error "Invalid planning type: %s" what)))
  12237. " ")
  12238. ;; Insert associated timestamp.
  12239. (let ((ts (org-insert-time-stamp
  12240. time
  12241. (or org-time-was-given
  12242. (and (eq what 'closed) org-log-done-with-time))
  12243. (eq what 'closed)
  12244. nil nil (list org-end-time-was-given))))
  12245. (unless (eolp) (insert " "))
  12246. ts))))))
  12247. (defvar org-log-note-marker (make-marker)
  12248. "Marker pointing at the entry where the note is to be inserted.")
  12249. (defvar org-log-note-purpose nil)
  12250. (defvar org-log-note-state nil)
  12251. (defvar org-log-note-previous-state nil)
  12252. (defvar org-log-note-extra nil)
  12253. (defvar org-log-note-window-configuration nil)
  12254. (defvar org-log-note-return-to (make-marker))
  12255. (defvar org-log-note-effective-time nil
  12256. "Remembered current time so that dynamically scoped
  12257. `org-extend-today-until' affects timestamps in state change log")
  12258. (defvar org-log-post-message nil
  12259. "Message to be displayed after a log note has been stored.
  12260. The auto-repeater uses this.")
  12261. (defun org-add-note ()
  12262. "Add a note to the current entry.
  12263. This is done in the same way as adding a state change note."
  12264. (interactive)
  12265. (org-add-log-setup 'note))
  12266. (defun org-log-beginning (&optional create)
  12267. "Return expected start of log notes in current entry.
  12268. When optional argument CREATE is non-nil, the function creates
  12269. a drawer to store notes, if necessary. Returned position ignores
  12270. narrowing."
  12271. (org-with-wide-buffer
  12272. (let ((drawer (org-log-into-drawer)))
  12273. (cond
  12274. (drawer
  12275. (org-end-of-meta-data)
  12276. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12277. (end (if (org-at-heading-p) (point)
  12278. (save-excursion (outline-next-heading) (point))))
  12279. (case-fold-search t))
  12280. (catch 'exit
  12281. ;; Try to find existing drawer.
  12282. (while (re-search-forward regexp end t)
  12283. (let ((element (org-element-at-point)))
  12284. (when (eq (org-element-type element) 'drawer)
  12285. (let ((cend (org-element-property :contents-end element)))
  12286. (when (and (not org-log-states-order-reversed) cend)
  12287. (goto-char cend)))
  12288. (throw 'exit nil))))
  12289. ;; No drawer found. Create one, if permitted.
  12290. (when create
  12291. (unless (bolp) (insert "\n"))
  12292. (let ((beg (point)))
  12293. (insert ":" drawer ":\n:END:\n")
  12294. (org-indent-region beg (point)))
  12295. (end-of-line -1)))))
  12296. (t
  12297. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12298. (skip-chars-forward " \t\n")
  12299. (beginning-of-line)
  12300. (unless org-log-states-order-reversed
  12301. (org-skip-over-state-notes)
  12302. (skip-chars-backward " \t\n")
  12303. (forward-line)))))
  12304. (if (bolp) (point) (line-beginning-position 2))))
  12305. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12306. "Set up the post command hook to take a note.
  12307. If this is about to TODO state change, the new state is expected in STATE.
  12308. HOW is an indicator what kind of note should be created.
  12309. EXTRA is additional text that will be inserted into the notes buffer."
  12310. (move-marker org-log-note-marker (point))
  12311. (setq org-log-note-purpose purpose
  12312. org-log-note-state state
  12313. org-log-note-previous-state prev-state
  12314. org-log-note-how how
  12315. org-log-note-extra extra
  12316. org-log-note-effective-time (org-current-effective-time))
  12317. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12318. (defun org-skip-over-state-notes ()
  12319. "Skip past the list of State notes in an entry."
  12320. (when (ignore-errors (goto-char (org-in-item-p)))
  12321. (let* ((struct (org-list-struct))
  12322. (prevs (org-list-prevs-alist struct))
  12323. (regexp
  12324. (concat "[ \t]*- +"
  12325. (replace-regexp-in-string
  12326. " +" " +"
  12327. (org-replace-escapes
  12328. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12329. `(("%d" . ,org-ts-regexp-inactive)
  12330. ("%D" . ,org-ts-regexp)
  12331. ("%s" . "\"\\S-+\"")
  12332. ("%S" . "\"\\S-+\"")
  12333. ("%t" . ,org-ts-regexp-inactive)
  12334. ("%T" . ,org-ts-regexp)
  12335. ("%u" . ".*?")
  12336. ("%U" . ".*?")))))))
  12337. (while (looking-at-p regexp)
  12338. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12339. (org-list-get-item-end (point) struct)))))))
  12340. (defun org-add-log-note (&optional _purpose)
  12341. "Pop up a window for taking a note, and add this note later."
  12342. (remove-hook 'post-command-hook 'org-add-log-note)
  12343. (setq org-log-note-window-configuration (current-window-configuration))
  12344. (delete-other-windows)
  12345. (move-marker org-log-note-return-to (point))
  12346. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12347. (goto-char org-log-note-marker)
  12348. (org-switch-to-buffer-other-window "*Org Note*")
  12349. (erase-buffer)
  12350. (if (memq org-log-note-how '(time state))
  12351. (let (current-prefix-arg) (org-store-log-note))
  12352. (let ((org-inhibit-startup t)) (org-mode))
  12353. (insert (format "# Insert note for %s.
  12354. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12355. (cond
  12356. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12357. ((eq org-log-note-purpose 'done) "closed todo item")
  12358. ((eq org-log-note-purpose 'state)
  12359. (format "state change from \"%s\" to \"%s\""
  12360. (or org-log-note-previous-state "")
  12361. (or org-log-note-state "")))
  12362. ((eq org-log-note-purpose 'reschedule)
  12363. "rescheduling")
  12364. ((eq org-log-note-purpose 'delschedule)
  12365. "no longer scheduled")
  12366. ((eq org-log-note-purpose 'redeadline)
  12367. "changing deadline")
  12368. ((eq org-log-note-purpose 'deldeadline)
  12369. "removing deadline")
  12370. ((eq org-log-note-purpose 'refile)
  12371. "refiling")
  12372. ((eq org-log-note-purpose 'note)
  12373. "this entry")
  12374. (t (error "This should not happen")))))
  12375. (when org-log-note-extra (insert org-log-note-extra))
  12376. (setq-local org-finish-function 'org-store-log-note)
  12377. (run-hooks 'org-log-buffer-setup-hook)))
  12378. (defvar org-note-abort nil) ; dynamically scoped
  12379. (defun org-store-log-note ()
  12380. "Finish taking a log note, and insert it to where it belongs."
  12381. (let ((txt (prog1 (buffer-string)
  12382. (kill-buffer)))
  12383. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12384. lines)
  12385. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12386. (setq txt (replace-match "" t t txt)))
  12387. (when (string-match "\\s-+\\'" txt)
  12388. (setq txt (replace-match "" t t txt)))
  12389. (setq lines (org-split-string txt "\n"))
  12390. (when (org-string-nw-p note)
  12391. (setq note
  12392. (org-replace-escapes
  12393. note
  12394. (list (cons "%u" (user-login-name))
  12395. (cons "%U" user-full-name)
  12396. (cons "%t" (format-time-string
  12397. (org-time-stamp-format 'long 'inactive)
  12398. org-log-note-effective-time))
  12399. (cons "%T" (format-time-string
  12400. (org-time-stamp-format 'long nil)
  12401. org-log-note-effective-time))
  12402. (cons "%d" (format-time-string
  12403. (org-time-stamp-format nil 'inactive)
  12404. org-log-note-effective-time))
  12405. (cons "%D" (format-time-string
  12406. (org-time-stamp-format nil nil)
  12407. org-log-note-effective-time))
  12408. (cons "%s" (cond
  12409. ((not org-log-note-state) "")
  12410. ((string-match-p org-ts-regexp
  12411. org-log-note-state)
  12412. (format "\"[%s]\""
  12413. (substring org-log-note-state 1 -1)))
  12414. (t (format "\"%s\"" org-log-note-state))))
  12415. (cons "%S"
  12416. (cond
  12417. ((not org-log-note-previous-state) "")
  12418. ((string-match-p org-ts-regexp
  12419. org-log-note-previous-state)
  12420. (format "\"[%s]\""
  12421. (substring
  12422. org-log-note-previous-state 1 -1)))
  12423. (t (format "\"%s\""
  12424. org-log-note-previous-state)))))))
  12425. (when lines (setq note (concat note " \\\\")))
  12426. (push note lines))
  12427. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12428. (with-current-buffer (marker-buffer org-log-note-marker)
  12429. (org-with-wide-buffer
  12430. ;; Find location for the new note.
  12431. (goto-char org-log-note-marker)
  12432. (set-marker org-log-note-marker nil)
  12433. ;; Note associated to a clock is to be located right after
  12434. ;; the clock. Do not move point.
  12435. (unless (eq org-log-note-purpose 'clock-out)
  12436. (goto-char (org-log-beginning t)))
  12437. ;; Make sure point is at the beginning of an empty line.
  12438. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12439. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12440. ;; In an existing list, add a new item at the top level.
  12441. ;; Otherwise, indent line like a regular one.
  12442. (let ((itemp (org-in-item-p)))
  12443. (if itemp
  12444. (indent-line-to
  12445. (let ((struct (save-excursion
  12446. (goto-char itemp) (org-list-struct))))
  12447. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12448. (org-indent-line)))
  12449. (insert (org-list-bullet-string "-") (pop lines))
  12450. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12451. (dolist (line lines)
  12452. (insert "\n")
  12453. (indent-line-to ind)
  12454. (insert line)))
  12455. (message "Note stored")
  12456. (org-back-to-heading t)
  12457. (org-cycle-hide-drawers 'children))
  12458. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12459. ;; from within `org-add-log-note' because `buffer-undo-list'
  12460. ;; is then modified outside of `org-with-remote-undo'.
  12461. (when (eq this-command 'org-agenda-todo)
  12462. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12463. ;; Don't add undo information when called from `org-agenda-todo'.
  12464. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12465. (set-window-configuration org-log-note-window-configuration)
  12466. (with-current-buffer (marker-buffer org-log-note-return-to)
  12467. (goto-char org-log-note-return-to))
  12468. (move-marker org-log-note-return-to nil)
  12469. (when org-log-post-message (message "%s" org-log-post-message))))
  12470. (defun org-remove-empty-drawer-at (pos)
  12471. "Remove an empty drawer at position POS.
  12472. POS may also be a marker."
  12473. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12474. (org-with-wide-buffer
  12475. (goto-char pos)
  12476. (let ((drawer (org-element-at-point)))
  12477. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12478. (not (org-element-property :contents-begin drawer)))
  12479. (delete-region (org-element-property :begin drawer)
  12480. (progn (goto-char (org-element-property :end drawer))
  12481. (skip-chars-backward " \r\t\n")
  12482. (forward-line)
  12483. (point))))))))
  12484. (defvar org-ts-type nil)
  12485. (defun org-sparse-tree (&optional arg type)
  12486. "Create a sparse tree, prompt for the details.
  12487. This command can create sparse trees. You first need to select the type
  12488. of match used to create the tree:
  12489. t Show all TODO entries.
  12490. T Show entries with a specific TODO keyword.
  12491. m Show entries selected by a tags/property match.
  12492. p Enter a property name and its value (both with completion on existing
  12493. names/values) and show entries with that property.
  12494. r Show entries matching a regular expression (`/' can be used as well).
  12495. b Show deadlines and scheduled items before a date.
  12496. a Show deadlines and scheduled items after a date.
  12497. d Show deadlines due within `org-deadline-warning-days'.
  12498. D Show deadlines and scheduled items between a date range."
  12499. (interactive "P")
  12500. (setq type (or type org-sparse-tree-default-date-type))
  12501. (setq org-ts-type type)
  12502. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12503. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12504. \[c]ycle through date types: %s"
  12505. (cl-case type
  12506. (all "all timestamps")
  12507. (scheduled "only scheduled")
  12508. (deadline "only deadline")
  12509. (active "only active timestamps")
  12510. (inactive "only inactive timestamps")
  12511. (closed "with a closed time-stamp")
  12512. (otherwise "scheduled/deadline")))
  12513. (let ((answer (read-char-exclusive)))
  12514. (cl-case answer
  12515. (?c
  12516. (org-sparse-tree
  12517. arg
  12518. (cadr
  12519. (memq type '(nil all scheduled deadline active inactive closed)))))
  12520. (?d (call-interactively 'org-check-deadlines))
  12521. (?b (call-interactively 'org-check-before-date))
  12522. (?a (call-interactively 'org-check-after-date))
  12523. (?D (call-interactively 'org-check-dates-range))
  12524. (?t (call-interactively 'org-show-todo-tree))
  12525. (?T (org-show-todo-tree '(4)))
  12526. (?m (call-interactively 'org-match-sparse-tree))
  12527. ((?p ?P)
  12528. (let* ((kwd (completing-read
  12529. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12530. (value (completing-read
  12531. "Value: " (mapcar #'list (org-property-values kwd)))))
  12532. (unless (string-match "\\`{.*}\\'" value)
  12533. (setq value (concat "\"" value "\"")))
  12534. (org-match-sparse-tree arg (concat kwd "=" value))))
  12535. ((?r ?R ?/) (call-interactively 'org-occur))
  12536. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12537. (defvar-local org-occur-highlights nil
  12538. "List of overlays used for occur matches.")
  12539. (defvar-local org-occur-parameters nil
  12540. "Parameters of the active org-occur calls.
  12541. This is a list, each call to org-occur pushes as cons cell,
  12542. containing the regular expression and the callback, onto the list.
  12543. The list can contain several entries if `org-occur' has been called
  12544. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12545. will only contain one set of parameters. When the highlights are
  12546. removed (for example with `C-c C-c', or with the next edit (depending
  12547. on `org-remove-highlights-with-change'), this variable is emptied
  12548. as well.")
  12549. (defun org-occur (regexp &optional keep-previous callback)
  12550. "Make a compact tree which shows all matches of REGEXP.
  12551. The tree will show the lines where the regexp matches, and any other context
  12552. defined in `org-show-context-detail', which see.
  12553. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12554. done by a previous call to `org-occur' will be kept, to allow stacking of
  12555. calls to this command.
  12556. Optional argument CALLBACK can be a function of no argument. In this case,
  12557. it is called with point at the end of the match, match data being set
  12558. accordingly. Current match is shown only if the return value is non-nil.
  12559. The function must neither move point nor alter narrowing."
  12560. (interactive "sRegexp: \nP")
  12561. (when (equal regexp "")
  12562. (user-error "Regexp cannot be empty"))
  12563. (unless keep-previous
  12564. (org-remove-occur-highlights nil nil t))
  12565. (push (cons regexp callback) org-occur-parameters)
  12566. (let ((cnt 0))
  12567. (save-excursion
  12568. (goto-char (point-min))
  12569. (when (or (not keep-previous) ; do not want to keep
  12570. (not org-occur-highlights)) ; no previous matches
  12571. ;; hide everything
  12572. (org-overview))
  12573. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12574. (isearch-no-upper-case-p regexp t)
  12575. org-occur-case-fold-search)))
  12576. (while (re-search-forward regexp nil t)
  12577. (when (or (not callback)
  12578. (save-match-data (funcall callback)))
  12579. (setq cnt (1+ cnt))
  12580. (when org-highlight-sparse-tree-matches
  12581. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12582. (org-show-context 'occur-tree)))))
  12583. (when org-remove-highlights-with-change
  12584. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12585. nil 'local))
  12586. (unless org-sparse-tree-open-archived-trees
  12587. (org-hide-archived-subtrees (point-min) (point-max)))
  12588. (run-hooks 'org-occur-hook)
  12589. (when (called-interactively-p 'interactive)
  12590. (message "%d match(es) for regexp %s" cnt regexp))
  12591. cnt))
  12592. (defun org-occur-next-match (&optional n _reset)
  12593. "Function for `next-error-function' to find sparse tree matches.
  12594. N is the number of matches to move, when negative move backwards.
  12595. This function always goes back to the starting point when no
  12596. match is found."
  12597. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12598. (search-func (if (< n 0)
  12599. 'previous-single-char-property-change
  12600. 'next-single-char-property-change))
  12601. (n (abs n))
  12602. (pos (point))
  12603. p1)
  12604. (catch 'exit
  12605. (while (setq p1 (funcall search-func (point) 'org-type))
  12606. (when (equal p1 limit)
  12607. (goto-char pos)
  12608. (user-error "No more matches"))
  12609. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12610. (setq n (1- n))
  12611. (when (= n 0)
  12612. (goto-char p1)
  12613. (throw 'exit (point))))
  12614. (goto-char p1))
  12615. (goto-char p1)
  12616. (user-error "No more matches"))))
  12617. (defun org-show-context (&optional key)
  12618. "Make sure point and context are visible.
  12619. Optional argument KEY, when non-nil, is a symbol. See
  12620. `org-show-context-detail' for allowed values and how much is to
  12621. be shown."
  12622. (org-show-set-visibility
  12623. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12624. ((cdr (assq key org-show-context-detail)))
  12625. (t (cdr (assq 'default org-show-context-detail))))))
  12626. (defun org-show-set-visibility (detail)
  12627. "Set visibility around point according to DETAIL.
  12628. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12629. `tree', `canonical' or t. See `org-show-context-detail' for more
  12630. information."
  12631. ;; Show current heading and possibly its entry, following headline
  12632. ;; or all children.
  12633. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12634. (org-flag-heading nil)
  12635. (org-show-entry)
  12636. ;; If point is hidden within a drawer or a block, make sure to
  12637. ;; expose it.
  12638. (dolist (o (overlays-at (point)))
  12639. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12640. (delete-overlay o)))
  12641. (unless (org-before-first-heading-p)
  12642. (org-with-limited-levels
  12643. (cl-case detail
  12644. ((tree canonical t) (org-show-children))
  12645. ((nil minimal ancestors))
  12646. (t (save-excursion
  12647. (outline-next-heading)
  12648. (org-flag-heading nil)))))))
  12649. ;; Show all siblings.
  12650. (when (eq detail 'lineage) (org-show-siblings))
  12651. ;; Show ancestors, possibly with their children.
  12652. (when (memq detail '(ancestors lineage tree canonical t))
  12653. (save-excursion
  12654. (while (org-up-heading-safe)
  12655. (org-flag-heading nil)
  12656. (when (memq detail '(canonical t)) (org-show-entry))
  12657. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12658. (defvar org-reveal-start-hook nil
  12659. "Hook run before revealing a location.")
  12660. (defun org-reveal (&optional siblings)
  12661. "Show current entry, hierarchy above it, and the following headline.
  12662. This can be used to show a consistent set of context around
  12663. locations exposed with `org-show-context'.
  12664. With optional argument SIBLINGS, on each level of the hierarchy all
  12665. siblings are shown. This repairs the tree structure to what it would
  12666. look like when opened with hierarchical calls to `org-cycle'.
  12667. With a \\[universal-argument] \\[universal-argument] prefix, \
  12668. go to the parent and show the entire tree."
  12669. (interactive "P")
  12670. (run-hooks 'org-reveal-start-hook)
  12671. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12672. ((equal siblings '(16))
  12673. (save-excursion
  12674. (when (org-up-heading-safe)
  12675. (org-show-subtree)
  12676. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12677. (t (org-show-set-visibility 'lineage))))
  12678. (defun org-highlight-new-match (beg end)
  12679. "Highlight from BEG to END and mark the highlight is an occur headline."
  12680. (let ((ov (make-overlay beg end)))
  12681. (overlay-put ov 'face 'secondary-selection)
  12682. (overlay-put ov 'org-type 'org-occur)
  12683. (push ov org-occur-highlights)))
  12684. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12685. "Remove the occur highlights from the buffer.
  12686. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12687. from the `before-change-functions' in the current buffer."
  12688. (interactive)
  12689. (unless org-inhibit-highlight-removal
  12690. (mapc #'delete-overlay org-occur-highlights)
  12691. (setq org-occur-highlights nil)
  12692. (setq org-occur-parameters nil)
  12693. (unless noremove
  12694. (remove-hook 'before-change-functions
  12695. 'org-remove-occur-highlights 'local))))
  12696. ;;;; Priorities
  12697. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12698. "Regular expression matching the priority indicator.")
  12699. (defvar org-remove-priority-next-time nil)
  12700. (defun org-priority-up ()
  12701. "Increase the priority of the current item."
  12702. (interactive)
  12703. (org-priority 'up))
  12704. (defun org-priority-down ()
  12705. "Decrease the priority of the current item."
  12706. (interactive)
  12707. (org-priority 'down))
  12708. (defun org-priority (&optional action _show)
  12709. "Change the priority of an item.
  12710. ACTION can be `set', `up', `down', or a character."
  12711. (interactive "P")
  12712. (if (equal action '(4))
  12713. (org-show-priority)
  12714. (unless org-enable-priority-commands
  12715. (user-error "Priority commands are disabled"))
  12716. (setq action (or action 'set))
  12717. (let (current new news have remove)
  12718. (save-excursion
  12719. (org-back-to-heading t)
  12720. (when (looking-at org-priority-regexp)
  12721. (setq current (string-to-char (match-string 2))
  12722. have t))
  12723. (cond
  12724. ((eq action 'remove)
  12725. (setq remove t new ?\ ))
  12726. ((or (eq action 'set)
  12727. (integerp action))
  12728. (if (not (eq action 'set))
  12729. (setq new action)
  12730. (message "Priority %c-%c, SPC to remove: "
  12731. org-highest-priority org-lowest-priority)
  12732. (save-match-data
  12733. (setq new (read-char-exclusive))))
  12734. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12735. (= (upcase org-lowest-priority) org-lowest-priority))
  12736. (setq new (upcase new)))
  12737. (cond ((equal new ?\ ) (setq remove t))
  12738. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12739. (user-error "Priority must be between `%c' and `%c'"
  12740. org-highest-priority org-lowest-priority))))
  12741. ((eq action 'up)
  12742. (setq new (if have
  12743. (1- current) ; normal cycling
  12744. ;; last priority was empty
  12745. (if (eq last-command this-command)
  12746. org-lowest-priority ; wrap around empty to lowest
  12747. ;; default
  12748. (if org-priority-start-cycle-with-default
  12749. org-default-priority
  12750. (1- org-default-priority))))))
  12751. ((eq action 'down)
  12752. (setq new (if have
  12753. (1+ current) ; normal cycling
  12754. ;; last priority was empty
  12755. (if (eq last-command this-command)
  12756. org-highest-priority ; wrap around empty to highest
  12757. ;; default
  12758. (if org-priority-start-cycle-with-default
  12759. org-default-priority
  12760. (1+ org-default-priority))))))
  12761. (t (user-error "Invalid action")))
  12762. (when (or (< (upcase new) org-highest-priority)
  12763. (> (upcase new) org-lowest-priority))
  12764. (if (and (memq action '(up down))
  12765. (not have) (not (eq last-command this-command)))
  12766. ;; `new' is from default priority
  12767. (error
  12768. "The default can not be set, see `org-default-priority' why")
  12769. ;; normal cycling: `new' is beyond highest/lowest priority
  12770. ;; and is wrapped around to the empty priority
  12771. (setq remove t)))
  12772. (setq news (format "%c" new))
  12773. (if have
  12774. (if remove
  12775. (replace-match "" t t nil 1)
  12776. (replace-match news t t nil 2))
  12777. (if remove
  12778. (user-error "No priority cookie found in line")
  12779. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12780. (if (match-end 2)
  12781. (progn
  12782. (goto-char (match-end 2))
  12783. (insert " [#" news "]"))
  12784. (goto-char (match-beginning 3))
  12785. (insert "[#" news "] "))))
  12786. (org-set-tags nil 'align))
  12787. (if remove
  12788. (message "Priority removed")
  12789. (message "Priority of current item set to %s" news)))))
  12790. (defun org-show-priority ()
  12791. "Show the priority of the current item.
  12792. This priority is composed of the main priority given with the [#A] cookies,
  12793. and by additional input from the age of a schedules or deadline entry."
  12794. (interactive)
  12795. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12796. (org-get-at-bol 'priority)
  12797. (save-excursion
  12798. (save-match-data
  12799. (beginning-of-line)
  12800. (and (looking-at org-heading-regexp)
  12801. (org-get-priority (match-string 0))))))))
  12802. (message "Priority is %d" (if pri pri -1000))))
  12803. (defun org-get-priority (s)
  12804. "Find priority cookie and return priority."
  12805. (save-match-data
  12806. (if (functionp org-get-priority-function)
  12807. (funcall org-get-priority-function)
  12808. (if (not (string-match org-priority-regexp s))
  12809. (* 1000 (- org-lowest-priority org-default-priority))
  12810. (* 1000 (- org-lowest-priority
  12811. (string-to-char (match-string 2 s))))))))
  12812. ;;;; Tags
  12813. (defvar org-agenda-archives-mode)
  12814. (defvar org-map-continue-from nil
  12815. "Position from where mapping should continue.
  12816. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12817. (defvar org-scanner-tags nil
  12818. "The current tag list while the tags scanner is running.")
  12819. (defvar org-trust-scanner-tags nil
  12820. "Should `org-get-tags-at' use the tags for the scanner.
  12821. This is for internal dynamical scoping only.
  12822. When this is non-nil, the function `org-get-tags-at' will return the value
  12823. of `org-scanner-tags' instead of building the list by itself. This
  12824. can lead to large speed-ups when the tags scanner is used in a file with
  12825. many entries, and when the list of tags is retrieved, for example to
  12826. obtain a list of properties. Building the tags list for each entry in such
  12827. a file becomes an N^2 operation - but with this variable set, it scales
  12828. as N.")
  12829. (defvar org--matcher-tags-todo-only nil)
  12830. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12831. "Scan headline tags with inheritance and produce output ACTION.
  12832. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12833. or `agenda' to produce an entry list for an agenda view. It can also be
  12834. a Lisp form or a function that should be called at each matched headline, in
  12835. this case the return value is a list of all return values from these calls.
  12836. MATCHER is a function accepting three arguments, returning
  12837. a non-nil value whenever a given set of tags qualifies a headline
  12838. for inclusion. See `org-make-tags-matcher' for more information.
  12839. As a special case, it can also be set to t (respectively nil) in
  12840. order to match all (respectively none) headline.
  12841. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12842. keyword are included in the output.
  12843. START-LEVEL can be a string with asterisks, reducing the scope to
  12844. headlines matching this string."
  12845. (require 'org-agenda)
  12846. (let* ((re (concat "^"
  12847. (if start-level
  12848. ;; Get the correct level to match
  12849. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12850. org-outline-regexp)
  12851. " *\\(\\<\\("
  12852. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12853. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12854. (props (list 'face 'default
  12855. 'done-face 'org-agenda-done
  12856. 'undone-face 'default
  12857. 'mouse-face 'highlight
  12858. 'org-not-done-regexp org-not-done-regexp
  12859. 'org-todo-regexp org-todo-regexp
  12860. 'org-complex-heading-regexp org-complex-heading-regexp
  12861. 'help-echo
  12862. (format "mouse-2 or RET jump to org file %s"
  12863. (abbreviate-file-name
  12864. (or (buffer-file-name (buffer-base-buffer))
  12865. (buffer-name (buffer-base-buffer)))))))
  12866. (org-map-continue-from nil)
  12867. lspos tags tags-list
  12868. (tags-alist (list (cons 0 org-file-tags)))
  12869. (llast 0) rtn rtn1 level category i txt
  12870. todo marker entry priority
  12871. ts-date ts-date-type ts-date-pair)
  12872. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12873. (setq action (list 'lambda nil action)))
  12874. (save-excursion
  12875. (goto-char (point-min))
  12876. (when (eq action 'sparse-tree)
  12877. (org-overview)
  12878. (org-remove-occur-highlights))
  12879. (while (let (case-fold-search)
  12880. (re-search-forward re nil t))
  12881. (setq org-map-continue-from nil)
  12882. (catch :skip
  12883. (setq todo
  12884. ;; TODO: is the 1-2 difference a bug?
  12885. (when (match-end 1) (match-string-no-properties 2))
  12886. tags (when (match-end 4) (match-string-no-properties 4)))
  12887. (goto-char (setq lspos (match-beginning 0)))
  12888. (setq level (org-reduced-level (org-outline-level))
  12889. category (org-get-category))
  12890. (when (eq action 'agenda)
  12891. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12892. ts-date (car ts-date-pair)
  12893. ts-date-type (cdr ts-date-pair)))
  12894. (setq i llast llast level)
  12895. ;; remove tag lists from same and sublevels
  12896. (while (>= i level)
  12897. (when (setq entry (assoc i tags-alist))
  12898. (setq tags-alist (delete entry tags-alist)))
  12899. (setq i (1- i)))
  12900. ;; add the next tags
  12901. (when tags
  12902. (setq tags (org-split-string tags ":")
  12903. tags-alist
  12904. (cons (cons level tags) tags-alist)))
  12905. ;; compile tags for current headline
  12906. (setq tags-list
  12907. (if org-use-tag-inheritance
  12908. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12909. tags)
  12910. org-scanner-tags tags-list)
  12911. (when org-use-tag-inheritance
  12912. (setcdr (car tags-alist)
  12913. (mapcar (lambda (x)
  12914. (setq x (copy-sequence x))
  12915. (org-add-prop-inherited x))
  12916. (cdar tags-alist))))
  12917. (when (and tags org-use-tag-inheritance
  12918. (or (not (eq t org-use-tag-inheritance))
  12919. org-tags-exclude-from-inheritance))
  12920. ;; Selective inheritance, remove uninherited ones.
  12921. (setcdr (car tags-alist)
  12922. (org-remove-uninherited-tags (cdar tags-alist))))
  12923. (when (and
  12924. ;; eval matcher only when the todo condition is OK
  12925. (and (or (not todo-only) (member todo org-not-done-keywords))
  12926. (if (functionp matcher)
  12927. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12928. (funcall matcher todo tags-list level))
  12929. matcher))
  12930. ;; Call the skipper, but return t if it does not
  12931. ;; skip, so that the `and' form continues evaluating.
  12932. (progn
  12933. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12934. t)
  12935. ;; Check if timestamps are deselecting this entry
  12936. (or (not todo-only)
  12937. (and (member todo org-not-done-keywords)
  12938. (or (not org-agenda-tags-todo-honor-ignore-options)
  12939. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12940. ;; select this headline
  12941. (cond
  12942. ((eq action 'sparse-tree)
  12943. (and org-highlight-sparse-tree-matches
  12944. (org-get-heading) (match-end 0)
  12945. (org-highlight-new-match
  12946. (match-beginning 1) (match-end 1)))
  12947. (org-show-context 'tags-tree))
  12948. ((eq action 'agenda)
  12949. (setq txt (org-agenda-format-item
  12950. ""
  12951. (concat
  12952. (if (eq org-tags-match-list-sublevels 'indented)
  12953. (make-string (1- level) ?.) "")
  12954. (org-get-heading))
  12955. (make-string level ?\s)
  12956. category
  12957. tags-list)
  12958. priority (org-get-priority txt))
  12959. (goto-char lspos)
  12960. (setq marker (org-agenda-new-marker))
  12961. (org-add-props txt props
  12962. 'org-marker marker 'org-hd-marker marker 'org-category category
  12963. 'todo-state todo
  12964. 'ts-date ts-date
  12965. 'priority priority
  12966. 'type (concat "tagsmatch" ts-date-type))
  12967. (push txt rtn))
  12968. ((functionp action)
  12969. (setq org-map-continue-from nil)
  12970. (save-excursion
  12971. (setq rtn1 (funcall action))
  12972. (push rtn1 rtn)))
  12973. (t (user-error "Invalid action")))
  12974. ;; if we are to skip sublevels, jump to end of subtree
  12975. (unless org-tags-match-list-sublevels
  12976. (org-end-of-subtree t)
  12977. (backward-char 1))))
  12978. ;; Get the correct position from where to continue
  12979. (if org-map-continue-from
  12980. (goto-char org-map-continue-from)
  12981. (and (= (point) lspos) (end-of-line 1)))))
  12982. (when (and (eq action 'sparse-tree)
  12983. (not org-sparse-tree-open-archived-trees))
  12984. (org-hide-archived-subtrees (point-min) (point-max)))
  12985. (nreverse rtn)))
  12986. (defun org-remove-uninherited-tags (tags)
  12987. "Remove all tags that are not inherited from the list TAGS."
  12988. (cond
  12989. ((eq org-use-tag-inheritance t)
  12990. (if org-tags-exclude-from-inheritance
  12991. (org-delete-all org-tags-exclude-from-inheritance tags)
  12992. tags))
  12993. ((not org-use-tag-inheritance) nil)
  12994. ((stringp org-use-tag-inheritance)
  12995. (delq nil (mapcar
  12996. (lambda (x)
  12997. (if (and (string-match org-use-tag-inheritance x)
  12998. (not (member x org-tags-exclude-from-inheritance)))
  12999. x nil))
  13000. tags)))
  13001. ((listp org-use-tag-inheritance)
  13002. (delq nil (mapcar
  13003. (lambda (x)
  13004. (if (member x org-use-tag-inheritance) x nil))
  13005. tags)))))
  13006. (defun org-match-sparse-tree (&optional todo-only match)
  13007. "Create a sparse tree according to tags string MATCH.
  13008. MATCH is a string with match syntax. It can contain a selection
  13009. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  13010. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  13011. those. See the manual for details.
  13012. If optional argument TODO-ONLY is non-nil, only select lines that
  13013. are also TODO tasks."
  13014. (interactive "P")
  13015. (org-agenda-prepare-buffers (list (current-buffer)))
  13016. (let ((org--matcher-tags-todo-only todo-only))
  13017. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13018. org--matcher-tags-todo-only)))
  13019. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13020. (defvar org-cached-props nil)
  13021. (defun org-cached-entry-get (pom property)
  13022. (if (or (eq t org-use-property-inheritance)
  13023. (and (stringp org-use-property-inheritance)
  13024. (let ((case-fold-search t))
  13025. (string-match-p org-use-property-inheritance property)))
  13026. (and (listp org-use-property-inheritance)
  13027. (member-ignore-case property org-use-property-inheritance)))
  13028. ;; Caching is not possible, check it directly.
  13029. (org-entry-get pom property 'inherit)
  13030. ;; Get all properties, so we can do complicated checks easily.
  13031. (cdr (assoc-string property
  13032. (or org-cached-props
  13033. (setq org-cached-props (org-entry-properties pom)))
  13034. t))))
  13035. (defun org-global-tags-completion-table (&optional files)
  13036. "Return the list of all tags in all agenda buffer/files.
  13037. Optional FILES argument is a list of files which can be used
  13038. instead of the agenda files."
  13039. (save-excursion
  13040. (org-uniquify
  13041. (delq nil
  13042. (apply #'append
  13043. (mapcar
  13044. (lambda (file)
  13045. (set-buffer (find-file-noselect file))
  13046. (mapcar (lambda (x)
  13047. (and (stringp (car-safe x))
  13048. (list (car-safe x))))
  13049. (or org-current-tag-alist (org-get-buffer-tags))))
  13050. (if (car-safe files) files
  13051. (org-agenda-files))))))))
  13052. (defun org-make-tags-matcher (match)
  13053. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13054. Returns a cons of the selection string MATCH and a function
  13055. implementing the matcher.
  13056. The matcher is to be called at an Org entry, with point on the
  13057. headline, and returns non-nil if the entry matches the selection
  13058. string MATCH. It must be called with three arguments: the TODO
  13059. keyword at the entry (or nil if none), the list of all tags at
  13060. the entry including inherited ones and the reduced level of the
  13061. headline. Additionally, the category of the entry, if any, must
  13062. be specified as the text property `org-category' on the headline.
  13063. This function sets the variable `org--matcher-tags-todo-only' to
  13064. a non-nil value if the matcher restricts matching to TODO
  13065. entries, otherwise it is not touched.
  13066. See also `org-scan-tags'."
  13067. (unless match
  13068. ;; Get a new match request, with completion against the global
  13069. ;; tags table and the local tags in current buffer.
  13070. (let ((org-last-tags-completion-table
  13071. (org-uniquify
  13072. (delq nil (append (org-get-buffer-tags)
  13073. (org-global-tags-completion-table))))))
  13074. (setq match
  13075. (completing-read
  13076. "Match: "
  13077. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13078. (let ((match0 match)
  13079. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13080. (start 0)
  13081. tagsmatch todomatch tagsmatcher todomatcher)
  13082. ;; Expand group tags.
  13083. (setq match (org-tags-expand match))
  13084. ;; Check if there is a TODO part of this match, which would be the
  13085. ;; part after a "/". To make sure that this slash is not part of
  13086. ;; a property value to be matched against, we also check that
  13087. ;; there is no / after that slash. First, find the last slash.
  13088. (let ((s 0))
  13089. (while (string-match "/+" match s)
  13090. (setq start (match-beginning 0))
  13091. (setq s (match-end 0))))
  13092. (if (and (string-match "/+" match start)
  13093. (not (string-match-p "\"" match start)))
  13094. ;; Match contains also a TODO-matching request.
  13095. (progn
  13096. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13097. (setq todomatch (substring match (match-end 0)))
  13098. (when (string-prefix-p "!" todomatch)
  13099. (setq org--matcher-tags-todo-only t)
  13100. (setq todomatch (substring todomatch 1)))
  13101. (when (string-match "\\`\\s-*\\'" todomatch)
  13102. (setq todomatch nil)))
  13103. ;; Only matching tags.
  13104. (setq tagsmatch match)
  13105. (setq todomatch nil))
  13106. ;; Make the tags matcher.
  13107. (when (org-string-nw-p tagsmatch)
  13108. (let ((orlist nil)
  13109. (orterms (org-split-string tagsmatch "|"))
  13110. term)
  13111. (while (setq term (pop orterms))
  13112. (while (and (equal (substring term -1) "\\") orterms)
  13113. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13114. (while (string-match re term)
  13115. (let* ((rest (substring term (match-end 0)))
  13116. (minus (and (match-end 1)
  13117. (equal (match-string 1 term) "-")))
  13118. (tag (save-match-data
  13119. (replace-regexp-in-string
  13120. "\\\\-" "-" (match-string 2 term))))
  13121. (regexp (eq (string-to-char tag) ?{))
  13122. (levelp (match-end 4))
  13123. (propp (match-end 5))
  13124. (mm
  13125. (cond
  13126. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13127. (levelp
  13128. `(,(org-op-to-function (match-string 3 term))
  13129. level
  13130. ,(string-to-number (match-string 4 term))))
  13131. (propp
  13132. (let* ((gv (pcase (upcase (match-string 5 term))
  13133. ("CATEGORY"
  13134. '(get-text-property (point) 'org-category))
  13135. ("TODO" 'todo)
  13136. (p `(org-cached-entry-get nil ,p))))
  13137. (pv (match-string 7 term))
  13138. (regexp (eq (string-to-char pv) ?{))
  13139. (strp (eq (string-to-char pv) ?\"))
  13140. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13141. (po (org-op-to-function (match-string 6 term)
  13142. (if timep 'time strp))))
  13143. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13144. (when timep (setq pv (org-matcher-time pv)))
  13145. (cond ((and regexp (eq po 'org<>))
  13146. `(not (string-match ,pv (or ,gv ""))))
  13147. (regexp `(string-match ,pv (or ,gv "")))
  13148. (strp `(,po (or ,gv "") ,pv))
  13149. (t
  13150. `(,po
  13151. (string-to-number (or ,gv ""))
  13152. ,(string-to-number pv))))))
  13153. (t `(member ,tag tags-list)))))
  13154. (push (if minus `(not ,mm) mm) tagsmatcher)
  13155. (setq term rest)))
  13156. (push `(and ,@tagsmatcher) orlist)
  13157. (setq tagsmatcher nil))
  13158. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13159. ;; Make the TODO matcher.
  13160. (when (org-string-nw-p todomatch)
  13161. (let ((orlist nil))
  13162. (dolist (term (org-split-string todomatch "|"))
  13163. (while (string-match re term)
  13164. (let* ((minus (and (match-end 1)
  13165. (equal (match-string 1 term) "-")))
  13166. (kwd (match-string 2 term))
  13167. (regexp (eq (string-to-char kwd) ?{))
  13168. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13169. `(equal todo ,kwd))))
  13170. (push (if minus `(not ,mm) mm) todomatcher))
  13171. (setq term (substring term (match-end 0))))
  13172. (push (if (> (length todomatcher) 1)
  13173. (cons 'and todomatcher)
  13174. (car todomatcher))
  13175. orlist)
  13176. (setq todomatcher nil))
  13177. (setq todomatcher (cons 'or orlist))))
  13178. ;; Return the string and function of the matcher. If no
  13179. ;; tags-specific or todo-specific matcher exists, match
  13180. ;; everything.
  13181. (let ((matcher (if (and tagsmatcher todomatcher)
  13182. `(and ,tagsmatcher ,todomatcher)
  13183. (or tagsmatcher todomatcher t))))
  13184. (when org--matcher-tags-todo-only
  13185. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13186. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13187. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13188. "Expand group tags in MATCH.
  13189. This replaces every group tag in MATCH with a regexp tag search.
  13190. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13191. will be replaced like this:
  13192. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13193. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13194. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13195. Replacing by a regexp preserves the structure of the match.
  13196. E.g., this expansion
  13197. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13198. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13199. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13200. A group tag in MATCH can contain regular expressions of its own.
  13201. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13202. will be replaced like this:
  13203. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13204. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13205. assumed to be a single group tag, and the function will return
  13206. the list of tags in this group.
  13207. When DOWNCASE is non-nil, expand downcased TAGS."
  13208. (if org-group-tags
  13209. (let* ((case-fold-search t)
  13210. (stable org-mode-syntax-table)
  13211. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13212. (taggroups (if downcased
  13213. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13214. taggroups)
  13215. taggroups))
  13216. (taggroups-keys (mapcar #'car taggroups))
  13217. (return-match (if downcased (downcase match) match))
  13218. (count 0)
  13219. (work-already-expanded tags-already-expanded)
  13220. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13221. ;; @ and _ are allowed as word-components in tags.
  13222. (modify-syntax-entry ?@ "w" stable)
  13223. (modify-syntax-entry ?_ "w" stable)
  13224. ;; Temporarily replace regexp-expressions in the match-expression.
  13225. (while (string-match "{.+?}" return-match)
  13226. (cl-incf count)
  13227. (push (match-string 0 return-match) regexps-in-match)
  13228. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13229. (while (and taggroups-keys
  13230. (with-syntax-table stable
  13231. (string-match
  13232. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13233. (regexp-opt taggroups-keys) "\\>\\)")
  13234. return-match)))
  13235. (let* ((dir (match-string 1 return-match))
  13236. (tag (match-string 2 return-match))
  13237. (tag (if downcased (downcase tag) tag)))
  13238. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13239. (member tag work-already-expanded))
  13240. (setq tags-in-group (assoc tag taggroups))
  13241. (push tag work-already-expanded)
  13242. ;; Recursively expand each tag in the group, if the tag hasn't
  13243. ;; already been expanded. Restore the match-data after all recursive calls.
  13244. (save-match-data
  13245. (let (tags-expanded)
  13246. (dolist (x (cdr tags-in-group))
  13247. (if (and (member x taggroups-keys)
  13248. (not (member x work-already-expanded)))
  13249. (setq tags-expanded
  13250. (delete-dups
  13251. (append
  13252. (org-tags-expand x t downcased
  13253. work-already-expanded)
  13254. tags-expanded)))
  13255. (setq tags-expanded
  13256. (append (list x) tags-expanded)))
  13257. (setq work-already-expanded
  13258. (delete-dups
  13259. (append tags-expanded
  13260. work-already-expanded))))
  13261. (setq tags-in-group
  13262. (delete-dups (cons (car tags-in-group)
  13263. tags-expanded)))))
  13264. ;; Filter tag-regexps from tags.
  13265. (setq regexp-in-group-escaped
  13266. (delq nil (mapcar (lambda (x)
  13267. (if (stringp x)
  13268. (and (equal "{" (substring x 0 1))
  13269. (equal "}" (substring x -1))
  13270. x)
  13271. x))
  13272. tags-in-group))
  13273. regexp-in-group
  13274. (mapcar (lambda (x)
  13275. (substring x 1 -1))
  13276. regexp-in-group-escaped)
  13277. tags-in-group
  13278. (delq nil (mapcar (lambda (x)
  13279. (if (stringp x)
  13280. (and (not (equal "{" (substring x 0 1)))
  13281. (not (equal "}" (substring x -1)))
  13282. x)
  13283. x))
  13284. tags-in-group)))
  13285. ;; If single-as-list, do no more in the while-loop.
  13286. (if (not single-as-list)
  13287. (progn
  13288. (when regexp-in-group
  13289. (setq regexp-in-group
  13290. (concat "\\|"
  13291. (mapconcat 'identity regexp-in-group
  13292. "\\|"))))
  13293. (setq tags-in-group
  13294. (concat dir
  13295. "{\\<"
  13296. (regexp-opt tags-in-group)
  13297. "\\>"
  13298. regexp-in-group
  13299. "}"))
  13300. (when (stringp tags-in-group)
  13301. (org-add-props tags-in-group '(grouptag t)))
  13302. (setq return-match
  13303. (replace-match tags-in-group t t return-match)))
  13304. (setq tags-in-group
  13305. (append regexp-in-group-escaped tags-in-group))))
  13306. (setq taggroups-keys (delete tag taggroups-keys))))
  13307. ;; Add the regular expressions back into the match-expression again.
  13308. (while regexps-in-match
  13309. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13310. (pop regexps-in-match)
  13311. return-match t t))
  13312. (cl-decf count))
  13313. (if single-as-list
  13314. (if tags-in-group tags-in-group (list return-match))
  13315. return-match))
  13316. (if single-as-list
  13317. (list (if downcased (downcase match) match))
  13318. match)))
  13319. (defun org-op-to-function (op &optional stringp)
  13320. "Turn an operator into the appropriate function."
  13321. (setq op
  13322. (cond
  13323. ((equal op "<" ) '(< string< org-time<))
  13324. ((equal op ">" ) '(> org-string> org-time>))
  13325. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13326. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13327. ((member op '("=" "==")) '(= string= org-time=))
  13328. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13329. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13330. (defun org<> (a b) (not (= a b)))
  13331. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13332. (defun org-string>= (a b) (not (string< a b)))
  13333. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13334. (defun org-string<> (a b) (not (string= a b)))
  13335. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13336. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13337. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13338. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13339. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13340. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13341. (defun org-2ft (s)
  13342. "Convert S to a floating point time.
  13343. If S is already a number, just return it. If it is a string, parse
  13344. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13345. (cond
  13346. ((numberp s) s)
  13347. ((stringp s)
  13348. (condition-case nil
  13349. (float-time (apply 'encode-time (org-parse-time-string s)))
  13350. (error 0.)))
  13351. (t 0.)))
  13352. (defun org-time-today ()
  13353. "Time in seconds today at 0:00.
  13354. Returns the float number of seconds since the beginning of the
  13355. epoch to the beginning of today (00:00)."
  13356. (float-time (apply 'encode-time
  13357. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13358. (defun org-matcher-time (s)
  13359. "Interpret a time comparison value."
  13360. (save-match-data
  13361. (cond
  13362. ((string= s "<now>") (float-time))
  13363. ((string= s "<today>") (org-time-today))
  13364. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13365. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13366. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13367. (+ (org-time-today)
  13368. (* (string-to-number (match-string 1 s))
  13369. (cdr (assoc (match-string 2 s)
  13370. '(("d" . 86400.0) ("w" . 604800.0)
  13371. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13372. (t (org-2ft s)))))
  13373. (defun org-match-any-p (re list)
  13374. "Does re match any element of list?"
  13375. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13376. (delq nil list))
  13377. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13378. (defvar org-tags-overlay (make-overlay 1 1))
  13379. (delete-overlay org-tags-overlay)
  13380. (defun org-get-local-tags-at (&optional pos)
  13381. "Get a list of tags defined in the current headline."
  13382. (org-get-tags-at pos 'local))
  13383. (defun org-get-local-tags ()
  13384. "Get a list of tags defined in the current headline."
  13385. (org-get-tags-at nil 'local))
  13386. (defun org-get-tags-at (&optional pos local)
  13387. "Get a list of all headline tags applicable at POS.
  13388. POS defaults to point. If tags are inherited, the list contains
  13389. the targets in the same sequence as the headlines appear, i.e.
  13390. the tags of the current headline come last.
  13391. When LOCAL is non-nil, only return tags from the current headline,
  13392. ignore inherited ones."
  13393. (interactive)
  13394. (if (and org-trust-scanner-tags
  13395. (or (not pos) (equal pos (point)))
  13396. (not local))
  13397. org-scanner-tags
  13398. (let (tags ltags lastpos parent)
  13399. (save-excursion
  13400. (save-restriction
  13401. (widen)
  13402. (goto-char (or pos (point)))
  13403. (save-match-data
  13404. (catch 'done
  13405. (condition-case nil
  13406. (progn
  13407. (org-back-to-heading t)
  13408. (while (not (equal lastpos (point)))
  13409. (setq lastpos (point))
  13410. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13411. (setq ltags (org-split-string
  13412. (match-string-no-properties 1) ":"))
  13413. (when parent
  13414. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13415. (setq tags (append
  13416. (if parent
  13417. (org-remove-uninherited-tags ltags)
  13418. ltags)
  13419. tags)))
  13420. (or org-use-tag-inheritance (throw 'done t))
  13421. (when local (throw 'done t))
  13422. (or (org-up-heading-safe) (error nil))
  13423. (setq parent t)))
  13424. (error nil)))))
  13425. (if local
  13426. tags
  13427. (reverse (delete-dups
  13428. (reverse (append
  13429. (org-remove-uninherited-tags
  13430. org-file-tags)
  13431. tags)))))))))
  13432. (defun org-add-prop-inherited (s)
  13433. (add-text-properties 0 (length s) '(inherited t) s)
  13434. s)
  13435. (defun org-toggle-tag (tag &optional onoff)
  13436. "Toggle the tag TAG for the current line.
  13437. If ONOFF is `on' or `off', don't toggle but set to this state."
  13438. (let (res current)
  13439. (save-excursion
  13440. (org-back-to-heading t)
  13441. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13442. (point-at-eol) t)
  13443. (progn
  13444. (setq current (match-string 1))
  13445. (replace-match ""))
  13446. (setq current ""))
  13447. (setq current (nreverse (org-split-string current ":")))
  13448. (cond
  13449. ((eq onoff 'on)
  13450. (setq res t)
  13451. (or (member tag current) (push tag current)))
  13452. ((eq onoff 'off)
  13453. (or (not (member tag current)) (setq current (delete tag current))))
  13454. (t (if (member tag current)
  13455. (setq current (delete tag current))
  13456. (setq res t)
  13457. (push tag current))))
  13458. (end-of-line 1)
  13459. (if current
  13460. (progn
  13461. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13462. (org-set-tags nil t))
  13463. (delete-horizontal-space))
  13464. (run-hooks 'org-after-tags-change-hook))
  13465. res))
  13466. (defun org--align-tags-here (to-col)
  13467. "Align tags on the current headline to TO-COL.
  13468. Assume point is on a headline."
  13469. (let ((pos (point)))
  13470. (beginning-of-line)
  13471. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13472. (>= pos (match-beginning 2)))
  13473. ;; No tags or point within tags: do not align.
  13474. (goto-char pos)
  13475. (goto-char (match-beginning 1))
  13476. (let ((shift (max (- (if (>= to-col 0) to-col
  13477. (- (abs to-col) (string-width (match-string 2))))
  13478. (current-column))
  13479. 1)))
  13480. (replace-match (make-string shift ?\s) nil nil nil 1)
  13481. ;; Preserve initial position, if possible. In any case, stop
  13482. ;; before tags.
  13483. (when (< pos (point)) (goto-char pos))))))
  13484. (defun org-set-tags-command (&optional arg just-align)
  13485. "Call the set-tags command for the current entry."
  13486. (interactive "P")
  13487. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13488. (org-set-tags arg just-align)
  13489. (save-excursion
  13490. (unless (and (org-region-active-p)
  13491. org-loop-over-headlines-in-active-region)
  13492. (org-back-to-heading t))
  13493. (org-set-tags arg just-align))))
  13494. (defun org-set-tags-to (data)
  13495. "Set the tags of the current entry to DATA, replacing the current tags.
  13496. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13497. If DATA is nil or the empty string, any tags will be removed."
  13498. (interactive "sTags: ")
  13499. (setq data
  13500. (cond
  13501. ((eq data nil) "")
  13502. ((equal data "") "")
  13503. ((stringp data)
  13504. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13505. ":"))
  13506. ((listp data)
  13507. (concat ":" (mapconcat 'identity data ":") ":"))))
  13508. (when data
  13509. (save-excursion
  13510. (org-back-to-heading t)
  13511. (when (let ((case-fold-search nil))
  13512. (looking-at org-complex-heading-regexp))
  13513. (if (match-end 5)
  13514. (progn
  13515. (goto-char (match-beginning 5))
  13516. (insert data)
  13517. (delete-region (point) (point-at-eol))
  13518. (org-set-tags nil 'align))
  13519. (goto-char (point-at-eol))
  13520. (insert " " data)
  13521. (org-set-tags nil 'align)))
  13522. (beginning-of-line 1)
  13523. (when (looking-at ".*?\\([ \t]+\\)$")
  13524. (delete-region (match-beginning 1) (match-end 1))))))
  13525. (defun org-align-all-tags ()
  13526. "Align the tags in all headings."
  13527. (interactive)
  13528. (save-excursion
  13529. (or (ignore-errors (org-back-to-heading t))
  13530. (outline-next-heading))
  13531. (if (org-at-heading-p)
  13532. (org-set-tags t)
  13533. (message "No headings"))))
  13534. (defvar org-indent-indentation-per-level)
  13535. (defun org-set-tags (&optional arg just-align)
  13536. "Set the tags for the current headline.
  13537. With prefix ARG, realign all tags in headings in the current buffer.
  13538. When JUST-ALIGN is non-nil, only align tags."
  13539. (interactive "P")
  13540. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13541. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13542. 'region-start-level
  13543. 'region))
  13544. org-loop-over-headlines-in-active-region)
  13545. (org-map-entries
  13546. ;; We don't use ARG and JUST-ALIGN here because these args
  13547. ;; are not useful when looping over headlines.
  13548. #'org-set-tags
  13549. org-loop-over-headlines-in-active-region
  13550. cl
  13551. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13552. (let ((org-setting-tags t))
  13553. (if arg
  13554. (save-excursion
  13555. (goto-char (point-min))
  13556. (while (re-search-forward org-outline-regexp-bol nil t)
  13557. (org-set-tags nil t)
  13558. (end-of-line))
  13559. (message "All tags realigned to column %d" org-tags-column))
  13560. (let* ((current (org-get-tags-string))
  13561. (tags
  13562. (if just-align current
  13563. ;; Get a new set of tags from the user.
  13564. (save-excursion
  13565. (let* ((seen)
  13566. (table
  13567. (setq
  13568. org-last-tags-completion-table
  13569. ;; Uniquify tags in alists, yet preserve
  13570. ;; structure (i.e., keywords).
  13571. (delq nil
  13572. (mapcar
  13573. (lambda (pair)
  13574. (let ((head (car pair)))
  13575. (cond ((symbolp head) pair)
  13576. ((member head seen) nil)
  13577. (t (push head seen)
  13578. pair))))
  13579. (append
  13580. (or org-current-tag-alist
  13581. (org-get-buffer-tags))
  13582. (and
  13583. org-complete-tags-always-offer-all-agenda-tags
  13584. (org-global-tags-completion-table
  13585. (org-agenda-files))))))))
  13586. (current-tags (org-split-string current ":"))
  13587. (inherited-tags
  13588. (nreverse (nthcdr (length current-tags)
  13589. (nreverse (org-get-tags-at))))))
  13590. (replace-regexp-in-string
  13591. "\\([-+&]+\\|,\\)"
  13592. ":"
  13593. (if (or (eq t org-use-fast-tag-selection)
  13594. (and org-use-fast-tag-selection
  13595. (delq nil (mapcar #'cdr table))))
  13596. (org-fast-tag-selection
  13597. current-tags inherited-tags table
  13598. (and org-fast-tag-selection-include-todo
  13599. org-todo-key-alist))
  13600. (let ((org-add-colon-after-tag-completion
  13601. (< 1 (length table))))
  13602. (org-trim
  13603. (completing-read
  13604. "Tags: "
  13605. #'org-tags-completion-function
  13606. nil nil current 'org-tags-history))))))))))
  13607. (when org-tags-sort-function
  13608. (setq tags
  13609. (mapconcat
  13610. #'identity
  13611. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13612. org-tags-sort-function)
  13613. ":")))
  13614. (if (or (string= ":" tags)
  13615. (string= "::" tags))
  13616. (setq tags ""))
  13617. (if (not (org-string-nw-p tags)) (setq tags "")
  13618. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13619. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13620. ;; Insert new tags at the correct column.
  13621. (unless (equal current tags)
  13622. (save-excursion
  13623. (beginning-of-line)
  13624. (let ((case-fold-search nil))
  13625. (looking-at org-complex-heading-regexp))
  13626. ;; Remove current tags, if any.
  13627. (when (match-end 5) (replace-match "" nil nil nil 5))
  13628. ;; Insert new tags, if any. Otherwise, remove trailing
  13629. ;; white spaces.
  13630. (end-of-line)
  13631. (if (not (equal tags ""))
  13632. ;; When text is being inserted on an invisible
  13633. ;; region boundary, it can be inadvertently sucked
  13634. ;; into invisibility.
  13635. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13636. (skip-chars-backward " \t")
  13637. (delete-region (point) (line-end-position)))))
  13638. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13639. ;; is on.
  13640. (unless (equal tags "")
  13641. (let* ((level (save-excursion
  13642. (beginning-of-line)
  13643. (skip-chars-forward "\\*")))
  13644. (offset (if (bound-and-true-p org-indent-mode)
  13645. (* (1- org-indent-indentation-per-level)
  13646. (1- level))
  13647. 0))
  13648. (tags-column
  13649. (+ org-tags-column
  13650. (if (> org-tags-column 0) (- offset) offset))))
  13651. (org--align-tags-here tags-column))))
  13652. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13653. (defun org-change-tag-in-region (beg end tag off)
  13654. "Add or remove TAG for each entry in the region.
  13655. This works in the agenda, and also in an Org buffer."
  13656. (interactive
  13657. (list (region-beginning) (region-end)
  13658. (let ((org-last-tags-completion-table
  13659. (if (derived-mode-p 'org-mode)
  13660. (org-uniquify
  13661. (delq nil (append (org-get-buffer-tags)
  13662. (org-global-tags-completion-table))))
  13663. (org-global-tags-completion-table))))
  13664. (completing-read
  13665. "Tag: " 'org-tags-completion-function nil nil nil
  13666. 'org-tags-history))
  13667. (progn
  13668. (message "[s]et or [r]emove? ")
  13669. (equal (read-char-exclusive) ?r))))
  13670. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13671. (let ((agendap (equal major-mode 'org-agenda-mode))
  13672. l1 l2 m buf pos newhead (cnt 0))
  13673. (goto-char end)
  13674. (setq l2 (1- (org-current-line)))
  13675. (goto-char beg)
  13676. (setq l1 (org-current-line))
  13677. (cl-loop for l from l1 to l2 do
  13678. (org-goto-line l)
  13679. (setq m (get-text-property (point) 'org-hd-marker))
  13680. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13681. (and agendap m))
  13682. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13683. pos (if agendap m (point)))
  13684. (with-current-buffer buf
  13685. (save-excursion
  13686. (save-restriction
  13687. (goto-char pos)
  13688. (setq cnt (1+ cnt))
  13689. (org-toggle-tag tag (if off 'off 'on))
  13690. (setq newhead (org-get-heading)))))
  13691. (and agendap (org-agenda-change-all-lines newhead m))))
  13692. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13693. (defun org-tags-completion-function (string _predicate &optional flag)
  13694. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13695. (confirm (lambda (x) (stringp (car x)))))
  13696. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13697. (setq s1 (match-string 1 string)
  13698. s2 (match-string 2 string))
  13699. (setq s1 "" s2 string))
  13700. (cond
  13701. ((eq flag nil)
  13702. ;; try completion
  13703. (setq rtn (try-completion s2 ctable confirm))
  13704. (when (stringp rtn)
  13705. (setq rtn
  13706. (concat s1 s2 (substring rtn (length s2))
  13707. (if (and org-add-colon-after-tag-completion
  13708. (assoc rtn ctable))
  13709. ":" ""))))
  13710. rtn)
  13711. ((eq flag t)
  13712. ;; all-completions
  13713. (all-completions s2 ctable confirm))
  13714. ((eq flag 'lambda)
  13715. ;; exact match?
  13716. (assoc s2 ctable)))))
  13717. (defun org-fast-tag-insert (kwd tags face &optional end)
  13718. "Insert KDW, and the TAGS, the latter with face FACE.
  13719. Also insert END."
  13720. (insert (format "%-12s" (concat kwd ":"))
  13721. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13722. (or end "")))
  13723. (defun org-fast-tag-show-exit (flag)
  13724. (save-excursion
  13725. (org-goto-line 3)
  13726. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13727. (replace-match ""))
  13728. (when flag
  13729. (end-of-line 1)
  13730. (org-move-to-column (- (window-width) 19) t)
  13731. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13732. (defun org-set-current-tags-overlay (current prefix)
  13733. "Add an overlay to CURRENT tag with PREFIX."
  13734. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13735. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13736. (org-overlay-display org-tags-overlay (concat prefix s))))
  13737. (defvar org-last-tag-selection-key nil)
  13738. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13739. "Fast tag selection with single keys.
  13740. CURRENT is the current list of tags in the headline, INHERITED is the
  13741. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13742. possibly with grouping information. TODO-TABLE is a similar table with
  13743. TODO keywords, should these have keys assigned to them.
  13744. If the keys are nil, a-z are automatically assigned.
  13745. Returns the new tags string, or nil to not change the current settings."
  13746. (let* ((fulltable (append table todo-table))
  13747. (maxlen (apply 'max (mapcar
  13748. (lambda (x)
  13749. (if (stringp (car x)) (string-width (car x)) 0))
  13750. fulltable)))
  13751. (buf (current-buffer))
  13752. (expert (eq org-fast-tag-selection-single-key 'expert))
  13753. (buffer-tags nil)
  13754. (fwidth (+ maxlen 3 1 3))
  13755. (ncol (/ (- (window-width) 4) fwidth))
  13756. (i-face 'org-done)
  13757. (c-face 'org-todo)
  13758. tg cnt e c char c1 c2 ntable tbl rtn
  13759. ov-start ov-end ov-prefix
  13760. (exit-after-next org-fast-tag-selection-single-key)
  13761. (done-keywords org-done-keywords)
  13762. groups ingroup intaggroup)
  13763. (save-excursion
  13764. (beginning-of-line 1)
  13765. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13766. (setq ov-start (match-beginning 1)
  13767. ov-end (match-end 1)
  13768. ov-prefix "")
  13769. (setq ov-start (1- (point-at-eol))
  13770. ov-end (1+ ov-start))
  13771. (skip-chars-forward "^\n\r")
  13772. (setq ov-prefix
  13773. (concat
  13774. (buffer-substring (1- (point)) (point))
  13775. (if (> (current-column) org-tags-column)
  13776. " "
  13777. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13778. (move-overlay org-tags-overlay ov-start ov-end)
  13779. (save-window-excursion
  13780. (if expert
  13781. (set-buffer (get-buffer-create " *Org tags*"))
  13782. (delete-other-windows)
  13783. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13784. (org-switch-to-buffer-other-window " *Org tags*"))
  13785. (erase-buffer)
  13786. (setq-local org-done-keywords done-keywords)
  13787. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13788. (org-fast-tag-insert "Current" current c-face "\n\n")
  13789. (org-fast-tag-show-exit exit-after-next)
  13790. (org-set-current-tags-overlay current ov-prefix)
  13791. (setq tbl fulltable char ?a cnt 0)
  13792. (while (setq e (pop tbl))
  13793. (cond
  13794. ((eq (car e) :startgroup)
  13795. (push '() groups) (setq ingroup t)
  13796. (unless (zerop cnt)
  13797. (setq cnt 0)
  13798. (insert "\n"))
  13799. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13800. ((eq (car e) :endgroup)
  13801. (setq ingroup nil cnt 0)
  13802. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13803. ((eq (car e) :startgrouptag)
  13804. (setq intaggroup t)
  13805. (unless (zerop cnt)
  13806. (setq cnt 0)
  13807. (insert "\n"))
  13808. (insert "[ "))
  13809. ((eq (car e) :endgrouptag)
  13810. (setq intaggroup nil cnt 0)
  13811. (insert "]\n"))
  13812. ((equal e '(:newline))
  13813. (unless (zerop cnt)
  13814. (setq cnt 0)
  13815. (insert "\n")
  13816. (setq e (car tbl))
  13817. (while (equal (car tbl) '(:newline))
  13818. (insert "\n")
  13819. (setq tbl (cdr tbl)))))
  13820. ((equal e '(:grouptags)) (insert " : "))
  13821. (t
  13822. (setq tg (copy-sequence (car e)) c2 nil)
  13823. (if (cdr e)
  13824. (setq c (cdr e))
  13825. ;; automatically assign a character.
  13826. (setq c1 (string-to-char
  13827. (downcase (substring
  13828. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13829. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13830. (while (or (rassoc char ntable) (rassoc char table))
  13831. (setq char (1+ char)))
  13832. (setq c2 c1))
  13833. (setq c (or c2 char)))
  13834. (when ingroup (push tg (car groups)))
  13835. (setq tg (org-add-props tg nil 'face
  13836. (cond
  13837. ((not (assoc tg table))
  13838. (org-get-todo-face tg))
  13839. ((member tg current) c-face)
  13840. ((member tg inherited) i-face))))
  13841. (when (equal (caar tbl) :grouptags)
  13842. (org-add-props tg nil 'face 'org-tag-group))
  13843. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13844. (insert "[" c "] " tg (make-string
  13845. (- fwidth 4 (length tg)) ?\ ))
  13846. (push (cons tg c) ntable)
  13847. (when (= (cl-incf cnt) ncol)
  13848. (insert "\n")
  13849. (when (or ingroup intaggroup) (insert " "))
  13850. (setq cnt 0)))))
  13851. (setq ntable (nreverse ntable))
  13852. (insert "\n")
  13853. (goto-char (point-min))
  13854. (unless expert (org-fit-window-to-buffer))
  13855. (setq rtn
  13856. (catch 'exit
  13857. (while t
  13858. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13859. (if (not groups) "no " "")
  13860. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13861. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13862. (setq org-last-tag-selection-key c)
  13863. (cond
  13864. ((= c ?\r) (throw 'exit t))
  13865. ((= c ?!)
  13866. (setq groups (not groups))
  13867. (goto-char (point-min))
  13868. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13869. ((= c ?\C-c)
  13870. (if (not expert)
  13871. (org-fast-tag-show-exit
  13872. (setq exit-after-next (not exit-after-next)))
  13873. (setq expert nil)
  13874. (delete-other-windows)
  13875. (set-window-buffer (split-window-vertically) " *Org tags*")
  13876. (org-switch-to-buffer-other-window " *Org tags*")
  13877. (org-fit-window-to-buffer)))
  13878. ((or (= c ?\C-g)
  13879. (and (= c ?q) (not (rassoc c ntable))))
  13880. (delete-overlay org-tags-overlay)
  13881. (setq quit-flag t))
  13882. ((= c ?\ )
  13883. (setq current nil)
  13884. (when exit-after-next (setq exit-after-next 'now)))
  13885. ((= c ?\t)
  13886. (condition-case nil
  13887. (setq tg (completing-read
  13888. "Tag: "
  13889. (or buffer-tags
  13890. (with-current-buffer buf
  13891. (setq buffer-tags
  13892. (org-get-buffer-tags))))))
  13893. (quit (setq tg "")))
  13894. (when (string-match "\\S-" tg)
  13895. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13896. (if (member tg current)
  13897. (setq current (delete tg current))
  13898. (push tg current)))
  13899. (when exit-after-next (setq exit-after-next 'now)))
  13900. ((setq e (rassoc c todo-table) tg (car e))
  13901. (with-current-buffer buf
  13902. (save-excursion (org-todo tg)))
  13903. (when exit-after-next (setq exit-after-next 'now)))
  13904. ((setq e (rassoc c ntable) tg (car e))
  13905. (if (member tg current)
  13906. (setq current (delete tg current))
  13907. (cl-loop for g in groups do
  13908. (when (member tg g)
  13909. (dolist (x g) (setq current (delete x current)))))
  13910. (push tg current))
  13911. (when exit-after-next (setq exit-after-next 'now))))
  13912. ;; Create a sorted list
  13913. (setq current
  13914. (sort current
  13915. (lambda (a b)
  13916. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13917. (when (eq exit-after-next 'now) (throw 'exit t))
  13918. (goto-char (point-min))
  13919. (beginning-of-line 2)
  13920. (delete-region (point) (point-at-eol))
  13921. (org-fast-tag-insert "Current" current c-face)
  13922. (org-set-current-tags-overlay current ov-prefix)
  13923. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13924. (setq tg (match-string 1))
  13925. (add-text-properties
  13926. (match-beginning 1) (match-end 1)
  13927. (list 'face
  13928. (cond
  13929. ((member tg current) c-face)
  13930. ((member tg inherited) i-face)
  13931. (t (get-text-property (match-beginning 1) 'face))))))
  13932. (goto-char (point-min)))))
  13933. (delete-overlay org-tags-overlay)
  13934. (if rtn
  13935. (mapconcat 'identity current ":")
  13936. nil))))
  13937. (defun org-get-tags-string ()
  13938. "Get the TAGS string in the current headline."
  13939. (unless (org-at-heading-p t)
  13940. (user-error "Not on a heading"))
  13941. (save-excursion
  13942. (beginning-of-line 1)
  13943. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13944. (match-string-no-properties 1)
  13945. "")))
  13946. (defun org-get-tags ()
  13947. "Get the list of tags specified in the current headline."
  13948. (org-split-string (org-get-tags-string) ":"))
  13949. (defun org-get-buffer-tags ()
  13950. "Get a table of all tags used in the buffer, for completion."
  13951. (org-with-wide-buffer
  13952. (goto-char (point-min))
  13953. (let ((tag-re (concat org-outline-regexp-bol
  13954. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13955. tags)
  13956. (while (re-search-forward tag-re nil t)
  13957. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13958. (push tag tags)))
  13959. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13960. ;;;; The mapping API
  13961. (defvar org-agenda-skip-comment-trees)
  13962. (defvar org-agenda-skip-function)
  13963. (defun org-map-entries (func &optional match scope &rest skip)
  13964. "Call FUNC at each headline selected by MATCH in SCOPE.
  13965. FUNC is a function or a lisp form. The function will be called without
  13966. arguments, with the cursor positioned at the beginning of the headline.
  13967. The return values of all calls to the function will be collected and
  13968. returned as a list.
  13969. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13970. does not need to preserve point. After evaluation, the cursor will be
  13971. moved to the end of the line (presumably of the headline of the
  13972. processed entry) and search continues from there. Under some
  13973. circumstances, this may not produce the wanted results. For example,
  13974. if you have removed (e.g. archived) the current (sub)tree it could
  13975. mean that the next entry will be skipped entirely. In such cases, you
  13976. can specify the position from where search should continue by making
  13977. FUNC set the variable `org-map-continue-from' to the desired buffer
  13978. position.
  13979. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13980. Only headlines that are matched by this query will be considered during
  13981. the iteration. When MATCH is nil or t, all headlines will be
  13982. visited by the iteration.
  13983. SCOPE determines the scope of this command. It can be any of:
  13984. nil The current buffer, respecting the restriction if any
  13985. tree The subtree started with the entry at point
  13986. region The entries within the active region, if any
  13987. region-start-level
  13988. The entries within the active region, but only those at
  13989. the same level than the first one.
  13990. file The current buffer, without restriction
  13991. file-with-archives
  13992. The current buffer, and any archives associated with it
  13993. agenda All agenda files
  13994. agenda-with-archives
  13995. All agenda files with any archive files associated with them
  13996. \(file1 file2 ...)
  13997. If this is a list, all files in the list will be scanned
  13998. The remaining args are treated as settings for the skipping facilities of
  13999. the scanner. The following items can be given here:
  14000. archive skip trees with the archive tag
  14001. comment skip trees with the COMMENT keyword
  14002. function or Emacs Lisp form:
  14003. will be used as value for `org-agenda-skip-function', so
  14004. whenever the function returns a position, FUNC will not be
  14005. called for that entry and search will continue from the
  14006. position returned
  14007. If your function needs to retrieve the tags including inherited tags
  14008. at the *current* entry, you can use the value of the variable
  14009. `org-scanner-tags' which will be much faster than getting the value
  14010. with `org-get-tags-at'. If your function gets properties with
  14011. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14012. to t around the call to `org-entry-properties' to get the same speedup.
  14013. Note that if your function moves around to retrieve tags and properties at
  14014. a *different* entry, you cannot use these techniques."
  14015. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14016. (not (org-region-active-p)))
  14017. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14018. (org-agenda-skip-archived-trees (memq 'archive skip))
  14019. (org-agenda-skip-comment-trees (memq 'comment skip))
  14020. (org-agenda-skip-function
  14021. (car (org-delete-all '(comment archive) skip)))
  14022. (org-tags-match-list-sublevels t)
  14023. (start-level (eq scope 'region-start-level))
  14024. matcher res
  14025. org-todo-keywords-for-agenda
  14026. org-done-keywords-for-agenda
  14027. org-todo-keyword-alist-for-agenda
  14028. org-tag-alist-for-agenda
  14029. org--matcher-tags-todo-only)
  14030. (cond
  14031. ((eq match t) (setq matcher t))
  14032. ((eq match nil) (setq matcher t))
  14033. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14034. (save-excursion
  14035. (save-restriction
  14036. (cond ((eq scope 'tree)
  14037. (org-back-to-heading t)
  14038. (org-narrow-to-subtree)
  14039. (setq scope nil))
  14040. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14041. (org-region-active-p))
  14042. ;; If needed, set start-level to a string like "2"
  14043. (when start-level
  14044. (save-excursion
  14045. (goto-char (region-beginning))
  14046. (unless (org-at-heading-p) (outline-next-heading))
  14047. (setq start-level (org-current-level))))
  14048. (narrow-to-region (region-beginning)
  14049. (save-excursion
  14050. (goto-char (region-end))
  14051. (unless (and (bolp) (org-at-heading-p))
  14052. (outline-next-heading))
  14053. (point)))
  14054. (setq scope nil)))
  14055. (if (not scope)
  14056. (progn
  14057. (org-agenda-prepare-buffers
  14058. (and buffer-file-name (list buffer-file-name)))
  14059. (setq res
  14060. (org-scan-tags
  14061. func matcher org--matcher-tags-todo-only start-level)))
  14062. ;; Get the right scope
  14063. (cond
  14064. ((and scope (listp scope) (symbolp (car scope)))
  14065. (setq scope (eval scope)))
  14066. ((eq scope 'agenda)
  14067. (setq scope (org-agenda-files t)))
  14068. ((eq scope 'agenda-with-archives)
  14069. (setq scope (org-agenda-files t))
  14070. (setq scope (org-add-archive-files scope)))
  14071. ((eq scope 'file)
  14072. (setq scope (and buffer-file-name (list buffer-file-name))))
  14073. ((eq scope 'file-with-archives)
  14074. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14075. (org-agenda-prepare-buffers scope)
  14076. (dolist (file scope)
  14077. (with-current-buffer (org-find-base-buffer-visiting file)
  14078. (org-with-wide-buffer
  14079. (goto-char (point-min))
  14080. (setq res
  14081. (append
  14082. res
  14083. (org-scan-tags
  14084. func matcher org--matcher-tags-todo-only)))))))))
  14085. res)))
  14086. ;;; Properties API
  14087. (defconst org-special-properties
  14088. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14089. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14090. "The special properties valid in Org mode.
  14091. These are properties that are not defined in the property drawer,
  14092. but in some other way.")
  14093. (defconst org-default-properties
  14094. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14095. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14096. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14097. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14098. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14099. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14100. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14101. "Some properties that are used by Org mode for various purposes.
  14102. Being in this list makes sure that they are offered for completion.")
  14103. (defun org--valid-property-p (property)
  14104. "Non nil when string PROPERTY is a valid property name."
  14105. (not
  14106. (or (equal property "")
  14107. (string-match-p "\\s-" property))))
  14108. (defun org--update-property-plist (key val props)
  14109. "Associate KEY to VAL in alist PROPS.
  14110. Modifications are made by side-effect. Return new alist."
  14111. (let* ((appending (string= (substring key -1) "+"))
  14112. (key (if appending (substring key 0 -1) key))
  14113. (old (assoc-string key props t)))
  14114. (if (not old) (cons (cons key val) props)
  14115. (setcdr old (if appending (concat (cdr old) " " val) val))
  14116. props)))
  14117. (defun org-get-property-block (&optional beg force)
  14118. "Return the (beg . end) range of the body of the property drawer.
  14119. BEG is the beginning of the current subtree, or of the part
  14120. before the first headline. If it is not given, it will be found.
  14121. If the drawer does not exist, create it if FORCE is non-nil, or
  14122. return nil."
  14123. (org-with-wide-buffer
  14124. (when beg (goto-char beg))
  14125. (unless (org-before-first-heading-p)
  14126. (let ((beg (cond (beg)
  14127. ((or (not (featurep 'org-inlinetask))
  14128. (org-inlinetask-in-task-p))
  14129. (org-back-to-heading t))
  14130. (t (org-with-limited-levels (org-back-to-heading t))))))
  14131. (forward-line)
  14132. (when (looking-at-p org-planning-line-re) (forward-line))
  14133. (cond ((looking-at org-property-drawer-re)
  14134. (forward-line)
  14135. (cons (point) (progn (goto-char (match-end 0))
  14136. (line-beginning-position))))
  14137. (force
  14138. (goto-char beg)
  14139. (org-insert-property-drawer)
  14140. (let ((pos (save-excursion (search-forward ":END:")
  14141. (line-beginning-position))))
  14142. (cons pos pos))))))))
  14143. (defun org-at-property-p ()
  14144. "Non-nil when point is inside a property drawer.
  14145. See `org-property-re' for match data, if applicable."
  14146. (save-excursion
  14147. (beginning-of-line)
  14148. (and (looking-at org-property-re)
  14149. (let ((property-drawer (save-match-data (org-get-property-block))))
  14150. (and property-drawer
  14151. (>= (point) (car property-drawer))
  14152. (< (point) (cdr property-drawer)))))))
  14153. (defun org-property-action ()
  14154. "Do an action on properties."
  14155. (interactive)
  14156. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14157. (let ((c (read-char-exclusive)))
  14158. (cl-case c
  14159. (?s (call-interactively #'org-set-property))
  14160. (?d (call-interactively #'org-delete-property))
  14161. (?D (call-interactively #'org-delete-property-globally))
  14162. (?c (call-interactively #'org-compute-property-at-point))
  14163. (otherwise (user-error "No such property action %c" c)))))
  14164. (defun org-inc-effort ()
  14165. "Increment the value of the effort property in the current entry."
  14166. (interactive)
  14167. (org-set-effort nil t))
  14168. (defvar org-clock-effort) ; Defined in org-clock.el.
  14169. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14170. (defun org-set-effort (&optional value increment)
  14171. "Set the effort property of the current entry.
  14172. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14173. 10th allowed value.
  14174. When INCREMENT is non-nil, set the property to the next allowed value."
  14175. (interactive "P")
  14176. (when (equal value 0) (setq value 10))
  14177. (let* ((completion-ignore-case t)
  14178. (prop org-effort-property)
  14179. (cur (org-entry-get nil prop))
  14180. (allowed (org-property-get-allowed-values nil prop 'table))
  14181. (existing (mapcar 'list (org-property-values prop)))
  14182. (heading (nth 4 (org-heading-components)))
  14183. rpl
  14184. (val (cond
  14185. ((stringp value) value)
  14186. ((and allowed (integerp value))
  14187. (or (car (nth (1- value) allowed))
  14188. (car (org-last allowed))))
  14189. ((and allowed increment)
  14190. (or (cl-caadr (member (list cur) allowed))
  14191. (user-error "Allowed effort values are not set")))
  14192. (allowed
  14193. (message "Select 1-9,0, [RET%s]: %s"
  14194. (if cur (concat "=" cur) "")
  14195. (mapconcat 'car allowed " "))
  14196. (setq rpl (read-char-exclusive))
  14197. (if (equal rpl ?\r)
  14198. cur
  14199. (setq rpl (- rpl ?0))
  14200. (when (equal rpl 0) (setq rpl 10))
  14201. (if (and (> rpl 0) (<= rpl (length allowed)))
  14202. (car (nth (1- rpl) allowed))
  14203. (org-completing-read "Effort: " allowed nil))))
  14204. (t
  14205. (org-completing-read
  14206. (concat "Effort" (and cur (string-match "\\S-" cur)
  14207. (concat " [" cur "]"))
  14208. ": ")
  14209. existing nil nil "" nil cur)))))
  14210. (unless (equal (org-entry-get nil prop) val)
  14211. (org-entry-put nil prop val))
  14212. (org-refresh-property
  14213. '((effort . identity)
  14214. (effort-minutes . org-duration-to-minutes))
  14215. val)
  14216. (when (equal heading (bound-and-true-p org-clock-current-task))
  14217. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14218. (org-clock-update-mode-line))
  14219. (message "%s is now %s" prop val)))
  14220. (defun org-entry-properties (&optional pom which)
  14221. "Get all properties of the current entry.
  14222. When POM is a buffer position, get all properties from the entry
  14223. there instead.
  14224. This includes the TODO keyword, the tags, time strings for
  14225. deadline, scheduled, and clocking, and any additional properties
  14226. defined in the entry.
  14227. If WHICH is nil or `all', get all properties. If WHICH is
  14228. `special' or `standard', only get that subclass. If WHICH is
  14229. a string, only get that property.
  14230. Return value is an alist. Keys are properties, as upcased
  14231. strings."
  14232. (org-with-point-at pom
  14233. (when (and (derived-mode-p 'org-mode)
  14234. (ignore-errors (org-back-to-heading t)))
  14235. (catch 'exit
  14236. (let* ((beg (point))
  14237. (specific (and (stringp which) (upcase which)))
  14238. (which (cond ((not specific) which)
  14239. ((member specific org-special-properties) 'special)
  14240. (t 'standard)))
  14241. props)
  14242. ;; Get the special properties, like TODO and TAGS.
  14243. (when (memq which '(nil all special))
  14244. (when (or (not specific) (string= specific "CLOCKSUM"))
  14245. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14246. (when clocksum
  14247. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  14248. props)))
  14249. (when specific (throw 'exit props)))
  14250. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14251. (let ((clocksumt (get-text-property (point)
  14252. :org-clock-minutes-today)))
  14253. (when clocksumt
  14254. (push (cons "CLOCKSUM_T"
  14255. (org-duration-from-minutes clocksumt))
  14256. props)))
  14257. (when specific (throw 'exit props)))
  14258. (when (or (not specific) (string= specific "ITEM"))
  14259. (let ((case-fold-search nil))
  14260. (when (looking-at org-complex-heading-regexp)
  14261. (push (cons "ITEM"
  14262. (let ((title (match-string-no-properties 4)))
  14263. (if (org-string-nw-p title)
  14264. (org-remove-tabs title)
  14265. "")))
  14266. props)))
  14267. (when specific (throw 'exit props)))
  14268. (when (or (not specific) (string= specific "TODO"))
  14269. (let ((case-fold-search nil))
  14270. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14271. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14272. (when specific (throw 'exit props)))
  14273. (when (or (not specific) (string= specific "PRIORITY"))
  14274. (push (cons "PRIORITY"
  14275. (if (looking-at org-priority-regexp)
  14276. (match-string-no-properties 2)
  14277. (char-to-string org-default-priority)))
  14278. props)
  14279. (when specific (throw 'exit props)))
  14280. (when (or (not specific) (string= specific "FILE"))
  14281. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14282. props)
  14283. (when specific (throw 'exit props)))
  14284. (when (or (not specific) (string= specific "TAGS"))
  14285. (let ((value (org-string-nw-p (org-get-tags-string))))
  14286. (when value (push (cons "TAGS" value) props)))
  14287. (when specific (throw 'exit props)))
  14288. (when (or (not specific) (string= specific "ALLTAGS"))
  14289. (let ((value (org-get-tags-at)))
  14290. (when value
  14291. (push (cons "ALLTAGS"
  14292. (format ":%s:" (mapconcat #'identity value ":")))
  14293. props)))
  14294. (when specific (throw 'exit props)))
  14295. (when (or (not specific) (string= specific "BLOCKED"))
  14296. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14297. (when specific (throw 'exit props)))
  14298. (when (or (not specific)
  14299. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14300. (forward-line)
  14301. (when (looking-at-p org-planning-line-re)
  14302. (end-of-line)
  14303. (let ((bol (line-beginning-position))
  14304. ;; Backward compatibility: time keywords used to
  14305. ;; be configurable (before 8.3). Make sure we
  14306. ;; get the correct keyword.
  14307. (key-assoc `(("CLOSED" . ,org-closed-string)
  14308. ("DEADLINE" . ,org-deadline-string)
  14309. ("SCHEDULED" . ,org-scheduled-string))))
  14310. (dolist (pair (if specific (list (assoc specific key-assoc))
  14311. key-assoc))
  14312. (save-excursion
  14313. (when (search-backward (cdr pair) bol t)
  14314. (goto-char (match-end 0))
  14315. (skip-chars-forward " \t")
  14316. (and (looking-at org-ts-regexp-both)
  14317. (push (cons (car pair)
  14318. (match-string-no-properties 0))
  14319. props)))))))
  14320. (when specific (throw 'exit props)))
  14321. (when (or (not specific)
  14322. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14323. (let ((find-ts
  14324. (lambda (end ts)
  14325. ;; Fix next time-stamp before END. TS is the
  14326. ;; list of time-stamps found so far.
  14327. (let ((ts ts)
  14328. (regexp (cond
  14329. ((string= specific "TIMESTAMP")
  14330. org-ts-regexp)
  14331. ((string= specific "TIMESTAMP_IA")
  14332. org-ts-regexp-inactive)
  14333. ((assoc "TIMESTAMP_IA" ts)
  14334. org-ts-regexp)
  14335. ((assoc "TIMESTAMP" ts)
  14336. org-ts-regexp-inactive)
  14337. (t org-ts-regexp-both))))
  14338. (catch 'next
  14339. (while (re-search-forward regexp end t)
  14340. (backward-char)
  14341. (let ((object (org-element-context)))
  14342. ;; Accept to match timestamps in node
  14343. ;; properties, too.
  14344. (when (memq (org-element-type object)
  14345. '(node-property timestamp))
  14346. (let ((type
  14347. (org-element-property :type object)))
  14348. (cond
  14349. ((and (memq type '(active active-range))
  14350. (not (equal specific "TIMESTAMP_IA")))
  14351. (unless (assoc "TIMESTAMP" ts)
  14352. (push (cons "TIMESTAMP"
  14353. (org-element-property
  14354. :raw-value object))
  14355. ts)
  14356. (when specific (throw 'exit ts))))
  14357. ((and (memq type '(inactive inactive-range))
  14358. (not (string= specific "TIMESTAMP")))
  14359. (unless (assoc "TIMESTAMP_IA" ts)
  14360. (push (cons "TIMESTAMP_IA"
  14361. (org-element-property
  14362. :raw-value object))
  14363. ts)
  14364. (when specific (throw 'exit ts))))))
  14365. ;; Both timestamp types are found,
  14366. ;; move to next part.
  14367. (when (= (length ts) 2) (throw 'next ts)))))
  14368. ts)))))
  14369. (goto-char beg)
  14370. ;; First look for timestamps within headline.
  14371. (let ((ts (funcall find-ts (line-end-position) nil)))
  14372. (if (= (length ts) 2) (setq props (nconc ts props))
  14373. ;; Then find timestamps in the section, skipping
  14374. ;; planning line.
  14375. (let ((end (save-excursion (outline-next-heading))))
  14376. (forward-line)
  14377. (when (looking-at-p org-planning-line-re) (forward-line))
  14378. (setq props (nconc (funcall find-ts end ts) props))))))))
  14379. ;; Get the standard properties, like :PROP:.
  14380. (when (memq which '(nil all standard))
  14381. ;; If we are looking after a specific property, delegate
  14382. ;; to `org-entry-get', which is faster. However, make an
  14383. ;; exception for "CATEGORY", since it can be also set
  14384. ;; through keywords (i.e. #+CATEGORY).
  14385. (if (and specific (not (equal specific "CATEGORY")))
  14386. (let ((value (org-entry-get beg specific nil t)))
  14387. (throw 'exit (and value (list (cons specific value)))))
  14388. (let ((range (org-get-property-block beg)))
  14389. (when range
  14390. (let ((end (cdr range)) seen-base)
  14391. (goto-char (car range))
  14392. ;; Unlike to `org--update-property-plist', we
  14393. ;; handle the case where base values is found
  14394. ;; after its extension. We also forbid standard
  14395. ;; properties to be named as special properties.
  14396. (while (re-search-forward org-property-re end t)
  14397. (let* ((key (upcase (match-string-no-properties 2)))
  14398. (extendp (string-match-p "\\+\\'" key))
  14399. (key-base (if extendp (substring key 0 -1) key))
  14400. (value (match-string-no-properties 3)))
  14401. (cond
  14402. ((member-ignore-case key-base org-special-properties))
  14403. (extendp
  14404. (setq props
  14405. (org--update-property-plist key value props)))
  14406. ((member key seen-base))
  14407. (t (push key seen-base)
  14408. (let ((p (assoc-string key props t)))
  14409. (if p (setcdr p (concat value " " (cdr p)))
  14410. (push (cons key value) props))))))))))))
  14411. (unless (assoc "CATEGORY" props)
  14412. (push (cons "CATEGORY" (org-get-category beg)) props)
  14413. (when (string= specific "CATEGORY") (throw 'exit props)))
  14414. ;; Return value.
  14415. props)))))
  14416. (defun org--property-local-values (property literal-nil)
  14417. "Return value for PROPERTY in current entry.
  14418. Value is a list whose car is the base value for PROPERTY and cdr
  14419. a list of accumulated values. Return nil if neither is found in
  14420. the entry. Also return nil when PROPERTY is set to \"nil\",
  14421. unless LITERAL-NIL is non-nil."
  14422. (let ((range (org-get-property-block)))
  14423. (when range
  14424. (goto-char (car range))
  14425. (let* ((case-fold-search t)
  14426. (end (cdr range))
  14427. (value
  14428. ;; Base value.
  14429. (save-excursion
  14430. (let ((v (and (re-search-forward
  14431. (org-re-property property nil t) end t)
  14432. (match-string-no-properties 3))))
  14433. (list (if literal-nil v (org-not-nil v)))))))
  14434. ;; Find additional values.
  14435. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14436. (while (re-search-forward property+ end t)
  14437. (push (match-string-no-properties 3) value)))
  14438. ;; Return final values.
  14439. (and (not (equal value '(nil))) (nreverse value))))))
  14440. (defun org--property-global-value (property literal-nil)
  14441. "Return value for PROPERTY in current buffer.
  14442. Return value is a string. Return nil if property is not set
  14443. globally. Also return nil when PROPERTY is set to \"nil\",
  14444. unless LITERAL-NIL is non-nil."
  14445. (let ((global
  14446. (cdr (or (assoc-string property org-file-properties t)
  14447. (assoc-string property org-global-properties t)
  14448. (assoc-string property org-global-properties-fixed t)))))
  14449. (if literal-nil global (org-not-nil global))))
  14450. (defun org-entry-get (pom property &optional inherit literal-nil)
  14451. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14452. If INHERIT is non-nil and the entry does not have the property,
  14453. then also check higher levels of the hierarchy. If INHERIT is
  14454. the symbol `selective', use inheritance only if the setting in
  14455. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14456. If the property is present but empty, the return value is the
  14457. empty string. If the property is not present at all, nil is
  14458. returned. In any other case, return the value as a string.
  14459. Search is case-insensitive.
  14460. If LITERAL-NIL is set, return the string value \"nil\" as
  14461. a string, do not interpret it as the list atom nil. This is used
  14462. for inheritance when a \"nil\" value can supersede a non-nil
  14463. value higher up the hierarchy."
  14464. (org-with-point-at pom
  14465. (cond
  14466. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14467. ;; We need a special property. Use `org-entry-properties' to
  14468. ;; retrieve it, but specify the wanted property.
  14469. (cdr (assoc-string property (org-entry-properties nil property))))
  14470. ((and inherit
  14471. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14472. (org-entry-get-with-inheritance property literal-nil))
  14473. (t
  14474. (let* ((local (org--property-local-values property literal-nil))
  14475. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14476. (if literal-nil value (org-not-nil value)))))))
  14477. (defun org-property-or-variable-value (var &optional inherit)
  14478. "Check if there is a property fixing the value of VAR.
  14479. If yes, return this value. If not, return the current value of the variable."
  14480. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14481. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14482. (read prop)
  14483. (symbol-value var))))
  14484. (defun org-entry-delete (pom property)
  14485. "Delete PROPERTY from entry at point-or-marker POM.
  14486. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14487. non-nil when a property was removed."
  14488. (org-with-point-at pom
  14489. (pcase (org-get-property-block)
  14490. (`(,begin . ,origin)
  14491. (let* ((end (copy-marker origin))
  14492. (re (org-re-property
  14493. (concat (regexp-quote property) "\\+?") t t)))
  14494. (goto-char begin)
  14495. (while (re-search-forward re end t)
  14496. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14497. ;; If drawer is empty, remove it altogether.
  14498. (when (= begin end)
  14499. (delete-region (line-beginning-position 0)
  14500. (line-beginning-position 2)))
  14501. ;; Return non-nil if some property was removed.
  14502. (prog1 (/= end origin) (set-marker end nil))))
  14503. (_ nil))))
  14504. ;; Multi-values properties are properties that contain multiple values
  14505. ;; These values are assumed to be single words, separated by whitespace.
  14506. (defun org-entry-add-to-multivalued-property (pom property value)
  14507. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14508. (let* ((old (org-entry-get pom property))
  14509. (values (and old (org-split-string old "[ \t]"))))
  14510. (setq value (org-entry-protect-space value))
  14511. (unless (member value values)
  14512. (setq values (append values (list value)))
  14513. (org-entry-put pom property
  14514. (mapconcat 'identity values " ")))))
  14515. (defun org-entry-remove-from-multivalued-property (pom property value)
  14516. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14517. (let* ((old (org-entry-get pom property))
  14518. (values (and old (org-split-string old "[ \t]"))))
  14519. (setq value (org-entry-protect-space value))
  14520. (when (member value values)
  14521. (setq values (delete value values))
  14522. (org-entry-put pom property
  14523. (mapconcat 'identity values " ")))))
  14524. (defun org-entry-member-in-multivalued-property (pom property value)
  14525. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14526. (let* ((old (org-entry-get pom property))
  14527. (values (and old (org-split-string old "[ \t]"))))
  14528. (setq value (org-entry-protect-space value))
  14529. (member value values)))
  14530. (defun org-entry-get-multivalued-property (pom property)
  14531. "Return a list of values in a multivalued property."
  14532. (let* ((value (org-entry-get pom property))
  14533. (values (and value (org-split-string value "[ \t]"))))
  14534. (mapcar 'org-entry-restore-space values)))
  14535. (defun org-entry-put-multivalued-property (pom property &rest values)
  14536. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14537. VALUES should be a list of strings. Spaces will be protected."
  14538. (org-entry-put pom property
  14539. (mapconcat 'org-entry-protect-space values " "))
  14540. (let* ((value (org-entry-get pom property))
  14541. (values (and value (org-split-string value "[ \t]"))))
  14542. (mapcar 'org-entry-restore-space values)))
  14543. (defun org-entry-protect-space (s)
  14544. "Protect spaces and newline in string S."
  14545. (while (string-match " " s)
  14546. (setq s (replace-match "%20" t t s)))
  14547. (while (string-match "\n" s)
  14548. (setq s (replace-match "%0A" t t s)))
  14549. s)
  14550. (defun org-entry-restore-space (s)
  14551. "Restore spaces and newline in string S."
  14552. (while (string-match "%20" s)
  14553. (setq s (replace-match " " t t s)))
  14554. (while (string-match "%0A" s)
  14555. (setq s (replace-match "\n" t t s)))
  14556. s)
  14557. (defvar org-entry-property-inherited-from (make-marker)
  14558. "Marker pointing to the entry from where a property was inherited.
  14559. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14560. location of the entry where the inheritance search matched. If there was
  14561. no match, the marker will point nowhere.
  14562. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14563. is set.")
  14564. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14565. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14566. The search will stop at the first ancestor which has the property defined.
  14567. If the value found is \"nil\", return nil to show that the property
  14568. should be considered as undefined (this is the meaning of nil here).
  14569. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14570. (move-marker org-entry-property-inherited-from nil)
  14571. (org-with-wide-buffer
  14572. (let (value)
  14573. (catch 'exit
  14574. (while t
  14575. (let ((v (org--property-local-values property literal-nil)))
  14576. (when v
  14577. (setq value
  14578. (concat (mapconcat #'identity (delq nil v) " ")
  14579. (and value " ")
  14580. value)))
  14581. (cond
  14582. ((car v)
  14583. (org-back-to-heading t)
  14584. (move-marker org-entry-property-inherited-from (point))
  14585. (throw 'exit nil))
  14586. ((org-up-heading-safe))
  14587. (t
  14588. (let ((global (org--property-global-value property literal-nil)))
  14589. (cond ((not global))
  14590. (value (setq value (concat global " " value)))
  14591. (t (setq value global))))
  14592. (throw 'exit nil))))))
  14593. (if literal-nil value (org-not-nil value)))))
  14594. (defvar org-property-changed-functions nil
  14595. "Hook called when the value of a property has changed.
  14596. Each hook function should accept two arguments, the name of the property
  14597. and the new value.")
  14598. (defun org-entry-put (pom property value)
  14599. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14600. If the value is nil, it is converted to the empty string. If it
  14601. is not a string, an error is raised. Also raise an error on
  14602. invalid property names.
  14603. PROPERTY can be any regular property (see
  14604. `org-special-properties'). It can also be \"TODO\",
  14605. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14606. For the last two properties, VALUE may have any of the special
  14607. values \"earlier\" and \"later\". The function then increases or
  14608. decreases scheduled or deadline date by one day."
  14609. (cond ((null value) (setq value ""))
  14610. ((not (stringp value)) (error "Properties values should be strings"))
  14611. ((not (org--valid-property-p property))
  14612. (user-error "Invalid property name: \"%s\"" property)))
  14613. (org-with-point-at pom
  14614. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14615. (org-back-to-heading t)
  14616. (org-with-limited-levels (org-back-to-heading t)))
  14617. (let ((beg (point)))
  14618. (cond
  14619. ((equal property "TODO")
  14620. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14621. ((not (member value org-todo-keywords-1))
  14622. (user-error "\"%s\" is not a valid TODO state" value)))
  14623. (org-todo value)
  14624. (org-set-tags nil 'align))
  14625. ((equal property "PRIORITY")
  14626. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14627. (org-set-tags nil 'align))
  14628. ((equal property "SCHEDULED")
  14629. (forward-line)
  14630. (if (and (looking-at-p org-planning-line-re)
  14631. (re-search-forward
  14632. org-scheduled-time-regexp (line-end-position) t))
  14633. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14634. ((string= value "later") (org-timestamp-change 1 'day))
  14635. ((string= value "") (org-schedule '(4)))
  14636. (t (org-schedule nil value)))
  14637. (if (member value '("earlier" "later" ""))
  14638. (call-interactively #'org-schedule)
  14639. (org-schedule nil value))))
  14640. ((equal property "DEADLINE")
  14641. (forward-line)
  14642. (if (and (looking-at-p org-planning-line-re)
  14643. (re-search-forward
  14644. org-deadline-time-regexp (line-end-position) t))
  14645. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14646. ((string= value "later") (org-timestamp-change 1 'day))
  14647. ((string= value "") (org-deadline '(4)))
  14648. (t (org-deadline nil value)))
  14649. (if (member value '("earlier" "later" ""))
  14650. (call-interactively #'org-deadline)
  14651. (org-deadline nil value))))
  14652. ((member property org-special-properties)
  14653. (error "The %s property cannot be set with `org-entry-put'" property))
  14654. (t
  14655. (let* ((range (org-get-property-block beg 'force))
  14656. (end (cdr range))
  14657. (case-fold-search t))
  14658. (goto-char (car range))
  14659. (if (re-search-forward (org-re-property property nil t) end t)
  14660. (progn (delete-region (match-beginning 0) (match-end 0))
  14661. (goto-char (match-beginning 0)))
  14662. (goto-char end)
  14663. (insert "\n")
  14664. (backward-char))
  14665. (insert ":" property ":")
  14666. (when value (insert " " value))
  14667. (org-indent-line)))))
  14668. (run-hook-with-args 'org-property-changed-functions property value)))
  14669. (defun org-buffer-property-keys
  14670. (&optional specials defaults columns ignore-malformed)
  14671. "Get all property keys in the current buffer.
  14672. When SPECIALS is non-nil, also list the special properties that
  14673. reflect things like tags and TODO state.
  14674. When DEFAULTS is non-nil, also include properties that has
  14675. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14676. DESCRIPTION, LOCATION, and LOGGING and others.
  14677. When COLUMNS in non-nil, also include property names given in
  14678. COLUMN formats in the current buffer.
  14679. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14680. automatically performed, such drawers will be silently ignored."
  14681. (let ((case-fold-search t)
  14682. (props (append
  14683. (and specials org-special-properties)
  14684. (and defaults (cons org-effort-property org-default-properties))
  14685. nil)))
  14686. (org-with-wide-buffer
  14687. (goto-char (point-min))
  14688. (while (re-search-forward org-property-start-re nil t)
  14689. (let ((range (org-get-property-block)))
  14690. (catch 'skip
  14691. (unless range
  14692. (when (and (not ignore-malformed)
  14693. (not (org-before-first-heading-p))
  14694. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14695. (line-beginning-position))))
  14696. (org-get-property-block nil t))
  14697. (throw 'skip nil))
  14698. (goto-char (car range))
  14699. (let ((begin (car range))
  14700. (end (cdr range)))
  14701. ;; Make sure that found property block is not located
  14702. ;; before current point, as it would generate an infloop.
  14703. ;; It can happen, for example, in the following
  14704. ;; situation:
  14705. ;;
  14706. ;; * Headline
  14707. ;; :PROPERTIES:
  14708. ;; ...
  14709. ;; :END:
  14710. ;; *************** Inlinetask
  14711. ;; #+BEGIN_EXAMPLE
  14712. ;; :PROPERTIES:
  14713. ;; #+END_EXAMPLE
  14714. ;;
  14715. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14716. (while (< (point) end)
  14717. (let ((p (progn (looking-at org-property-re)
  14718. (match-string-no-properties 2))))
  14719. ;; Only add true property name, not extension symbol.
  14720. (push (if (not (string-match-p "\\+\\'" p)) p
  14721. (substring p 0 -1))
  14722. props))
  14723. (forward-line))))
  14724. (outline-next-heading)))
  14725. (when columns
  14726. (goto-char (point-min))
  14727. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14728. (let ((element (org-element-at-point)))
  14729. (when (memq (org-element-type element) '(keyword node-property))
  14730. (let ((value (org-element-property :value element))
  14731. (start 0))
  14732. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14733. (setq start (match-end 0))
  14734. (let ((p (match-string-no-properties 1 value)))
  14735. (unless (member-ignore-case p org-special-properties)
  14736. (push p props))))))))))
  14737. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14738. (defun org-property-values (key)
  14739. "List all non-nil values of property KEY in current buffer."
  14740. (org-with-wide-buffer
  14741. (goto-char (point-min))
  14742. (let ((case-fold-search t)
  14743. (re (org-re-property key))
  14744. values)
  14745. (while (re-search-forward re nil t)
  14746. (push (org-entry-get (point) key) values))
  14747. (delete-dups values))))
  14748. (defun org-insert-property-drawer ()
  14749. "Insert a property drawer into the current entry."
  14750. (org-with-wide-buffer
  14751. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14752. (org-back-to-heading t)
  14753. (org-with-limited-levels (org-back-to-heading t)))
  14754. (forward-line)
  14755. (when (looking-at-p org-planning-line-re) (forward-line))
  14756. (unless (looking-at-p org-property-drawer-re)
  14757. ;; Make sure we start editing a line from current entry, not from
  14758. ;; next one. It prevents extending text properties or overlays
  14759. ;; belonging to the latter.
  14760. (when (bolp) (backward-char))
  14761. (let ((begin (1+ (point)))
  14762. (inhibit-read-only t))
  14763. (insert "\n:PROPERTIES:\n:END:")
  14764. (when (eobp) (insert "\n"))
  14765. (org-indent-region begin (point))))))
  14766. (defun org-insert-drawer (&optional arg drawer)
  14767. "Insert a drawer at point.
  14768. When optional argument ARG is non-nil, insert a property drawer.
  14769. Optional argument DRAWER, when non-nil, is a string representing
  14770. drawer's name. Otherwise, the user is prompted for a name.
  14771. If a region is active, insert the drawer around that region
  14772. instead.
  14773. Point is left between drawer's boundaries."
  14774. (interactive "P")
  14775. (let* ((drawer (if arg "PROPERTIES"
  14776. (or drawer (read-from-minibuffer "Drawer: ")))))
  14777. (cond
  14778. ;; With C-u, fall back on `org-insert-property-drawer'
  14779. (arg (org-insert-property-drawer))
  14780. ;; Check validity of suggested drawer's name.
  14781. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14782. (user-error "Invalid drawer name"))
  14783. ;; With an active region, insert a drawer at point.
  14784. ((not (org-region-active-p))
  14785. (progn
  14786. (unless (bolp) (insert "\n"))
  14787. (insert (format ":%s:\n\n:END:\n" drawer))
  14788. (forward-line -2)))
  14789. ;; Otherwise, insert the drawer at point
  14790. (t
  14791. (let ((rbeg (region-beginning))
  14792. (rend (copy-marker (region-end))))
  14793. (unwind-protect
  14794. (progn
  14795. (goto-char rbeg)
  14796. (beginning-of-line)
  14797. (when (save-excursion
  14798. (re-search-forward org-outline-regexp-bol rend t))
  14799. (user-error "Drawers cannot contain headlines"))
  14800. ;; Position point at the beginning of the first
  14801. ;; non-blank line in region. Insert drawer's opening
  14802. ;; there, then indent it.
  14803. (org-skip-whitespace)
  14804. (beginning-of-line)
  14805. (insert ":" drawer ":\n")
  14806. (forward-line -1)
  14807. (indent-for-tab-command)
  14808. ;; Move point to the beginning of the first blank line
  14809. ;; after the last non-blank line in region. Insert
  14810. ;; drawer's closing, then indent it.
  14811. (goto-char rend)
  14812. (skip-chars-backward " \r\t\n")
  14813. (insert "\n:END:")
  14814. (deactivate-mark t)
  14815. (indent-for-tab-command)
  14816. (unless (eolp) (insert "\n")))
  14817. ;; Clear marker, whatever the outcome of insertion is.
  14818. (set-marker rend nil)))))))
  14819. (defvar org-property-set-functions-alist nil
  14820. "Property set function alist.
  14821. Each entry should have the following format:
  14822. (PROPERTY . READ-FUNCTION)
  14823. The read function will be called with the same argument as
  14824. `org-completing-read'.")
  14825. (defun org-set-property-function (property)
  14826. "Get the function that should be used to set PROPERTY.
  14827. This is computed according to `org-property-set-functions-alist'."
  14828. (or (cdr (assoc property org-property-set-functions-alist))
  14829. 'org-completing-read))
  14830. (defun org-read-property-value (property)
  14831. "Read PROPERTY value from user."
  14832. (let* ((completion-ignore-case t)
  14833. (allowed (org-property-get-allowed-values nil property 'table))
  14834. (cur (org-entry-get nil property))
  14835. (prompt (concat property " value"
  14836. (if (and cur (string-match "\\S-" cur))
  14837. (concat " [" cur "]") "") ": "))
  14838. (set-function (org-set-property-function property))
  14839. (val (if allowed
  14840. (funcall set-function prompt allowed nil
  14841. (not (get-text-property 0 'org-unrestricted
  14842. (caar allowed))))
  14843. (funcall set-function prompt
  14844. (mapcar 'list (org-property-values property))
  14845. nil nil "" nil cur))))
  14846. (org-trim val)))
  14847. (defvar org-last-set-property nil)
  14848. (defvar org-last-set-property-value nil)
  14849. (defun org-read-property-name ()
  14850. "Read a property name."
  14851. (let ((completion-ignore-case t)
  14852. (default-prop (or (and (org-at-property-p)
  14853. (match-string-no-properties 2))
  14854. org-last-set-property)))
  14855. (org-completing-read
  14856. (concat "Property"
  14857. (if default-prop (concat " [" default-prop "]") "")
  14858. ": ")
  14859. (mapcar #'list (org-buffer-property-keys nil t t))
  14860. nil nil nil nil default-prop)))
  14861. (defun org-set-property-and-value (use-last)
  14862. "Allow to set [PROPERTY]: [value] direction from prompt.
  14863. When use-default, don't even ask, just use the last
  14864. \"[PROPERTY]: [value]\" string from the history."
  14865. (interactive "P")
  14866. (let* ((completion-ignore-case t)
  14867. (pv (or (and use-last org-last-set-property-value)
  14868. (org-completing-read
  14869. "Enter a \"[Property]: [value]\" pair: "
  14870. nil nil nil nil nil
  14871. org-last-set-property-value)))
  14872. prop val)
  14873. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14874. (setq prop (match-string 1 pv)
  14875. val (match-string 2 pv))
  14876. (org-set-property prop val))))
  14877. (defun org-set-property (property value)
  14878. "In the current entry, set PROPERTY to VALUE.
  14879. When called interactively, this will prompt for a property name, offering
  14880. completion on existing and default properties. And then it will prompt
  14881. for a value, offering completion either on allowed values (via an inherited
  14882. xxx_ALL property) or on existing values in other instances of this property
  14883. in the current file.
  14884. Throw an error when trying to set a property with an invalid name."
  14885. (interactive (list nil nil))
  14886. (let ((property (or property (org-read-property-name))))
  14887. ;; `org-entry-put' also makes the following check, but this one
  14888. ;; avoids polluting `org-last-set-property' and
  14889. ;; `org-last-set-property-value' needlessly.
  14890. (unless (org--valid-property-p property)
  14891. (user-error "Invalid property name: \"%s\"" property))
  14892. (let ((value (or value (org-read-property-value property)))
  14893. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14894. (setq org-last-set-property property)
  14895. (setq org-last-set-property-value (concat property ": " value))
  14896. ;; Possibly postprocess the inserted value:
  14897. (when fn (setq value (funcall fn value)))
  14898. (unless (equal (org-entry-get nil property) value)
  14899. (org-entry-put nil property value)))))
  14900. (defun org-find-property (property &optional value)
  14901. "Find first entry in buffer that sets PROPERTY.
  14902. When optional argument VALUE is non-nil, only consider an entry
  14903. if it contains PROPERTY set to this value. If PROPERTY should be
  14904. explicitly set to nil, use string \"nil\" for VALUE.
  14905. Return position where the entry begins, or nil if there is no
  14906. such entry. If narrowing is in effect, only search the visible
  14907. part of the buffer."
  14908. (save-excursion
  14909. (goto-char (point-min))
  14910. (let ((case-fold-search t)
  14911. (re (org-re-property property nil (not value) value)))
  14912. (catch 'exit
  14913. (while (re-search-forward re nil t)
  14914. (when (if value (org-at-property-p)
  14915. (org-entry-get (point) property nil t))
  14916. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14917. (defun org-delete-property (property)
  14918. "In the current entry, delete PROPERTY."
  14919. (interactive
  14920. (let* ((completion-ignore-case t)
  14921. (cat (org-entry-get (point) "CATEGORY"))
  14922. (props0 (org-entry-properties nil 'standard))
  14923. (props (if cat props0
  14924. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14925. (prop (if (< 1 (length props))
  14926. (completing-read "Property: " props nil t)
  14927. (caar props))))
  14928. (list prop)))
  14929. (if (not property)
  14930. (message "No property to delete in this entry")
  14931. (org-entry-delete nil property)
  14932. (message "Property \"%s\" deleted" property)))
  14933. (defun org-delete-property-globally (property)
  14934. "Remove PROPERTY globally, from all entries.
  14935. This function ignores narrowing, if any."
  14936. (interactive
  14937. (let* ((completion-ignore-case t)
  14938. (prop (completing-read
  14939. "Globally remove property: "
  14940. (mapcar #'list (org-buffer-property-keys)))))
  14941. (list prop)))
  14942. (org-with-wide-buffer
  14943. (goto-char (point-min))
  14944. (let ((count 0)
  14945. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14946. (while (re-search-forward re nil t)
  14947. (when (org-entry-delete (point) property) (cl-incf count)))
  14948. (message "Property \"%s\" removed from %d entries" property count))))
  14949. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14950. (defun org-compute-property-at-point ()
  14951. "Compute the property at point.
  14952. This looks for an enclosing column format, extracts the operator and
  14953. then applies it to the property in the column format's scope."
  14954. (interactive)
  14955. (unless (org-at-property-p)
  14956. (user-error "Not at a property"))
  14957. (let ((prop (match-string-no-properties 2)))
  14958. (org-columns-get-format-and-top-level)
  14959. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14960. (user-error "No operator defined for property %s" prop))
  14961. (org-columns-compute prop)))
  14962. (defvar org-property-allowed-value-functions nil
  14963. "Hook for functions supplying allowed values for a specific property.
  14964. The functions must take a single argument, the name of the property, and
  14965. return a flat list of allowed values. If \":ETC\" is one of
  14966. the values, this means that these values are intended as defaults for
  14967. completion, but that other values should be allowed too.
  14968. The functions must return nil if they are not responsible for this
  14969. property.")
  14970. (defun org-property-get-allowed-values (pom property &optional table)
  14971. "Get allowed values for the property PROPERTY.
  14972. When TABLE is non-nil, return an alist that can directly be used for
  14973. completion."
  14974. (let (vals)
  14975. (cond
  14976. ((equal property "TODO")
  14977. (setq vals (org-with-point-at pom
  14978. (append org-todo-keywords-1 '("")))))
  14979. ((equal property "PRIORITY")
  14980. (let ((n org-lowest-priority))
  14981. (while (>= n org-highest-priority)
  14982. (push (char-to-string n) vals)
  14983. (setq n (1- n)))))
  14984. ((equal property "CATEGORY"))
  14985. ((member property org-special-properties))
  14986. ((setq vals (run-hook-with-args-until-success
  14987. 'org-property-allowed-value-functions property)))
  14988. (t
  14989. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14990. (when (and vals (string-match "\\S-" vals))
  14991. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14992. (setq vals (mapcar (lambda (x)
  14993. (cond ((stringp x) x)
  14994. ((numberp x) (number-to-string x))
  14995. ((symbolp x) (symbol-name x))
  14996. (t "???")))
  14997. vals)))))
  14998. (when (member ":ETC" vals)
  14999. (setq vals (remove ":ETC" vals))
  15000. (org-add-props (car vals) '(org-unrestricted t)))
  15001. (if table (mapcar 'list vals) vals)))
  15002. (defun org-property-previous-allowed-value (&optional _previous)
  15003. "Switch to the next allowed value for this property."
  15004. (interactive)
  15005. (org-property-next-allowed-value t))
  15006. (defun org-property-next-allowed-value (&optional previous)
  15007. "Switch to the next allowed value for this property."
  15008. (interactive)
  15009. (unless (org-at-property-p)
  15010. (user-error "Not at a property"))
  15011. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15012. (key (match-string 2))
  15013. (value (match-string 3))
  15014. (allowed (or (org-property-get-allowed-values (point) key)
  15015. (and (member value '("[ ]" "[-]" "[X]"))
  15016. '("[ ]" "[X]"))))
  15017. (heading (save-match-data (nth 4 (org-heading-components))))
  15018. nval)
  15019. (unless allowed
  15020. (user-error "Allowed values for this property have not been defined"))
  15021. (when previous (setq allowed (reverse allowed)))
  15022. (when (member value allowed)
  15023. (setq nval (car (cdr (member value allowed)))))
  15024. (setq nval (or nval (car allowed)))
  15025. (when (equal nval value)
  15026. (user-error "Only one allowed value for this property"))
  15027. (org-at-property-p)
  15028. (replace-match (concat " :" key ": " nval) t t)
  15029. (org-indent-line)
  15030. (beginning-of-line 1)
  15031. (skip-chars-forward " \t")
  15032. (when (equal prop org-effort-property)
  15033. (org-refresh-property
  15034. '((effort . identity)
  15035. (effort-minutes . org-duration-to-minutes))
  15036. nval)
  15037. (when (string= org-clock-current-task heading)
  15038. (setq org-clock-effort nval)
  15039. (org-clock-update-mode-line)))
  15040. (run-hook-with-args 'org-property-changed-functions key nval)))
  15041. (defun org-find-olp (path &optional this-buffer)
  15042. "Return a marker pointing to the entry at outline path OLP.
  15043. If anything goes wrong, throw an error.
  15044. You can wrap this call to catch the error like this:
  15045. (condition-case msg
  15046. (org-mobile-locate-entry (match-string 4))
  15047. (error (nth 1 msg)))
  15048. The return value will then be either a string with the error message,
  15049. or a marker if everything is OK.
  15050. If THIS-BUFFER is set, the outline path does not contain a file,
  15051. only headings."
  15052. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15053. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15054. (level 1)
  15055. (lmin 1)
  15056. (lmax 1)
  15057. end found flevel)
  15058. (unless buffer (error "File not found :%s" file))
  15059. (with-current-buffer buffer
  15060. (unless (derived-mode-p 'org-mode)
  15061. (error "Buffer %s needs to be in Org mode" buffer))
  15062. (org-with-wide-buffer
  15063. (goto-char (point-min))
  15064. (dolist (heading path)
  15065. (let ((re (format org-complex-heading-regexp-format
  15066. (regexp-quote heading)))
  15067. (cnt 0))
  15068. (while (re-search-forward re end t)
  15069. (setq level (- (match-end 1) (match-beginning 1)))
  15070. (when (and (>= level lmin) (<= level lmax))
  15071. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15072. (when (= cnt 0)
  15073. (error "Heading not found on level %d: %s" lmax heading))
  15074. (when (> cnt 1)
  15075. (error "Heading not unique on level %d: %s" lmax heading))
  15076. (goto-char found)
  15077. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15078. (setq end (save-excursion (org-end-of-subtree t t)))))
  15079. (when (org-at-heading-p)
  15080. (point-marker))))))
  15081. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15082. "Find node HEADING in BUFFER.
  15083. Return a marker to the heading if it was found, or nil if not.
  15084. If POS-ONLY is set, return just the position instead of a marker.
  15085. The heading text must match exact, but it may have a TODO keyword,
  15086. a priority cookie and tags in the standard locations."
  15087. (with-current-buffer (or buffer (current-buffer))
  15088. (org-with-wide-buffer
  15089. (goto-char (point-min))
  15090. (let (case-fold-search)
  15091. (when (re-search-forward
  15092. (format org-complex-heading-regexp-format
  15093. (regexp-quote heading)) nil t)
  15094. (if pos-only
  15095. (match-beginning 0)
  15096. (move-marker (make-marker) (match-beginning 0))))))))
  15097. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15098. "Find Org node headline HEADING in all .org files in directory DIR.
  15099. When the target headline is found, return a marker to this location."
  15100. (let ((files (directory-files (or dir default-directory)
  15101. t "\\`[^.#].*\\.org\\'"))
  15102. visiting m buffer)
  15103. (catch 'found
  15104. (dolist (file files)
  15105. (message "trying %s" file)
  15106. (setq visiting (org-find-base-buffer-visiting file))
  15107. (setq buffer (or visiting (find-file-noselect file)))
  15108. (setq m (org-find-exact-headline-in-buffer
  15109. heading buffer))
  15110. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15111. (and m (throw 'found m))))))
  15112. (defun org-find-entry-with-id (ident)
  15113. "Locate the entry that contains the ID property with exact value IDENT.
  15114. IDENT can be a string, a symbol or a number, this function will search for
  15115. the string representation of it.
  15116. Return the position where this entry starts, or nil if there is no such entry."
  15117. (interactive "sID: ")
  15118. (let ((id (cond
  15119. ((stringp ident) ident)
  15120. ((symbolp ident) (symbol-name ident))
  15121. ((numberp ident) (number-to-string ident))
  15122. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15123. (org-with-wide-buffer (org-find-property "ID" id))))
  15124. ;;;; Timestamps
  15125. (defvar org-last-changed-timestamp nil)
  15126. (defvar org-last-inserted-timestamp nil
  15127. "The last time stamp inserted with `org-insert-time-stamp'.")
  15128. (defun org-time-stamp (arg &optional inactive)
  15129. "Prompt for a date/time and insert a time stamp.
  15130. If the user specifies a time like HH:MM or if this command is
  15131. called with at least one prefix argument, the time stamp contains
  15132. the date and the time. Otherwise, only the date is included.
  15133. All parts of a date not specified by the user are filled in from
  15134. the timestamp at point, if any, or the current date/time
  15135. otherwise.
  15136. If there is already a timestamp at the cursor, it is replaced.
  15137. With two universal prefix arguments, insert an active timestamp
  15138. with the current time without prompting the user.
  15139. When called from lisp, the timestamp is inactive if INACTIVE is
  15140. non-nil."
  15141. (interactive "P")
  15142. (let* ((ts (cond
  15143. ((org-at-date-range-p t)
  15144. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15145. ((org-at-timestamp-p 'lax) (match-string 0))))
  15146. ;; Default time is either the timestamp at point or today.
  15147. ;; When entering a range, only the range start is considered.
  15148. (default-time (if (not ts) (current-time)
  15149. (apply #'encode-time (org-parse-time-string ts))))
  15150. (default-input (and ts (org-get-compact-tod ts)))
  15151. (repeater (and ts
  15152. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15153. (match-string 0 ts)))
  15154. org-time-was-given
  15155. org-end-time-was-given
  15156. (time
  15157. (and (if (equal arg '(16)) (current-time)
  15158. ;; Preserve `this-command' and `last-command'.
  15159. (let ((this-command this-command)
  15160. (last-command last-command))
  15161. (org-read-date
  15162. arg 'totime nil nil default-time default-input
  15163. inactive))))))
  15164. (cond
  15165. ((and ts
  15166. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15167. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15168. (insert "--")
  15169. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15170. (ts
  15171. ;; Make sure we're on a timestamp. When in the middle of a date
  15172. ;; range, move arbitrarily to range end.
  15173. (unless (org-at-timestamp-p 'lax)
  15174. (skip-chars-forward "-")
  15175. (org-at-timestamp-p 'lax))
  15176. (replace-match "")
  15177. (setq org-last-changed-timestamp
  15178. (org-insert-time-stamp
  15179. time (or org-time-was-given arg)
  15180. inactive nil nil (list org-end-time-was-given)))
  15181. (when repeater
  15182. (backward-char)
  15183. (insert " " repeater)
  15184. (setq org-last-changed-timestamp
  15185. (concat (substring org-last-inserted-timestamp 0 -1)
  15186. " " repeater ">")))
  15187. (message "Timestamp updated"))
  15188. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15189. (t (org-insert-time-stamp
  15190. time (or org-time-was-given arg) inactive nil nil
  15191. (list org-end-time-was-given))))))
  15192. ;; FIXME: can we use this for something else, like computing time differences?
  15193. (defun org-get-compact-tod (s)
  15194. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15195. (let* ((t1 (match-string 1 s))
  15196. (h1 (string-to-number (match-string 2 s)))
  15197. (m1 (string-to-number (match-string 3 s)))
  15198. (t2 (and (match-end 4) (match-string 5 s)))
  15199. (h2 (and t2 (string-to-number (match-string 6 s))))
  15200. (m2 (and t2 (string-to-number (match-string 7 s))))
  15201. dh dm)
  15202. (if (not t2)
  15203. t1
  15204. (setq dh (- h2 h1) dm (- m2 m1))
  15205. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15206. (concat t1 "+" (number-to-string dh)
  15207. (and (/= 0 dm) (format ":%02d" dm)))))))
  15208. (defun org-time-stamp-inactive (&optional arg)
  15209. "Insert an inactive time stamp.
  15210. An inactive time stamp is enclosed in square brackets instead of angle
  15211. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15212. does not link to the calendar and cannot be changed with the S-cursor keys.
  15213. So these are more for recording a certain time/date."
  15214. (interactive "P")
  15215. (org-time-stamp arg 'inactive))
  15216. (defvar org-date-ovl (make-overlay 1 1))
  15217. (overlay-put org-date-ovl 'face 'org-date-selected)
  15218. (delete-overlay org-date-ovl)
  15219. (defvar org-ans1) ; dynamically scoped parameter
  15220. (defvar org-ans2) ; dynamically scoped parameter
  15221. (defvar org-plain-time-of-day-regexp) ; defined below
  15222. (defvar org-overriding-default-time nil) ; dynamically scoped
  15223. (defvar org-read-date-overlay nil)
  15224. (defvar org-dcst nil) ; dynamically scoped
  15225. (defvar org-read-date-history nil)
  15226. (defvar org-read-date-final-answer nil)
  15227. (defvar org-read-date-analyze-futurep nil)
  15228. (defvar org-read-date-analyze-forced-year nil)
  15229. (defvar org-read-date-inactive)
  15230. (defvar org-read-date-minibuffer-local-map
  15231. (let* ((map (make-sparse-keymap)))
  15232. (set-keymap-parent map minibuffer-local-map)
  15233. (org-defkey map (kbd ".")
  15234. (lambda () (interactive)
  15235. ;; Are we at the beginning of the prompt?
  15236. (if (looking-back "^[^:]+: "
  15237. (let ((inhibit-field-text-motion t))
  15238. (line-beginning-position)))
  15239. (org-eval-in-calendar '(calendar-goto-today))
  15240. (insert "."))))
  15241. (org-defkey map (kbd "C-.")
  15242. (lambda () (interactive)
  15243. (org-eval-in-calendar '(calendar-goto-today))))
  15244. (org-defkey map [(meta shift left)]
  15245. (lambda () (interactive)
  15246. (org-eval-in-calendar '(calendar-backward-month 1))))
  15247. (org-defkey map [(meta shift right)]
  15248. (lambda () (interactive)
  15249. (org-eval-in-calendar '(calendar-forward-month 1))))
  15250. (org-defkey map [(meta shift up)]
  15251. (lambda () (interactive)
  15252. (org-eval-in-calendar '(calendar-backward-year 1))))
  15253. (org-defkey map [(meta shift down)]
  15254. (lambda () (interactive)
  15255. (org-eval-in-calendar '(calendar-forward-year 1))))
  15256. (org-defkey map [?\e (shift left)]
  15257. (lambda () (interactive)
  15258. (org-eval-in-calendar '(calendar-backward-month 1))))
  15259. (org-defkey map [?\e (shift right)]
  15260. (lambda () (interactive)
  15261. (org-eval-in-calendar '(calendar-forward-month 1))))
  15262. (org-defkey map [?\e (shift up)]
  15263. (lambda () (interactive)
  15264. (org-eval-in-calendar '(calendar-backward-year 1))))
  15265. (org-defkey map [?\e (shift down)]
  15266. (lambda () (interactive)
  15267. (org-eval-in-calendar '(calendar-forward-year 1))))
  15268. (org-defkey map [(shift up)]
  15269. (lambda () (interactive)
  15270. (org-eval-in-calendar '(calendar-backward-week 1))))
  15271. (org-defkey map [(shift down)]
  15272. (lambda () (interactive)
  15273. (org-eval-in-calendar '(calendar-forward-week 1))))
  15274. (org-defkey map [(shift left)]
  15275. (lambda () (interactive)
  15276. (org-eval-in-calendar '(calendar-backward-day 1))))
  15277. (org-defkey map [(shift right)]
  15278. (lambda () (interactive)
  15279. (org-eval-in-calendar '(calendar-forward-day 1))))
  15280. (org-defkey map "!"
  15281. (lambda () (interactive)
  15282. (org-eval-in-calendar '(diary-view-entries))
  15283. (message "")))
  15284. (org-defkey map ">"
  15285. (lambda () (interactive)
  15286. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15287. (org-defkey map "<"
  15288. (lambda () (interactive)
  15289. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15290. (org-defkey map "\C-v"
  15291. (lambda () (interactive)
  15292. (org-eval-in-calendar
  15293. '(calendar-scroll-left-three-months 1))))
  15294. (org-defkey map "\M-v"
  15295. (lambda () (interactive)
  15296. (org-eval-in-calendar
  15297. '(calendar-scroll-right-three-months 1))))
  15298. map)
  15299. "Keymap for minibuffer commands when using `org-read-date'.")
  15300. (defvar org-def)
  15301. (defvar org-defdecode)
  15302. (defvar org-with-time)
  15303. (defvar calendar-setup) ; Dynamically scoped.
  15304. (defun org-read-date (&optional with-time to-time from-string prompt
  15305. default-time default-input inactive)
  15306. "Read a date, possibly a time, and make things smooth for the user.
  15307. The prompt will suggest to enter an ISO date, but you can also enter anything
  15308. which will at least partially be understood by `parse-time-string'.
  15309. Unrecognized parts of the date will default to the current day, month, year,
  15310. hour and minute. If this command is called to replace a timestamp at point,
  15311. or to enter the second timestamp of a range, the default time is taken
  15312. from the existing stamp. Furthermore, the command prefers the future,
  15313. so if you are giving a date where the year is not given, and the day-month
  15314. combination is already past in the current year, it will assume you
  15315. mean next year. For details, see the manual. A few examples:
  15316. 3-2-5 --> 2003-02-05
  15317. feb 15 --> currentyear-02-15
  15318. 2/15 --> currentyear-02-15
  15319. sep 12 9 --> 2009-09-12
  15320. 12:45 --> today 12:45
  15321. 22 sept 0:34 --> currentyear-09-22 0:34
  15322. 12 --> currentyear-currentmonth-12
  15323. Fri --> nearest Friday after today
  15324. -Tue --> last Tuesday
  15325. etc.
  15326. Furthermore you can specify a relative date by giving, as the *first* thing
  15327. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15328. change in days weeks, months, years.
  15329. With a single plus or minus, the date is relative to today. With a double
  15330. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15331. +4d --> four days from today
  15332. +4 --> same as above
  15333. +2w --> two weeks from today
  15334. ++5 --> five days from default date
  15335. The function understands only English month and weekday abbreviations.
  15336. While prompting, a calendar is popped up - you can also select the
  15337. date with the mouse (button 1). The calendar shows a period of three
  15338. months. To scroll it to other months, use the keys `>' and `<'.
  15339. If you don't like the calendar, turn it off with
  15340. (setq org-read-date-popup-calendar nil)
  15341. With optional argument TO-TIME, the date will immediately be converted
  15342. to an internal time.
  15343. With an optional argument WITH-TIME, the prompt will suggest to
  15344. also insert a time. Note that when WITH-TIME is not set, you can
  15345. still enter a time, and this function will inform the calling routine
  15346. about this change. The calling routine may then choose to change the
  15347. format used to insert the time stamp into the buffer to include the time.
  15348. With optional argument FROM-STRING, read from this string instead from
  15349. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15350. the time/date that is used for everything that is not specified by the
  15351. user."
  15352. (require 'parse-time)
  15353. (let* ((org-with-time with-time)
  15354. (org-time-stamp-rounding-minutes
  15355. (if (equal org-with-time '(16))
  15356. '(0 0)
  15357. org-time-stamp-rounding-minutes))
  15358. (org-dcst org-display-custom-times)
  15359. (ct (org-current-time))
  15360. (org-def (or org-overriding-default-time default-time ct))
  15361. (org-defdecode (decode-time org-def))
  15362. (cur-frame (selected-frame))
  15363. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15364. (calendar-setup
  15365. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15366. (calendar-move-hook nil)
  15367. (calendar-view-diary-initially-flag nil)
  15368. (calendar-view-holidays-initially-flag nil)
  15369. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15370. ;; Rationalize `org-def' and `org-defdecode', if required.
  15371. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15372. (setf (nth 2 org-defdecode) -1)
  15373. (setf (nth 1 org-defdecode) 59)
  15374. (setq org-def (apply #'encode-time org-defdecode))
  15375. (setq org-defdecode (decode-time org-def)))
  15376. (let* ((timestr (format-time-string
  15377. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15378. org-def))
  15379. (prompt (concat (if prompt (concat prompt " ") "")
  15380. (format "Date+time [%s]: " timestr))))
  15381. (cond
  15382. (from-string (setq ans from-string))
  15383. (org-read-date-popup-calendar
  15384. (save-excursion
  15385. (save-window-excursion
  15386. (calendar)
  15387. (when (eq calendar-setup 'calendar-only)
  15388. (setq cal-frame
  15389. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15390. (select-frame cal-frame))
  15391. (org-eval-in-calendar '(setq cursor-type nil) t)
  15392. (unwind-protect
  15393. (progn
  15394. (calendar-forward-day (- (time-to-days org-def)
  15395. (calendar-absolute-from-gregorian
  15396. (calendar-current-date))))
  15397. (org-eval-in-calendar nil t)
  15398. (let* ((old-map (current-local-map))
  15399. (map (copy-keymap calendar-mode-map))
  15400. (minibuffer-local-map
  15401. (copy-keymap org-read-date-minibuffer-local-map)))
  15402. (org-defkey map (kbd "RET") 'org-calendar-select)
  15403. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15404. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15405. (unwind-protect
  15406. (progn
  15407. (use-local-map map)
  15408. (setq org-read-date-inactive inactive)
  15409. (add-hook 'post-command-hook 'org-read-date-display)
  15410. (setq org-ans0
  15411. (read-string prompt
  15412. default-input
  15413. 'org-read-date-history
  15414. nil))
  15415. ;; org-ans0: from prompt
  15416. ;; org-ans1: from mouse click
  15417. ;; org-ans2: from calendar motion
  15418. (setq ans
  15419. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15420. (remove-hook 'post-command-hook 'org-read-date-display)
  15421. (use-local-map old-map)
  15422. (when org-read-date-overlay
  15423. (delete-overlay org-read-date-overlay)
  15424. (setq org-read-date-overlay nil)))))
  15425. (bury-buffer "*Calendar*")
  15426. (when cal-frame
  15427. (delete-frame cal-frame)
  15428. (select-frame-set-input-focus cur-frame))))))
  15429. (t ; Naked prompt only
  15430. (unwind-protect
  15431. (setq ans (read-string prompt default-input
  15432. 'org-read-date-history timestr))
  15433. (when org-read-date-overlay
  15434. (delete-overlay org-read-date-overlay)
  15435. (setq org-read-date-overlay nil))))))
  15436. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15437. (when org-read-date-analyze-forced-year
  15438. (message "Year was forced into %s"
  15439. (if org-read-date-force-compatible-dates
  15440. "compatible range (1970-2037)"
  15441. "range representable on this machine"))
  15442. (ding))
  15443. ;; One round trip to get rid of 34th of August and stuff like that....
  15444. (setq final (decode-time (apply 'encode-time final)))
  15445. (setq org-read-date-final-answer ans)
  15446. (if to-time
  15447. (apply 'encode-time final)
  15448. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15449. (format "%04d-%02d-%02d %02d:%02d"
  15450. (nth 5 final) (nth 4 final) (nth 3 final)
  15451. (nth 2 final) (nth 1 final))
  15452. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15453. (defun org-read-date-display ()
  15454. "Display the current date prompt interpretation in the minibuffer."
  15455. (when org-read-date-display-live
  15456. (when org-read-date-overlay
  15457. (delete-overlay org-read-date-overlay))
  15458. (when (minibufferp (current-buffer))
  15459. (save-excursion
  15460. (end-of-line 1)
  15461. (while (not (equal (buffer-substring
  15462. (max (point-min) (- (point) 4)) (point))
  15463. " "))
  15464. (insert " ")))
  15465. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15466. " " (or org-ans1 org-ans2)))
  15467. (org-end-time-was-given nil)
  15468. (f (org-read-date-analyze ans org-def org-defdecode))
  15469. (fmts (if org-dcst
  15470. org-time-stamp-custom-formats
  15471. org-time-stamp-formats))
  15472. (fmt (if (or org-with-time
  15473. (and (boundp 'org-time-was-given) org-time-was-given))
  15474. (cdr fmts)
  15475. (car fmts)))
  15476. (txt (format-time-string fmt (apply 'encode-time f)))
  15477. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15478. (txt (concat "=> " txt)))
  15479. (when (and org-end-time-was-given
  15480. (string-match org-plain-time-of-day-regexp txt))
  15481. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15482. org-end-time-was-given
  15483. (substring txt (match-end 0)))))
  15484. (when org-read-date-analyze-futurep
  15485. (setq txt (concat txt " (=>F)")))
  15486. (setq org-read-date-overlay
  15487. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15488. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15489. (defun org-read-date-analyze (ans def defdecode)
  15490. "Analyze the combined answer of the date prompt."
  15491. ;; FIXME: cleanup and comment
  15492. ;; Pass `current-time' result to `decode-time' (instead of calling
  15493. ;; without arguments) so that only `current-time' has to be
  15494. ;; overriden in tests.
  15495. (let ((org-def def)
  15496. (org-defdecode defdecode)
  15497. (nowdecode (decode-time (current-time)))
  15498. delta deltan deltaw deltadef year month day
  15499. hour minute second wday pm h2 m2 tl wday1
  15500. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15501. (setq org-read-date-analyze-futurep nil
  15502. org-read-date-analyze-forced-year nil)
  15503. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15504. (setq ans "+0"))
  15505. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15506. (setq ans (replace-match "" t t ans)
  15507. deltan (car delta)
  15508. deltaw (nth 1 delta)
  15509. deltadef (nth 2 delta)))
  15510. ;; Check if there is an iso week date in there. If yes, store the
  15511. ;; info and postpone interpreting it until the rest of the parsing
  15512. ;; is done.
  15513. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15514. (setq iso-year (when (match-end 1)
  15515. (org-small-year-to-year
  15516. (string-to-number (match-string 1 ans))))
  15517. iso-weekday (when (match-end 3)
  15518. (string-to-number (match-string 3 ans)))
  15519. iso-week (string-to-number (match-string 2 ans)))
  15520. (setq ans (replace-match "" t t ans)))
  15521. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15522. (when (string-match
  15523. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15524. (setq year (if (match-end 2)
  15525. (string-to-number (match-string 2 ans))
  15526. (progn (setq kill-year t)
  15527. (string-to-number (format-time-string "%Y"))))
  15528. month (string-to-number (match-string 3 ans))
  15529. day (string-to-number (match-string 4 ans)))
  15530. (setq year (org-small-year-to-year year))
  15531. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15532. t nil ans)))
  15533. ;; Help matching dotted european dates
  15534. (when (string-match
  15535. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15536. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15537. (setq kill-year t)
  15538. (string-to-number (format-time-string "%Y")))
  15539. day (string-to-number (match-string 1 ans))
  15540. month (string-to-number (match-string 2 ans))
  15541. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15542. t nil ans)))
  15543. ;; Help matching american dates, like 5/30 or 5/30/7
  15544. (when (string-match
  15545. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15546. (setq year (if (match-end 4)
  15547. (string-to-number (match-string 4 ans))
  15548. (progn (setq kill-year t)
  15549. (string-to-number (format-time-string "%Y"))))
  15550. month (string-to-number (match-string 1 ans))
  15551. day (string-to-number (match-string 2 ans)))
  15552. (setq year (org-small-year-to-year year))
  15553. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15554. t nil ans)))
  15555. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15556. ;; If there is a time with am/pm, and *no* time without it, we convert
  15557. ;; so that matching will be successful.
  15558. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15559. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15560. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15561. (setq hour (string-to-number (match-string 1 ans))
  15562. minute (if (match-end 3)
  15563. (string-to-number (match-string 3 ans))
  15564. 0)
  15565. pm (equal ?p
  15566. (string-to-char (downcase (match-string 4 ans)))))
  15567. (if (and (= hour 12) (not pm))
  15568. (setq hour 0)
  15569. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15570. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15571. t t ans))))
  15572. ;; Check if a time range is given as a duration
  15573. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15574. (setq hour (string-to-number (match-string 1 ans))
  15575. h2 (+ hour (string-to-number (match-string 3 ans)))
  15576. minute (string-to-number (match-string 2 ans))
  15577. m2 (+ minute (if (match-end 5) (string-to-number
  15578. (match-string 5 ans))0)))
  15579. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15580. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15581. t t ans)))
  15582. ;; Check if there is a time range
  15583. (when (boundp 'org-end-time-was-given)
  15584. (setq org-time-was-given nil)
  15585. (when (and (string-match org-plain-time-of-day-regexp ans)
  15586. (match-end 8))
  15587. (setq org-end-time-was-given (match-string 8 ans))
  15588. (setq ans (concat (substring ans 0 (match-beginning 7))
  15589. (substring ans (match-end 7))))))
  15590. (setq tl (parse-time-string ans)
  15591. day (or (nth 3 tl) (nth 3 org-defdecode))
  15592. month
  15593. (cond ((nth 4 tl))
  15594. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15595. ;; Day was specified. Make sure DAY+MONTH
  15596. ;; combination happens in the future.
  15597. ((nth 3 tl)
  15598. (setq futurep t)
  15599. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15600. (nth 4 nowdecode)))
  15601. (t (nth 4 org-defdecode)))
  15602. year
  15603. (cond ((and (not kill-year) (nth 5 tl)))
  15604. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15605. ;; Month was guessed in the future and is at least
  15606. ;; equal to NOWDECODE's. Fix year accordingly.
  15607. (futurep
  15608. (if (or (> month (nth 4 nowdecode))
  15609. (>= day (nth 3 nowdecode)))
  15610. (nth 5 nowdecode)
  15611. (1+ (nth 5 nowdecode))))
  15612. ;; Month was specified. Make sure MONTH+YEAR
  15613. ;; combination happens in the future.
  15614. ((nth 4 tl)
  15615. (setq futurep t)
  15616. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15617. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15618. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15619. (t (nth 5 nowdecode))))
  15620. (t (nth 5 org-defdecode)))
  15621. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15622. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15623. second (or (nth 0 tl) 0)
  15624. wday (nth 6 tl))
  15625. (when (and (eq org-read-date-prefer-future 'time)
  15626. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15627. (equal day (nth 3 nowdecode))
  15628. (equal month (nth 4 nowdecode))
  15629. (equal year (nth 5 nowdecode))
  15630. (nth 2 tl)
  15631. (or (< (nth 2 tl) (nth 2 nowdecode))
  15632. (and (= (nth 2 tl) (nth 2 nowdecode))
  15633. (nth 1 tl)
  15634. (< (nth 1 tl) (nth 1 nowdecode)))))
  15635. (setq day (1+ day)
  15636. futurep t))
  15637. ;; Special date definitions below
  15638. (cond
  15639. (iso-week
  15640. ;; There was an iso week
  15641. (require 'cal-iso)
  15642. (setq futurep nil)
  15643. (setq year (or iso-year year)
  15644. day (or iso-weekday wday 1)
  15645. wday nil ; to make sure that the trigger below does not match
  15646. iso-date (calendar-gregorian-from-absolute
  15647. (calendar-iso-to-absolute
  15648. (list iso-week day year))))
  15649. ; FIXME: Should we also push ISO weeks into the future?
  15650. ; (when (and org-read-date-prefer-future
  15651. ; (not iso-year)
  15652. ; (< (calendar-absolute-from-gregorian iso-date)
  15653. ; (time-to-days (current-time))))
  15654. ; (setq year (1+ year)
  15655. ; iso-date (calendar-gregorian-from-absolute
  15656. ; (calendar-iso-to-absolute
  15657. ; (list iso-week day year)))))
  15658. (setq month (car iso-date)
  15659. year (nth 2 iso-date)
  15660. day (nth 1 iso-date)))
  15661. (deltan
  15662. (setq futurep nil)
  15663. (unless deltadef
  15664. ;; Pass `current-time' result to `decode-time' (instead of
  15665. ;; calling without arguments) so that only `current-time' has
  15666. ;; to be overriden in tests.
  15667. (let ((now (decode-time (current-time))))
  15668. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15669. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15670. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15671. ((equal deltaw "m") (setq month (+ month deltan)))
  15672. ((equal deltaw "y") (setq year (+ year deltan)))))
  15673. ((and wday (not (nth 3 tl)))
  15674. ;; Weekday was given, but no day, so pick that day in the week
  15675. ;; on or after the derived date.
  15676. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15677. (unless (equal wday wday1)
  15678. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15679. (when (and (boundp 'org-time-was-given)
  15680. (nth 2 tl))
  15681. (setq org-time-was-given t))
  15682. (when (< year 100) (setq year (+ 2000 year)))
  15683. ;; Check of the date is representable
  15684. (if org-read-date-force-compatible-dates
  15685. (progn
  15686. (when (< year 1970)
  15687. (setq year 1970 org-read-date-analyze-forced-year t))
  15688. (when (> year 2037)
  15689. (setq year 2037 org-read-date-analyze-forced-year t)))
  15690. (condition-case nil
  15691. (ignore (encode-time second minute hour day month year))
  15692. (error
  15693. (setq year (nth 5 org-defdecode))
  15694. (setq org-read-date-analyze-forced-year t))))
  15695. (setq org-read-date-analyze-futurep futurep)
  15696. (list second minute hour day month year)))
  15697. (defvar parse-time-weekdays)
  15698. (defun org-read-date-get-relative (s today default)
  15699. "Check string S for special relative date string.
  15700. TODAY and DEFAULT are internal times, for today and for a default.
  15701. Return shift list (N what def-flag)
  15702. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15703. N is the number of WHATs to shift.
  15704. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15705. the DEFAULT date rather than TODAY."
  15706. (require 'parse-time)
  15707. (when (and
  15708. (string-match
  15709. (concat
  15710. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15711. "\\([0-9]+\\)?"
  15712. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15713. "\\([ \t]\\|$\\)") s)
  15714. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15715. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15716. (string-to-char (substring (match-string 1 s) -1))
  15717. ?+))
  15718. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15719. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15720. (what (if (match-end 3) (match-string 3 s) "d"))
  15721. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15722. (date (if rel default today))
  15723. (wday (nth 6 (decode-time date)))
  15724. delta)
  15725. (if wday1
  15726. (progn
  15727. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15728. (when (= delta 0) (setq delta 7))
  15729. (when (= dir ?-)
  15730. (setq delta (- delta 7))
  15731. (when (= delta 0) (setq delta -7)))
  15732. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15733. (list delta "d" rel))
  15734. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15735. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15736. "Turn a user-specified date into the internal representation.
  15737. The internal representation needed by the calendar is (month day year).
  15738. This is a wrapper to handle the brain-dead convention in calendar that
  15739. user function argument order change dependent on argument order."
  15740. (pcase calendar-date-style
  15741. (`american (list arg1 arg2 arg3))
  15742. (`european (list arg2 arg1 arg3))
  15743. (`iso (list arg2 arg3 arg1))))
  15744. (defun org-eval-in-calendar (form &optional keepdate)
  15745. "Eval FORM in the calendar window and return to current window.
  15746. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15747. (let ((sf (selected-frame))
  15748. (sw (selected-window)))
  15749. (select-window (get-buffer-window "*Calendar*" t))
  15750. (eval form)
  15751. (when (and (not keepdate) (calendar-cursor-to-date))
  15752. (let* ((date (calendar-cursor-to-date))
  15753. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15754. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15755. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15756. (select-window sw)
  15757. (select-frame-set-input-focus sf)))
  15758. (defun org-calendar-select ()
  15759. "Return to `org-read-date' with the date currently selected.
  15760. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15761. (interactive)
  15762. (when (calendar-cursor-to-date)
  15763. (let* ((date (calendar-cursor-to-date))
  15764. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15765. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15766. (when (active-minibuffer-window) (exit-minibuffer))))
  15767. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15768. "Insert a date stamp for the date given by the internal TIME.
  15769. See `format-time-string' for the format of TIME.
  15770. WITH-HM means use the stamp format that includes the time of the day.
  15771. INACTIVE means use square brackets instead of angular ones, so that the
  15772. stamp will not contribute to the agenda.
  15773. PRE and POST are optional strings to be inserted before and after the
  15774. stamp.
  15775. The command returns the inserted time stamp."
  15776. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15777. stamp)
  15778. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15779. (insert-before-markers (or pre ""))
  15780. (when (listp extra)
  15781. (setq extra (car extra))
  15782. (if (and (stringp extra)
  15783. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15784. (setq extra (format "-%02d:%02d"
  15785. (string-to-number (match-string 1 extra))
  15786. (string-to-number (match-string 2 extra))))
  15787. (setq extra nil)))
  15788. (when extra
  15789. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15790. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15791. (insert-before-markers (or post ""))
  15792. (setq org-last-inserted-timestamp stamp)))
  15793. (defun org-toggle-time-stamp-overlays ()
  15794. "Toggle the use of custom time stamp formats."
  15795. (interactive)
  15796. (setq org-display-custom-times (not org-display-custom-times))
  15797. (unless org-display-custom-times
  15798. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15799. (while (setq p (next-single-property-change p 'display))
  15800. (when (and (get-text-property p 'display)
  15801. (eq (get-text-property p 'face) 'org-date))
  15802. (remove-text-properties
  15803. p (setq p (next-single-property-change p 'display))
  15804. '(display t))))
  15805. (set-buffer-modified-p bmp)))
  15806. (org-restart-font-lock)
  15807. (setq org-table-may-need-update t)
  15808. (if org-display-custom-times
  15809. (message "Time stamps are overlaid with custom format")
  15810. (message "Time stamp overlays removed")))
  15811. (defun org-display-custom-time (beg end)
  15812. "Overlay modified time stamp format over timestamp between BEG and END."
  15813. (let* ((ts (buffer-substring beg end))
  15814. t1 w1 with-hm tf time str w2 (off 0))
  15815. (save-match-data
  15816. (setq t1 (org-parse-time-string ts t))
  15817. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15818. (setq off (- (match-end 0) (match-beginning 0)))))
  15819. (setq end (- end off))
  15820. (setq w1 (- end beg)
  15821. with-hm (and (nth 1 t1) (nth 2 t1))
  15822. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15823. time (org-fix-decoded-time t1)
  15824. str (org-add-props
  15825. (format-time-string
  15826. (substring tf 1 -1) (apply 'encode-time time))
  15827. nil 'mouse-face 'highlight)
  15828. w2 (length str))
  15829. (unless (= w2 w1)
  15830. (add-text-properties (1+ beg) (+ 2 beg)
  15831. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15832. (put-text-property beg end 'display str)))
  15833. (defun org-fix-decoded-time (time)
  15834. "Set 0 instead of nil for the first 6 elements of time.
  15835. Don't touch the rest."
  15836. (let ((n 0))
  15837. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15838. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15839. "Difference between TIMESTAMP-STRING and now in days.
  15840. If SECONDS is non-nil, return the difference in seconds."
  15841. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15842. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15843. (funcall fdiff (current-time)))))
  15844. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15845. "Is the time in TIMESTAMP-STRING close to the current date?"
  15846. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15847. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15848. (not (org-entry-is-done-p))))
  15849. (defun org-get-wdays (ts &optional delay zero-delay)
  15850. "Get the deadline lead time appropriate for timestring TS.
  15851. When DELAY is non-nil, get the delay time for scheduled items
  15852. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15853. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15854. don't try to find the delay cookie in the scheduled timestamp."
  15855. (let ((tv (if delay org-scheduled-delay-days
  15856. org-deadline-warning-days)))
  15857. (cond
  15858. ((or (and delay (< tv 0))
  15859. (and delay zero-delay (<= tv 0))
  15860. (and (not delay) (<= tv 0)))
  15861. ;; Enforce this value no matter what
  15862. (- tv))
  15863. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15864. ;; lead time is specified.
  15865. (floor (* (string-to-number (match-string 1 ts))
  15866. (cdr (assoc (match-string 2 ts)
  15867. '(("d" . 1) ("w" . 7)
  15868. ("m" . 30.4) ("y" . 365.25)
  15869. ("h" . 0.041667)))))))
  15870. ;; go for the default.
  15871. (t tv))))
  15872. (defun org-calendar-select-mouse (ev)
  15873. "Return to `org-read-date' with the date currently selected.
  15874. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15875. (interactive "e")
  15876. (mouse-set-point ev)
  15877. (when (calendar-cursor-to-date)
  15878. (let* ((date (calendar-cursor-to-date))
  15879. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15880. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15881. (when (active-minibuffer-window) (exit-minibuffer))))
  15882. (defun org-check-deadlines (ndays)
  15883. "Check if there are any deadlines due or past due.
  15884. A deadline is considered due if it happens within `org-deadline-warning-days'
  15885. days from today's date. If the deadline appears in an entry marked DONE,
  15886. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15887. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15888. are shown."
  15889. (interactive "P")
  15890. (let* ((org-warn-days
  15891. (cond
  15892. ((equal ndays '(4)) 100000)
  15893. (ndays (prefix-numeric-value ndays))
  15894. (t (abs org-deadline-warning-days))))
  15895. (case-fold-search nil)
  15896. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15897. (callback
  15898. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15899. (message "%d deadlines past-due or due within %d days"
  15900. (org-occur regexp nil callback)
  15901. org-warn-days)))
  15902. (defsubst org-re-timestamp (type)
  15903. "Return a regexp for timestamp TYPE.
  15904. Allowed values for TYPE are:
  15905. all: all timestamps
  15906. active: only active timestamps (<...>)
  15907. inactive: only inactive timestamps ([...])
  15908. scheduled: only scheduled timestamps
  15909. deadline: only deadline timestamps
  15910. closed: only closed time-stamps
  15911. When TYPE is nil, fall back on returning a regexp that matches
  15912. both scheduled and deadline timestamps."
  15913. (cl-case type
  15914. (all org-ts-regexp-both)
  15915. (active org-ts-regexp)
  15916. (inactive org-ts-regexp-inactive)
  15917. (scheduled org-scheduled-time-regexp)
  15918. (deadline org-deadline-time-regexp)
  15919. (closed org-closed-time-regexp)
  15920. (otherwise
  15921. (concat "\\<"
  15922. (regexp-opt (list org-deadline-string org-scheduled-string))
  15923. " *<\\([^>]+\\)>"))))
  15924. (defun org-check-before-date (d)
  15925. "Check if there are deadlines or scheduled entries before date D."
  15926. (interactive (list (org-read-date)))
  15927. (let* ((case-fold-search nil)
  15928. (regexp (org-re-timestamp org-ts-type))
  15929. (ts-type org-ts-type)
  15930. (callback
  15931. (lambda ()
  15932. (let ((match (match-string 1)))
  15933. (and (if (memq ts-type '(active inactive all))
  15934. (eq (org-element-type (save-excursion
  15935. (backward-char)
  15936. (org-element-context)))
  15937. 'timestamp)
  15938. (org-at-planning-p))
  15939. (time-less-p
  15940. (org-time-string-to-time match)
  15941. (org-time-string-to-time d)))))))
  15942. (message "%d entries before %s"
  15943. (org-occur regexp nil callback)
  15944. d)))
  15945. (defun org-check-after-date (d)
  15946. "Check if there are deadlines or scheduled entries after date D."
  15947. (interactive (list (org-read-date)))
  15948. (let* ((case-fold-search nil)
  15949. (regexp (org-re-timestamp org-ts-type))
  15950. (ts-type org-ts-type)
  15951. (callback
  15952. (lambda ()
  15953. (let ((match (match-string 1)))
  15954. (and (if (memq ts-type '(active inactive all))
  15955. (eq (org-element-type (save-excursion
  15956. (backward-char)
  15957. (org-element-context)))
  15958. 'timestamp)
  15959. (org-at-planning-p))
  15960. (not (time-less-p
  15961. (org-time-string-to-time match)
  15962. (org-time-string-to-time d))))))))
  15963. (message "%d entries after %s"
  15964. (org-occur regexp nil callback)
  15965. d)))
  15966. (defun org-check-dates-range (start-date end-date)
  15967. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15968. (interactive (list (org-read-date nil nil nil "Range starts")
  15969. (org-read-date nil nil nil "Range end")))
  15970. (let ((case-fold-search nil)
  15971. (regexp (org-re-timestamp org-ts-type))
  15972. (callback
  15973. (let ((type org-ts-type))
  15974. (lambda ()
  15975. (let ((match (match-string 1)))
  15976. (and
  15977. (if (memq type '(active inactive all))
  15978. (eq (org-element-type (save-excursion
  15979. (backward-char)
  15980. (org-element-context)))
  15981. 'timestamp)
  15982. (org-at-planning-p))
  15983. (not (time-less-p
  15984. (org-time-string-to-time match)
  15985. (org-time-string-to-time start-date)))
  15986. (time-less-p
  15987. (org-time-string-to-time match)
  15988. (org-time-string-to-time end-date))))))))
  15989. (message "%d entries between %s and %s"
  15990. (org-occur regexp nil callback) start-date end-date)))
  15991. (defun org-evaluate-time-range (&optional to-buffer)
  15992. "Evaluate a time range by computing the difference between start and end.
  15993. Normally the result is just printed in the echo area, but with prefix arg
  15994. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15995. If the time range is actually in a table, the result is inserted into the
  15996. next column.
  15997. For time difference computation, a year is assumed to be exactly 365
  15998. days in order to avoid rounding problems."
  15999. (interactive "P")
  16000. (or
  16001. (org-clock-update-time-maybe)
  16002. (save-excursion
  16003. (unless (org-at-date-range-p t)
  16004. (goto-char (point-at-bol))
  16005. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16006. (unless (org-at-date-range-p t)
  16007. (user-error "Not at a time-stamp range, and none found in current line")))
  16008. (let* ((ts1 (match-string 1))
  16009. (ts2 (match-string 2))
  16010. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16011. (match-end (match-end 0))
  16012. (time1 (org-time-string-to-time ts1))
  16013. (time2 (org-time-string-to-time ts2))
  16014. (t1 (float-time time1))
  16015. (t2 (float-time time2))
  16016. (diff (abs (- t2 t1)))
  16017. (negative (< (- t2 t1) 0))
  16018. ;; (ys (floor (* 365 24 60 60)))
  16019. (ds (* 24 60 60))
  16020. (hs (* 60 60))
  16021. (fy "%dy %dd %02d:%02d")
  16022. (fy1 "%dy %dd")
  16023. (fd "%dd %02d:%02d")
  16024. (fd1 "%dd")
  16025. (fh "%02d:%02d")
  16026. y d h m align)
  16027. (if havetime
  16028. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16029. y 0
  16030. d (floor (/ diff ds)) diff (mod diff ds)
  16031. h (floor (/ diff hs)) diff (mod diff hs)
  16032. m (floor (/ diff 60)))
  16033. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16034. y 0
  16035. d (floor (+ (/ diff ds) 0.5))
  16036. h 0 m 0))
  16037. (if (not to-buffer)
  16038. (message "%s" (org-make-tdiff-string y d h m))
  16039. (if (org-at-table-p)
  16040. (progn
  16041. (goto-char match-end)
  16042. (setq align t)
  16043. (and (looking-at " *|") (goto-char (match-end 0))))
  16044. (goto-char match-end))
  16045. (when (looking-at
  16046. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16047. (replace-match ""))
  16048. (when negative (insert " -"))
  16049. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16050. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16051. (insert " " (format fh h m))))
  16052. (when align (org-table-align))
  16053. (message "Time difference inserted")))))
  16054. (defun org-make-tdiff-string (y d h m)
  16055. (let ((fmt "")
  16056. (l nil))
  16057. (when (> y 0)
  16058. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16059. (push y l))
  16060. (when (> d 0)
  16061. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16062. (push d l))
  16063. (when (> h 0)
  16064. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16065. (push h l))
  16066. (when (> m 0)
  16067. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16068. (push m l))
  16069. (apply 'format fmt (nreverse l))))
  16070. (defun org-time-string-to-time (s &optional buffer pos)
  16071. "Convert a timestamp string into internal time."
  16072. (condition-case errdata
  16073. (apply 'encode-time (org-parse-time-string s))
  16074. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16075. s (if (not (and buffer pos))
  16076. ""
  16077. (format-message " at %d in buffer `%s'" pos buffer))
  16078. (cdr errdata)))))
  16079. (defun org-time-string-to-seconds (s)
  16080. "Convert a timestamp string to a number of seconds."
  16081. (float-time (org-time-string-to-time s)))
  16082. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16083. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16084. "Convert time stamp S to an absolute day number.
  16085. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16086. stamp, get the closest date to DAYNR. If PREFER is
  16087. `past' (respectively `future') return a date past (respectively
  16088. after) or equal to DAYNR.
  16089. POS is the location of time stamp S, as a buffer position in
  16090. BUFFER.
  16091. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16092. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16093. signalled."
  16094. (cond
  16095. ((string-match "\\`%%\\((.*)\\)" s)
  16096. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16097. ;; only able to match individual dates. If it fails, raise an
  16098. ;; error.
  16099. (if (and daynr
  16100. (org-diary-sexp-entry
  16101. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16102. daynr
  16103. (signal 'org-diary-sexp-no-match (list s))))
  16104. (daynr (org-closest-date s daynr prefer))
  16105. (t (time-to-days
  16106. (condition-case errdata
  16107. (apply #'encode-time (org-parse-time-string s))
  16108. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16109. s
  16110. (if (not (and buffer pos)) ""
  16111. (format-message " at %d in buffer `%s'" pos buffer))
  16112. (cdr errdata))))))))
  16113. (defun org-days-to-iso-week (days)
  16114. "Return the iso week number."
  16115. (require 'cal-iso)
  16116. (car (calendar-iso-from-absolute days)))
  16117. (defun org-small-year-to-year (year)
  16118. "Convert 2-digit years into 4-digit years.
  16119. YEAR is expanded into one of the 30 next years, if possible, or
  16120. into a past one. Any year larger than 99 is returned unchanged."
  16121. (if (>= year 100) year
  16122. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16123. (century (/ current 100))
  16124. (offset (- year (% current 100))))
  16125. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16126. ((> offset -70) (+ (* century 100) year))
  16127. (t (+ (* (1+ century) 100) year))))))
  16128. (defun org-time-from-absolute (d)
  16129. "Return the time corresponding to date D.
  16130. D may be an absolute day number, or a calendar-type list (month day year)."
  16131. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16132. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16133. (defvar org-agenda-current-date)
  16134. (defun org-calendar-holiday ()
  16135. "List of holidays, for Diary display in Org mode."
  16136. (require 'holidays)
  16137. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16138. (and hl (mapconcat #'identity hl "; "))))
  16139. (defun org-diary-sexp-entry (sexp entry d)
  16140. "Process a SEXP diary ENTRY for date D."
  16141. (require 'diary-lib)
  16142. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16143. ;; dynamically.
  16144. (let* ((sexp `(let ((entry ,entry)
  16145. (date ',d))
  16146. ,(car (read-from-string sexp))))
  16147. (result (if calendar-debug-sexp (eval sexp)
  16148. (condition-case nil
  16149. (eval sexp)
  16150. (error
  16151. (beep)
  16152. (message "Bad sexp at line %d in %s: %s"
  16153. (org-current-line)
  16154. (buffer-file-name) sexp)
  16155. (sleep-for 2))))))
  16156. (cond ((stringp result) (split-string result "; "))
  16157. ((and (consp result)
  16158. (not (consp (cdr result)))
  16159. (stringp (cdr result))) (cdr result))
  16160. ((and (consp result)
  16161. (stringp (car result))) result)
  16162. (result entry))))
  16163. (defun org-diary-to-ical-string (frombuf)
  16164. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16165. This uses the icalendar.el library."
  16166. (let* ((tmpdir temporary-file-directory)
  16167. (tmpfile (make-temp-name
  16168. (expand-file-name "orgics" tmpdir)))
  16169. buf rtn b e)
  16170. (with-current-buffer frombuf
  16171. (icalendar-export-region (point-min) (point-max) tmpfile)
  16172. (setq buf (find-buffer-visiting tmpfile))
  16173. (set-buffer buf)
  16174. (goto-char (point-min))
  16175. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16176. (setq b (match-beginning 0)))
  16177. (goto-char (point-max))
  16178. (when (re-search-backward "^END:VEVENT" nil t)
  16179. (setq e (match-end 0)))
  16180. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16181. (kill-buffer buf)
  16182. (delete-file tmpfile)
  16183. rtn))
  16184. (defun org-closest-date (start current prefer)
  16185. "Return closest date to CURRENT starting from START.
  16186. CURRENT and START are both time stamps.
  16187. When PREFER is `past', return a date that is either CURRENT or
  16188. past. When PREFER is `future', return a date that is either
  16189. CURRENT or future.
  16190. Only time stamps with a repeater are modified. Any other time
  16191. stamp stay unchanged. In any case, return value is an absolute
  16192. day number."
  16193. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16194. ;; No repeater. Do not shift time stamp.
  16195. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16196. (let ((value (string-to-number (match-string 1 start)))
  16197. (type (match-string 2 start)))
  16198. (if (= 0 value)
  16199. ;; Repeater with a 0-value is considered as void.
  16200. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16201. (let* ((base (org-date-to-gregorian start))
  16202. (target (org-date-to-gregorian current))
  16203. (sday (calendar-absolute-from-gregorian base))
  16204. (cday (calendar-absolute-from-gregorian target))
  16205. n1 n2)
  16206. ;; If START is already past CURRENT, just return START.
  16207. (if (<= cday sday) sday
  16208. ;; Compute closest date before (N1) and closest date past
  16209. ;; (N2) CURRENT.
  16210. (pcase type
  16211. ("h"
  16212. (let ((missing-hours
  16213. (mod (+ (- (* 24 (- cday sday))
  16214. (nth 2 (org-parse-time-string start)))
  16215. org-extend-today-until)
  16216. value)))
  16217. (setf n1 (if (= missing-hours 0) cday
  16218. (- cday (1+ (/ missing-hours 24)))))
  16219. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16220. ((or "d" "w")
  16221. (let ((value (if (equal type "w") (* 7 value) value)))
  16222. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16223. (setf n2 (+ n1 value))))
  16224. ("m"
  16225. (let* ((add-months
  16226. (lambda (d n)
  16227. ;; Add N months to gregorian date D, i.e.,
  16228. ;; a list (MONTH DAY YEAR). Return a valid
  16229. ;; gregorian date.
  16230. (let ((m (+ (nth 0 d) n)))
  16231. (list (mod m 12)
  16232. (nth 1 d)
  16233. (+ (/ m 12) (nth 2 d))))))
  16234. (months ; Complete months to TARGET.
  16235. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16236. (- (nth 0 target) (nth 0 base))
  16237. ;; If START's day is greater than
  16238. ;; TARGET's, remove incomplete month.
  16239. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16240. value)
  16241. value))
  16242. (before (funcall add-months base months)))
  16243. (setf n1 (calendar-absolute-from-gregorian before))
  16244. (setf n2
  16245. (calendar-absolute-from-gregorian
  16246. (funcall add-months before value)))))
  16247. (_
  16248. (let* ((d (nth 1 base))
  16249. (m (nth 0 base))
  16250. (y (nth 2 base))
  16251. (years ; Complete years to TARGET.
  16252. (* (/ (- (nth 2 target)
  16253. y
  16254. ;; If START's month and day are
  16255. ;; greater than TARGET's, remove
  16256. ;; incomplete year.
  16257. (if (or (> (nth 0 target) m)
  16258. (and (= (nth 0 target) m)
  16259. (> (nth 1 target) d)))
  16260. 0
  16261. 1))
  16262. value)
  16263. value))
  16264. (before (list m d (+ y years))))
  16265. (setf n1 (calendar-absolute-from-gregorian before))
  16266. (setf n2 (calendar-absolute-from-gregorian
  16267. (list m d (+ (nth 2 before) value)))))))
  16268. ;; Handle PREFER parameter, if any.
  16269. (cond
  16270. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16271. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16272. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16273. (defun org-date-to-gregorian (d)
  16274. "Turn any specification of date D into a Gregorian date for the calendar."
  16275. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16276. ((and (listp d) (= (length d) 3)) d)
  16277. ((stringp d)
  16278. (let ((d (org-parse-time-string d)))
  16279. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16280. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16281. (defun org-parse-time-string (s &optional nodefault)
  16282. "Parse the standard Org time string.
  16283. This should be a lot faster than the normal `parse-time-string'.
  16284. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16285. hour and minute fields will be nil if not given."
  16286. (cond ((string-match org-ts-regexp0 s)
  16287. (list 0
  16288. (when (or (match-beginning 8) (not nodefault))
  16289. (string-to-number (or (match-string 8 s) "0")))
  16290. (when (or (match-beginning 7) (not nodefault))
  16291. (string-to-number (or (match-string 7 s) "0")))
  16292. (string-to-number (match-string 4 s))
  16293. (string-to-number (match-string 3 s))
  16294. (string-to-number (match-string 2 s))
  16295. nil nil nil))
  16296. ((string-match "^<[^>]+>$" s)
  16297. (decode-time (seconds-to-time (org-matcher-time s))))
  16298. (t (error "Not a standard Org time string: %s" s))))
  16299. (defun org-timestamp-up (&optional arg)
  16300. "Increase the date item at the cursor by one.
  16301. If the cursor is on the year, change the year. If it is on the month,
  16302. the day or the time, change that.
  16303. With prefix ARG, change by that many units."
  16304. (interactive "p")
  16305. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16306. (defun org-timestamp-down (&optional arg)
  16307. "Decrease the date item at the cursor by one.
  16308. If the cursor is on the year, change the year. If it is on the month,
  16309. the day or the time, change that.
  16310. With prefix ARG, change by that many units."
  16311. (interactive "p")
  16312. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16313. (defun org-timestamp-up-day (&optional arg)
  16314. "Increase the date in the time stamp by one day.
  16315. With prefix ARG, change that many days."
  16316. (interactive "p")
  16317. (if (and (not (org-at-timestamp-p 'lax))
  16318. (org-at-heading-p))
  16319. (org-todo 'up)
  16320. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16321. (defun org-timestamp-down-day (&optional arg)
  16322. "Decrease the date in the time stamp by one day.
  16323. With prefix ARG, change that many days."
  16324. (interactive "p")
  16325. (if (and (not (org-at-timestamp-p 'lax))
  16326. (org-at-heading-p))
  16327. (org-todo 'down)
  16328. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16329. (defun org-at-timestamp-p (&optional extended)
  16330. "Non-nil if point is inside a timestamp.
  16331. By default, the function only consider syntactically valid active
  16332. timestamps. However, the caller may have a broader definition
  16333. for timestamps. As a consequence, optional argument EXTENDED can
  16334. be set to the following values
  16335. `inactive'
  16336. Include also syntactically valid inactive timestamps.
  16337. `agenda'
  16338. Include timestamps allowed in Agenda, i.e., those in
  16339. properties drawers, planning lines and clock lines.
  16340. `lax'
  16341. Ignore context. The function matches any part of the
  16342. document looking like a timestamp. This includes comments,
  16343. example blocks...
  16344. For backward-compatibility with Org 9.0, every other non-nil
  16345. value is equivalent to `inactive'.
  16346. When at a timestamp, return the position of the point as a symbol
  16347. among `bracket', `after', `year', `month', `hour', `minute',
  16348. `day' or a number of character from the last know part of the
  16349. time stamp.
  16350. When matching, the match groups are the following:
  16351. group 1: year
  16352. group 2: month
  16353. group 3: day number
  16354. group 4: day name
  16355. group 5: hours, if any
  16356. group 6: minutes, if any"
  16357. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16358. (pos (point))
  16359. (match?
  16360. (let ((boundaries (org-in-regexp regexp)))
  16361. (save-match-data
  16362. (cond ((null boundaries) nil)
  16363. ((eq extended 'lax) t)
  16364. (t
  16365. (or (and (eq extended 'agenda)
  16366. (or (org-at-planning-p)
  16367. (org-at-property-p)
  16368. (and org-agenda-include-inactive-timestamps
  16369. (org-at-clock-log-p))))
  16370. (eq 'timestamp
  16371. (save-excursion
  16372. (when (= pos (cdr boundaries)) (forward-char -1))
  16373. (org-element-type (org-element-context)))))))))))
  16374. (cond
  16375. ((not match?) nil)
  16376. ((= pos (match-beginning 0)) 'bracket)
  16377. ;; Distinguish location right before the closing bracket from
  16378. ;; right after it.
  16379. ((= pos (1- (match-end 0))) 'bracket)
  16380. ((= pos (match-end 0)) 'after)
  16381. ((org-pos-in-match-range pos 2) 'year)
  16382. ((org-pos-in-match-range pos 3) 'month)
  16383. ((org-pos-in-match-range pos 7) 'hour)
  16384. ((org-pos-in-match-range pos 8) 'minute)
  16385. ((or (org-pos-in-match-range pos 4)
  16386. (org-pos-in-match-range pos 5)) 'day)
  16387. ((and (> pos (or (match-end 8) (match-end 5)))
  16388. (< pos (match-end 0)))
  16389. (- pos (or (match-end 8) (match-end 5))))
  16390. (t 'day))))
  16391. (defun org-toggle-timestamp-type ()
  16392. "Toggle the type (<active> or [inactive]) of a time stamp."
  16393. (interactive)
  16394. (when (org-at-timestamp-p 'lax)
  16395. (let ((beg (match-beginning 0)) (end (match-end 0))
  16396. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16397. (save-excursion
  16398. (goto-char beg)
  16399. (while (re-search-forward "[][<>]" end t)
  16400. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16401. t t)))
  16402. (message "Timestamp is now %sactive"
  16403. (if (equal (char-after beg) ?<) "" "in")))))
  16404. (defun org-at-clock-log-p ()
  16405. "Non-nil if point is on a clock log line."
  16406. (and (org-match-line org-clock-line-re)
  16407. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16408. (defvar org-clock-history) ; defined in org-clock.el
  16409. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16410. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16411. "Change the date in the time stamp at point.
  16412. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16413. `year', `minute', `second'. If WHAT is not given, the cursor position
  16414. in the timestamp determines what will be changed.
  16415. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16416. (let ((origin (point))
  16417. (timestamp? (org-at-timestamp-p 'lax))
  16418. origin-cat
  16419. with-hm inactive
  16420. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16421. extra rem
  16422. ts time time0 fixnext clrgx)
  16423. (unless timestamp? (user-error "Not at a timestamp"))
  16424. (if (and (not what) (eq timestamp? 'bracket))
  16425. (org-toggle-timestamp-type)
  16426. ;; Point isn't on brackets. Remember the part of the time-stamp
  16427. ;; the point was in. Indeed, size of time-stamps may change,
  16428. ;; but point must be kept in the same category nonetheless.
  16429. (setq origin-cat timestamp?)
  16430. (when (and (not what) (not (eq timestamp? 'day))
  16431. org-display-custom-times
  16432. (get-text-property (point) 'display)
  16433. (not (get-text-property (1- (point)) 'display)))
  16434. (setq timestamp? 'day))
  16435. (setq timestamp? (or what timestamp?)
  16436. inactive (= (char-after (match-beginning 0)) ?\[)
  16437. ts (match-string 0))
  16438. (replace-match "")
  16439. (when (string-match
  16440. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16441. ts)
  16442. (setq extra (match-string 1 ts))
  16443. (when suppress-tmp-delay
  16444. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16445. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16446. (setq with-hm t))
  16447. (setq time0 (org-parse-time-string ts))
  16448. (when (and updown
  16449. (eq timestamp? 'minute)
  16450. (not current-prefix-arg))
  16451. ;; This looks like s-up and s-down. Change by one rounding step.
  16452. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16453. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16454. (setcar (cdr time0) (+ (nth 1 time0)
  16455. (if (> n 0) (- rem) (- dm rem))))))
  16456. (setq time
  16457. (apply #'encode-time
  16458. (or (car time0) 0)
  16459. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16460. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16461. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16462. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16463. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16464. (nthcdr 6 time0)))
  16465. (when (and (memq timestamp? '(hour minute))
  16466. extra
  16467. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16468. (setq extra (org-modify-ts-extra
  16469. extra
  16470. (if (eq timestamp? 'hour) 2 5)
  16471. n dm)))
  16472. (when (integerp timestamp?)
  16473. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16474. (when (eq what 'calendar)
  16475. (let ((cal-date (org-get-date-from-calendar)))
  16476. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16477. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16478. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16479. (setcar time0 (or (car time0) 0))
  16480. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16481. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16482. (setq time (apply 'encode-time time0))))
  16483. ;; Insert the new time-stamp, and ensure point stays in the same
  16484. ;; category as before (i.e. not after the last position in that
  16485. ;; category).
  16486. (let ((pos (point)))
  16487. ;; Stay before inserted string. `save-excursion' is of no use.
  16488. (setq org-last-changed-timestamp
  16489. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16490. (goto-char pos))
  16491. (save-match-data
  16492. (looking-at org-ts-regexp3)
  16493. (goto-char
  16494. (pcase origin-cat
  16495. ;; `day' category ends before `hour' if any, or at the end
  16496. ;; of the day name.
  16497. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16498. (`hour (min (match-end 7) origin))
  16499. (`minute (min (1- (match-end 8)) origin))
  16500. ((pred integerp) (min (1- (match-end 0)) origin))
  16501. ;; Point was right after the time-stamp. However, the
  16502. ;; time-stamp length might have changed, so refer to
  16503. ;; (match-end 0) instead.
  16504. (`after (match-end 0))
  16505. ;; `year' and `month' have both fixed size: point couldn't
  16506. ;; have moved into another part.
  16507. (_ origin))))
  16508. ;; Update clock if on a CLOCK line.
  16509. (org-clock-update-time-maybe)
  16510. ;; Maybe adjust the closest clock in `org-clock-history'
  16511. (when org-clock-adjust-closest
  16512. (if (not (and (org-at-clock-log-p)
  16513. (< 1 (length (delq nil (mapcar 'marker-position
  16514. org-clock-history))))))
  16515. (message "No clock to adjust")
  16516. (cond ((save-excursion ; fix previous clock?
  16517. (re-search-backward org-ts-regexp0 nil t)
  16518. (looking-back (concat org-clock-string " \\[")
  16519. (line-beginning-position)))
  16520. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16521. ((save-excursion ; fix next clock?
  16522. (re-search-backward org-ts-regexp0 nil t)
  16523. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16524. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16525. (save-window-excursion
  16526. ;; Find closest clock to point, adjust the previous/next one in history
  16527. (let* ((p (save-excursion (org-back-to-heading t)))
  16528. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16529. (clfixnth
  16530. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16531. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16532. (if (not clfixpos)
  16533. (message "No clock to adjust")
  16534. (save-excursion
  16535. (org-goto-marker-or-bmk clfixpos)
  16536. (org-show-subtree)
  16537. (when (re-search-forward clrgx nil t)
  16538. (goto-char (match-beginning 1))
  16539. (let (org-clock-adjust-closest)
  16540. (org-timestamp-change n timestamp? updown))
  16541. (message "Clock adjusted in %s for heading: %s"
  16542. (file-name-nondirectory (buffer-file-name))
  16543. (org-get-heading t t)))))))))
  16544. ;; Try to recenter the calendar window, if any.
  16545. (when (and org-calendar-follow-timestamp-change
  16546. (get-buffer-window "*Calendar*" t)
  16547. (memq timestamp? '(day month year)))
  16548. (org-recenter-calendar (time-to-days time))))))
  16549. (defun org-modify-ts-extra (s pos n dm)
  16550. "Change the different parts of the lead-time and repeat fields in timestamp."
  16551. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16552. ng h m new rem)
  16553. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16554. (cond
  16555. ((or (org-pos-in-match-range pos 2)
  16556. (org-pos-in-match-range pos 3))
  16557. (setq m (string-to-number (match-string 3 s))
  16558. h (string-to-number (match-string 2 s)))
  16559. (if (org-pos-in-match-range pos 2)
  16560. (setq h (+ h n))
  16561. (setq n (* dm (with-no-warnings (signum n))))
  16562. (unless (= 0 (setq rem (% m dm)))
  16563. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16564. (setq m (+ m n)))
  16565. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16566. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16567. (setq h (mod h 24))
  16568. (setq ng 1 new (format "-%02d:%02d" h m)))
  16569. ((org-pos-in-match-range pos 6)
  16570. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16571. ((org-pos-in-match-range pos 5)
  16572. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16573. ((org-pos-in-match-range pos 9)
  16574. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16575. ((org-pos-in-match-range pos 8)
  16576. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16577. (when ng
  16578. (setq s (concat
  16579. (substring s 0 (match-beginning ng))
  16580. new
  16581. (substring s (match-end ng))))))
  16582. s))
  16583. (defun org-recenter-calendar (d)
  16584. "If the calendar is visible, recenter it to date D."
  16585. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16586. (when cwin
  16587. (let ((calendar-move-hook nil))
  16588. (with-selected-window cwin
  16589. (calendar-goto-date
  16590. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16591. (defun org-goto-calendar (&optional arg)
  16592. "Go to the Emacs calendar at the current date.
  16593. If there is a time stamp in the current line, go to that date.
  16594. A prefix ARG can be used to force the current date."
  16595. (interactive "P")
  16596. (let ((calendar-move-hook nil)
  16597. (calendar-view-holidays-initially-flag nil)
  16598. (calendar-view-diary-initially-flag nil)
  16599. diff)
  16600. (when (or (org-at-timestamp-p 'lax)
  16601. (org-match-line (concat ".*" org-ts-regexp)))
  16602. (let ((d1 (time-to-days (current-time)))
  16603. (d2 (time-to-days
  16604. (org-time-string-to-time (match-string 1)))))
  16605. (setq diff (- d2 d1))))
  16606. (calendar)
  16607. (calendar-goto-today)
  16608. (when (and diff (not arg)) (calendar-forward-day diff))))
  16609. (defun org-get-date-from-calendar ()
  16610. "Return a list (month day year) of date at point in calendar."
  16611. (with-current-buffer "*Calendar*"
  16612. (save-match-data
  16613. (calendar-cursor-to-date))))
  16614. (defun org-date-from-calendar ()
  16615. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16616. If there is already a time stamp at the cursor position, update it."
  16617. (interactive)
  16618. (if (org-at-timestamp-p 'lax)
  16619. (org-timestamp-change 0 'calendar)
  16620. (let ((cal-date (org-get-date-from-calendar)))
  16621. (org-insert-time-stamp
  16622. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16623. (defcustom org-effort-durations
  16624. `(("min" . 1)
  16625. ("h" . 60)
  16626. ("d" . ,(* 60 8))
  16627. ("w" . ,(* 60 8 5))
  16628. ("m" . ,(* 60 8 5 4))
  16629. ("y" . ,(* 60 8 5 40)))
  16630. "Conversion factor to minutes for an effort modifier.
  16631. Each entry has the form (MODIFIER . MINUTES).
  16632. In an effort string, a number followed by MODIFIER is multiplied
  16633. by the specified number of MINUTES to obtain an effort in
  16634. minutes.
  16635. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16636. effort string \"2hours\" is equivalent to 120 minutes."
  16637. :group 'org-agenda
  16638. :version "26.1"
  16639. :package-version '(Org . "8.3")
  16640. :type '(alist :key-type (string :tag "Modifier")
  16641. :value-type (number :tag "Minutes")))
  16642. (defcustom org-image-actual-width t
  16643. "Should we use the actual width of images when inlining them?
  16644. When set to t, always use the image width.
  16645. When set to a number, use imagemagick (when available) to set
  16646. the image's width to this value.
  16647. When set to a number in a list, try to get the width from any
  16648. #+ATTR.* keyword if it matches a width specification like
  16649. #+ATTR_HTML: :width 300px
  16650. and fall back on that number if none is found.
  16651. When set to nil, try to get the width from an #+ATTR.* keyword
  16652. and fall back on the original width if none is found.
  16653. This requires Emacs >= 24.1, build with imagemagick support."
  16654. :group 'org-appearance
  16655. :version "24.4"
  16656. :package-version '(Org . "8.0")
  16657. :type '(choice
  16658. (const :tag "Use the image width" t)
  16659. (integer :tag "Use a number of pixels")
  16660. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16661. (const :tag "Use #+ATTR* or don't resize" nil)))
  16662. (defcustom org-agenda-inhibit-startup nil
  16663. "Inhibit startup when preparing agenda buffers.
  16664. When this variable is t, the initialization of the Org agenda
  16665. buffers is inhibited: e.g. the visibility state is not set, the
  16666. tables are not re-aligned, etc."
  16667. :type 'boolean
  16668. :version "24.3"
  16669. :group 'org-agenda)
  16670. (defcustom org-agenda-ignore-properties nil
  16671. "Avoid updating text properties when building the agenda.
  16672. Properties are used to prepare buffers for effort estimates,
  16673. appointments, statistics and subtree-local categories.
  16674. If you don't use these in the agenda, you can add them to this
  16675. list and agenda building will be a bit faster.
  16676. The value is a list, with zero or more of the symbols `effort', `appt',
  16677. `stats' or `category'."
  16678. :type '(set :greedy t
  16679. (const effort)
  16680. (const appt)
  16681. (const stats)
  16682. (const category))
  16683. :version "26.1"
  16684. :package-version '(Org . "8.3")
  16685. :group 'org-agenda)
  16686. ;;;; Files
  16687. (defun org-save-all-org-buffers ()
  16688. "Save all Org buffers without user confirmation."
  16689. (interactive)
  16690. (message "Saving all Org buffers...")
  16691. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16692. (when (featurep 'org-id) (org-id-locations-save))
  16693. (message "Saving all Org buffers... done"))
  16694. (defun org-revert-all-org-buffers ()
  16695. "Revert all Org buffers.
  16696. Prompt for confirmation when there are unsaved changes.
  16697. Be sure you know what you are doing before letting this function
  16698. overwrite your changes.
  16699. This function is useful in a setup where one tracks org files
  16700. with a version control system, to revert on one machine after pulling
  16701. changes from another. I believe the procedure must be like this:
  16702. 1. M-x org-save-all-org-buffers
  16703. 2. Pull changes from the other machine, resolve conflicts
  16704. 3. M-x org-revert-all-org-buffers"
  16705. (interactive)
  16706. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16707. (user-error "Abort"))
  16708. (save-excursion
  16709. (save-window-excursion
  16710. (dolist (b (buffer-list))
  16711. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16712. (with-current-buffer b buffer-file-name))
  16713. (pop-to-buffer-same-window b)
  16714. (revert-buffer t 'no-confirm)))
  16715. (when (and (featurep 'org-id) org-id-track-globally)
  16716. (org-id-locations-load)))))
  16717. ;;;; Agenda files
  16718. ;;;###autoload
  16719. (defun org-switchb (&optional arg)
  16720. "Switch between Org buffers.
  16721. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16722. With `\\[universal-argument] \\[universal-argument]' \
  16723. prefix, restrict available buffers to agenda files."
  16724. (interactive "P")
  16725. (let ((blist (org-buffer-list
  16726. (cond ((equal arg '(4)) 'files)
  16727. ((equal arg '(16)) 'agenda)))))
  16728. (pop-to-buffer-same-window
  16729. (completing-read "Org buffer: "
  16730. (mapcar #'list (mapcar #'buffer-name blist))
  16731. nil t))))
  16732. (defun org-buffer-list (&optional predicate exclude-tmp)
  16733. "Return a list of Org buffers.
  16734. PREDICATE can be `export', `files' or `agenda'.
  16735. export restrict the list to Export buffers.
  16736. files restrict the list to buffers visiting Org files.
  16737. agenda restrict the list to buffers visiting agenda files.
  16738. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16739. (let* ((bfn nil)
  16740. (agenda-files (and (eq predicate 'agenda)
  16741. (mapcar 'file-truename (org-agenda-files t))))
  16742. (filter
  16743. (cond
  16744. ((eq predicate 'files)
  16745. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16746. ((eq predicate 'export)
  16747. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16748. ((eq predicate 'agenda)
  16749. (lambda (b)
  16750. (with-current-buffer b
  16751. (and (derived-mode-p 'org-mode)
  16752. (setq bfn (buffer-file-name b))
  16753. (member (file-truename bfn) agenda-files)))))
  16754. (t (lambda (b) (with-current-buffer b
  16755. (or (derived-mode-p 'org-mode)
  16756. (string-match "\\*Org .*Export"
  16757. (buffer-name b)))))))))
  16758. (delq nil
  16759. (mapcar
  16760. (lambda(b)
  16761. (if (and (funcall filter b)
  16762. (or (not exclude-tmp)
  16763. (not (string-match "tmp" (buffer-name b)))))
  16764. b
  16765. nil))
  16766. (buffer-list)))))
  16767. (defun org-agenda-files (&optional unrestricted archives)
  16768. "Get the list of agenda files.
  16769. Optional UNRESTRICTED means return the full list even if a restriction
  16770. is currently in place.
  16771. When ARCHIVES is t, include all archive files that are really being
  16772. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16773. `org-agenda-archives-mode' is t."
  16774. (let ((files
  16775. (cond
  16776. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16777. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16778. ((listp org-agenda-files) org-agenda-files)
  16779. (t (error "Invalid value of `org-agenda-files'")))))
  16780. (setq files (apply 'append
  16781. (mapcar (lambda (f)
  16782. (if (file-directory-p f)
  16783. (directory-files
  16784. f t org-agenda-file-regexp)
  16785. (list f)))
  16786. files)))
  16787. (when org-agenda-skip-unavailable-files
  16788. (setq files (delq nil
  16789. (mapcar (function
  16790. (lambda (file)
  16791. (and (file-readable-p file) file)))
  16792. files))))
  16793. (when (or (eq archives t)
  16794. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16795. (setq files (org-add-archive-files files)))
  16796. files))
  16797. (defun org-agenda-file-p (&optional file)
  16798. "Return non-nil, if FILE is an agenda file.
  16799. If FILE is omitted, use the file associated with the current
  16800. buffer."
  16801. (let ((fname (or file (buffer-file-name))))
  16802. (and fname
  16803. (member (file-truename fname)
  16804. (mapcar #'file-truename (org-agenda-files t))))))
  16805. (defun org-edit-agenda-file-list ()
  16806. "Edit the list of agenda files.
  16807. Depending on setup, this either uses customize to edit the variable
  16808. `org-agenda-files', or it visits the file that is holding the list. In the
  16809. latter case, the buffer is set up in a way that saving it automatically kills
  16810. the buffer and restores the previous window configuration."
  16811. (interactive)
  16812. (if (stringp org-agenda-files)
  16813. (let ((cw (current-window-configuration)))
  16814. (find-file org-agenda-files)
  16815. (setq-local org-window-configuration cw)
  16816. (add-hook 'after-save-hook
  16817. (lambda ()
  16818. (set-window-configuration
  16819. (prog1 org-window-configuration
  16820. (kill-buffer (current-buffer))))
  16821. (org-install-agenda-files-menu)
  16822. (message "New agenda file list installed"))
  16823. nil 'local)
  16824. (message "%s" (substitute-command-keys
  16825. "Edit list and finish with \\[save-buffer]")))
  16826. (customize-variable 'org-agenda-files)))
  16827. (defun org-store-new-agenda-file-list (list)
  16828. "Set new value for the agenda file list and save it correctly."
  16829. (if (stringp org-agenda-files)
  16830. (let ((fe (org-read-agenda-file-list t)) b u)
  16831. (while (setq b (find-buffer-visiting org-agenda-files))
  16832. (kill-buffer b))
  16833. (with-temp-file org-agenda-files
  16834. (insert
  16835. (mapconcat
  16836. (lambda (f) ;; Keep un-expanded entries.
  16837. (if (setq u (assoc f fe))
  16838. (cdr u)
  16839. f))
  16840. list "\n")
  16841. "\n")))
  16842. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16843. (org-insert-mode-line-in-empty-file nil))
  16844. (setq org-agenda-files list)
  16845. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16846. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16847. "Read the list of agenda files from a file.
  16848. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16849. filenames, used by `org-store-new-agenda-file-list' to write back
  16850. un-expanded file names."
  16851. (when (file-directory-p org-agenda-files)
  16852. (error "`org-agenda-files' cannot be a single directory"))
  16853. (when (stringp org-agenda-files)
  16854. (with-temp-buffer
  16855. (insert-file-contents org-agenda-files)
  16856. (mapcar
  16857. (lambda (f)
  16858. (let ((e (expand-file-name (substitute-in-file-name f)
  16859. org-directory)))
  16860. (if pair-with-expansion
  16861. (cons e f)
  16862. e)))
  16863. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16864. ;;;###autoload
  16865. (defun org-cycle-agenda-files ()
  16866. "Cycle through the files in `org-agenda-files'.
  16867. If the current buffer visits an agenda file, find the next one in the list.
  16868. If the current buffer does not, find the first agenda file."
  16869. (interactive)
  16870. (let* ((fs (or (org-agenda-files t)
  16871. (user-error "No agenda files")))
  16872. (files (copy-sequence fs))
  16873. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16874. file)
  16875. (when tcf
  16876. (while (and (setq file (pop files))
  16877. (not (equal (file-truename file) tcf)))))
  16878. (find-file (car (or files fs)))
  16879. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16880. (defun org-agenda-file-to-front (&optional to-end)
  16881. "Move/add the current file to the top of the agenda file list.
  16882. If the file is not present in the list, it is added to the front. If it is
  16883. present, it is moved there. With optional argument TO-END, add/move to the
  16884. end of the list."
  16885. (interactive "P")
  16886. (let ((org-agenda-skip-unavailable-files nil)
  16887. (file-alist (mapcar (lambda (x)
  16888. (cons (file-truename x) x))
  16889. (org-agenda-files t)))
  16890. (ctf (file-truename
  16891. (or buffer-file-name
  16892. (user-error "Please save the current buffer to a file"))))
  16893. x had)
  16894. (setq x (assoc ctf file-alist) had x)
  16895. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16896. (if to-end
  16897. (setq file-alist (append (delq x file-alist) (list x)))
  16898. (setq file-alist (cons x (delq x file-alist))))
  16899. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16900. (org-install-agenda-files-menu)
  16901. (message "File %s to %s of agenda file list"
  16902. (if had "moved" "added") (if to-end "end" "front"))))
  16903. (defun org-remove-file (&optional file)
  16904. "Remove current file from the list of files in variable `org-agenda-files'.
  16905. These are the files which are being checked for agenda entries.
  16906. Optional argument FILE means use this file instead of the current."
  16907. (interactive)
  16908. (let* ((org-agenda-skip-unavailable-files nil)
  16909. (file (or file buffer-file-name
  16910. (user-error "Current buffer does not visit a file")))
  16911. (true-file (file-truename file))
  16912. (afile (abbreviate-file-name file))
  16913. (files (delq nil (mapcar
  16914. (lambda (x)
  16915. (unless (equal true-file
  16916. (file-truename x))
  16917. x))
  16918. (org-agenda-files t)))))
  16919. (if (not (= (length files) (length (org-agenda-files t))))
  16920. (progn
  16921. (org-store-new-agenda-file-list files)
  16922. (org-install-agenda-files-menu)
  16923. (message "Removed from Org Agenda list: %s" afile))
  16924. (message "File was not in list: %s (not removed)" afile))))
  16925. (defun org-file-menu-entry (file)
  16926. (vector file (list 'find-file file) t))
  16927. (defun org-check-agenda-file (file)
  16928. "Make sure FILE exists. If not, ask user what to do."
  16929. (unless (file-exists-p file)
  16930. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16931. (abbreviate-file-name file))
  16932. (let ((r (downcase (read-char-exclusive))))
  16933. (cond
  16934. ((equal r ?r)
  16935. (org-remove-file file)
  16936. (throw 'nextfile t))
  16937. (t (user-error "Abort"))))))
  16938. (defun org-get-agenda-file-buffer (file)
  16939. "Get an agenda buffer visiting FILE.
  16940. If the buffer needs to be created, add it to the list of buffers
  16941. which might be released later."
  16942. (let ((buf (org-find-base-buffer-visiting file)))
  16943. (if buf
  16944. buf ; just return it
  16945. ;; Make a new buffer and remember it
  16946. (setq buf (find-file-noselect file))
  16947. (when buf (push buf org-agenda-new-buffers))
  16948. buf)))
  16949. (defun org-release-buffers (blist)
  16950. "Release all buffers in list, asking the user for confirmation when needed.
  16951. When a buffer is unmodified, it is just killed. When modified, it is saved
  16952. \(if the user agrees) and then killed."
  16953. (let (file)
  16954. (dolist (buf blist)
  16955. (setq file (buffer-file-name buf))
  16956. (when (and (buffer-modified-p buf)
  16957. file
  16958. (y-or-n-p (format "Save file %s? " file)))
  16959. (with-current-buffer buf (save-buffer)))
  16960. (kill-buffer buf))))
  16961. (defun org-agenda-prepare-buffers (files)
  16962. "Create buffers for all agenda files, protect archived trees and comments."
  16963. (interactive)
  16964. (let ((pa '(:org-archived t))
  16965. (pc '(:org-comment t))
  16966. (pall '(:org-archived t :org-comment t))
  16967. (inhibit-read-only t)
  16968. (org-inhibit-startup org-agenda-inhibit-startup)
  16969. (rea (concat ":" org-archive-tag ":"))
  16970. re pos)
  16971. (setq org-tag-alist-for-agenda nil
  16972. org-tag-groups-alist-for-agenda nil)
  16973. (save-excursion
  16974. (save-restriction
  16975. (dolist (file files)
  16976. (catch 'nextfile
  16977. (if (bufferp file)
  16978. (set-buffer file)
  16979. (org-check-agenda-file file)
  16980. (set-buffer (org-get-agenda-file-buffer file)))
  16981. (widen)
  16982. (org-set-regexps-and-options 'tags-only)
  16983. (setq pos (point))
  16984. (or (memq 'category org-agenda-ignore-properties)
  16985. (org-refresh-category-properties))
  16986. (or (memq 'stats org-agenda-ignore-properties)
  16987. (org-refresh-stats-properties))
  16988. (or (memq 'effort org-agenda-ignore-properties)
  16989. (org-refresh-effort-properties))
  16990. (or (memq 'appt org-agenda-ignore-properties)
  16991. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16992. (setq org-todo-keywords-for-agenda
  16993. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16994. (setq org-done-keywords-for-agenda
  16995. (append org-done-keywords-for-agenda org-done-keywords))
  16996. (setq org-todo-keyword-alist-for-agenda
  16997. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16998. (setq org-tag-alist-for-agenda
  16999. (org-uniquify
  17000. (append org-tag-alist-for-agenda
  17001. org-current-tag-alist)))
  17002. ;; Merge current file's tag groups into global
  17003. ;; `org-tag-groups-alist-for-agenda'.
  17004. (when org-group-tags
  17005. (dolist (alist org-tag-groups-alist)
  17006. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17007. (if old
  17008. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17009. (push alist org-tag-groups-alist-for-agenda)))))
  17010. (org-with-silent-modifications
  17011. (save-excursion
  17012. (remove-text-properties (point-min) (point-max) pall)
  17013. (when org-agenda-skip-archived-trees
  17014. (goto-char (point-min))
  17015. (while (re-search-forward rea nil t)
  17016. (when (org-at-heading-p t)
  17017. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17018. (goto-char (point-min))
  17019. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17020. (while (re-search-forward re nil t)
  17021. (when (save-match-data (org-in-commented-heading-p t))
  17022. (add-text-properties
  17023. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17024. (goto-char pos)))))
  17025. (setq org-todo-keywords-for-agenda
  17026. (org-uniquify org-todo-keywords-for-agenda))
  17027. (setq org-todo-keyword-alist-for-agenda
  17028. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17029. ;;;; CDLaTeX minor mode
  17030. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17031. "Keymap for the minor `org-cdlatex-mode'.")
  17032. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17033. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17034. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17035. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17036. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17037. (defvar org-cdlatex-texmathp-advice-is-done nil
  17038. "Flag remembering if we have applied the advice to texmathp already.")
  17039. (define-minor-mode org-cdlatex-mode
  17040. "Toggle the minor `org-cdlatex-mode'.
  17041. This mode supports entering LaTeX environment and math in LaTeX fragments
  17042. in Org mode.
  17043. \\{org-cdlatex-mode-map}"
  17044. nil " OCDL" nil
  17045. (when org-cdlatex-mode
  17046. (require 'cdlatex)
  17047. (run-hooks 'cdlatex-mode-hook)
  17048. (cdlatex-compute-tables))
  17049. (unless org-cdlatex-texmathp-advice-is-done
  17050. (setq org-cdlatex-texmathp-advice-is-done t)
  17051. (defadvice texmathp (around org-math-always-on activate)
  17052. "Always return t in Org buffers.
  17053. This is because we want to insert math symbols without dollars even outside
  17054. the LaTeX math segments. If Org mode thinks that point is actually inside
  17055. an embedded LaTeX fragment, let `texmathp' do its job.
  17056. `\\[org-cdlatex-mode-map]'"
  17057. (interactive)
  17058. (let (p)
  17059. (cond
  17060. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17061. ((eq this-command 'cdlatex-math-symbol)
  17062. (setq ad-return-value t
  17063. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17064. (t
  17065. (let ((p (org-inside-LaTeX-fragment-p)))
  17066. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17067. (setq ad-return-value t
  17068. texmathp-why '("Org mode embedded math" . 0))
  17069. (when p ad-do-it)))))))))
  17070. (defun turn-on-org-cdlatex ()
  17071. "Unconditionally turn on `org-cdlatex-mode'."
  17072. (org-cdlatex-mode 1))
  17073. (defun org-try-cdlatex-tab ()
  17074. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17075. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17076. - inside a LaTeX fragment, or
  17077. - after the first word in a line, where an abbreviation expansion could
  17078. insert a LaTeX environment."
  17079. (when org-cdlatex-mode
  17080. (cond
  17081. ;; Before any word on the line: No expansion possible.
  17082. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17083. ;; Just after first word on the line: Expand it. Make sure it
  17084. ;; cannot happen on headlines, though.
  17085. ((save-excursion
  17086. (skip-chars-backward "a-zA-Z0-9*")
  17087. (skip-chars-backward " \t")
  17088. (and (bolp) (not (org-at-heading-p))))
  17089. (cdlatex-tab) t)
  17090. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17091. (defun org-cdlatex-underscore-caret (&optional _arg)
  17092. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17093. Revert to the normal definition outside of these fragments."
  17094. (interactive "P")
  17095. (if (org-inside-LaTeX-fragment-p)
  17096. (call-interactively 'cdlatex-sub-superscript)
  17097. (let (org-cdlatex-mode)
  17098. (call-interactively (key-binding (vector last-input-event))))))
  17099. (defun org-cdlatex-math-modify (&optional _arg)
  17100. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17101. Revert to the normal definition outside of these fragments."
  17102. (interactive "P")
  17103. (if (org-inside-LaTeX-fragment-p)
  17104. (call-interactively 'cdlatex-math-modify)
  17105. (let (org-cdlatex-mode)
  17106. (call-interactively (key-binding (vector last-input-event))))))
  17107. (defun org-cdlatex-environment-indent (&optional environment item)
  17108. "Execute `cdlatex-environment' and indent the inserted environment.
  17109. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17110. The inserted environment is indented to current indentation
  17111. unless point is at the beginning of the line, in which the
  17112. environment remains unintended."
  17113. (interactive)
  17114. ;; cdlatex-environment always return nil. Therefore, capture output
  17115. ;; first and determine if an environment was selected.
  17116. (let* ((beg (point-marker))
  17117. (end (copy-marker (point) t))
  17118. (inserted (progn
  17119. (ignore-errors (cdlatex-environment environment item))
  17120. (< beg end)))
  17121. ;; Figure out how many lines to move forward after the
  17122. ;; environment has been inserted.
  17123. (lines (when inserted
  17124. (save-excursion
  17125. (- (cl-loop while (< beg (point))
  17126. with x = 0
  17127. do (forward-line -1)
  17128. (cl-incf x)
  17129. finally return x)
  17130. (if (progn (goto-char beg)
  17131. (and (progn (skip-chars-forward " \t") (eolp))
  17132. (progn (skip-chars-backward " \t") (bolp))))
  17133. 1 0)))))
  17134. (env (org-trim (delete-and-extract-region beg end))))
  17135. (when inserted
  17136. ;; Get indentation of next line unless at column 0.
  17137. (let ((ind (if (bolp) 0
  17138. (save-excursion
  17139. (org-return-indent)
  17140. (prog1 (org-get-indentation)
  17141. (when (progn (skip-chars-forward " \t") (eolp))
  17142. (delete-region beg (point)))))))
  17143. (bol (progn (skip-chars-backward " \t") (bolp))))
  17144. ;; Insert a newline before environment unless at column zero
  17145. ;; to "escape" the current line. Insert a newline if
  17146. ;; something is one the same line as \end{ENVIRONMENT}.
  17147. (insert
  17148. (concat (unless bol "\n") env
  17149. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17150. (unless (zerop ind)
  17151. (save-excursion
  17152. (goto-char beg)
  17153. (while (< (point) end)
  17154. (unless (eolp) (indent-line-to ind))
  17155. (forward-line))))
  17156. (goto-char beg)
  17157. (forward-line lines)
  17158. (indent-line-to ind)))
  17159. (set-marker beg nil)
  17160. (set-marker end nil)))
  17161. ;;;; LaTeX fragments
  17162. (defun org-inside-LaTeX-fragment-p ()
  17163. "Test if point is inside a LaTeX fragment.
  17164. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17165. sequence appearing also before point.
  17166. Even though the matchers for math are configurable, this function assumes
  17167. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17168. delimiters are skipped when they have been removed by customization.
  17169. The return value is nil, or a cons cell with the delimiter and the
  17170. position of this delimiter.
  17171. This function does a reasonably good job, but can locally be fooled by
  17172. for example currency specifications. For example it will assume being in
  17173. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17174. fragments that are properly closed, but during editing, we have to live
  17175. with the uncertainty caused by missing closing delimiters. This function
  17176. looks only before point, not after."
  17177. (catch 'exit
  17178. (let ((pos (point))
  17179. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17180. (lim (progn
  17181. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17182. (point)))
  17183. dd-on str (start 0) m re)
  17184. (goto-char pos)
  17185. (when dodollar
  17186. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17187. re (nth 1 (assoc "$" org-latex-regexps)))
  17188. (while (string-match re str start)
  17189. (cond
  17190. ((= (match-end 0) (length str))
  17191. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17192. ((= (match-end 0) (- (length str) 5))
  17193. (throw 'exit nil))
  17194. (t (setq start (match-end 0))))))
  17195. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17196. (goto-char pos)
  17197. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17198. (and (match-beginning 2) (throw 'exit nil))
  17199. ;; count $$
  17200. (while (re-search-backward "\\$\\$" lim t)
  17201. (setq dd-on (not dd-on)))
  17202. (goto-char pos)
  17203. (when dd-on (cons "$$" m))))))
  17204. (defun org-inside-latex-macro-p ()
  17205. "Is point inside a LaTeX macro or its arguments?"
  17206. (save-match-data
  17207. (org-in-regexp
  17208. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17209. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17210. "Build an overlay between BEG and END using IMAGE file.
  17211. Argument IMAGETYPE is the extension of the displayed image,
  17212. as a string. It defaults to \"png\"."
  17213. (let ((ov (make-overlay beg end))
  17214. (imagetype (or (intern imagetype) 'png)))
  17215. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17216. (overlay-put ov 'evaporate t)
  17217. (overlay-put ov
  17218. 'modification-hooks
  17219. (list (lambda (o _flag _beg _end &optional _l)
  17220. (delete-overlay o))))
  17221. (overlay-put ov
  17222. 'display
  17223. (list 'image :type imagetype :file image :ascent 'center))))
  17224. (defun org--list-latex-overlays (&optional beg end)
  17225. "List all Org LaTeX overlays in current buffer.
  17226. Limit to overlays between BEG and END when those are provided."
  17227. (cl-remove-if-not
  17228. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17229. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17230. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17231. "Remove all overlays with LaTeX fragment images in current buffer.
  17232. When optional arguments BEG and END are non-nil, remove all
  17233. overlays between them instead. Return a non-nil value when some
  17234. overlays were removed, nil otherwise."
  17235. (let ((overlays (org--list-latex-overlays beg end)))
  17236. (mapc #'delete-overlay overlays)
  17237. overlays))
  17238. (defun org-toggle-latex-fragment (&optional arg)
  17239. "Preview the LaTeX fragment at point, or all locally or globally.
  17240. If the cursor is on a LaTeX fragment, create the image and overlay
  17241. it over the source code, if there is none. Remove it otherwise.
  17242. If there is no fragment at point, display all fragments in the
  17243. current section.
  17244. With prefix ARG, preview or clear image for all fragments in the
  17245. current subtree or in the whole buffer when used before the first
  17246. headline. With a prefix ARG `\\[universal-argument] \
  17247. \\[universal-argument]' preview or clear images
  17248. for all fragments in the buffer."
  17249. (interactive "P")
  17250. (when (display-graphic-p)
  17251. (catch 'exit
  17252. (save-excursion
  17253. (let (beg end msg)
  17254. (cond
  17255. ((or (equal arg '(16))
  17256. (and (equal arg '(4))
  17257. (org-with-limited-levels (org-before-first-heading-p))))
  17258. (if (org-remove-latex-fragment-image-overlays)
  17259. (progn (message "LaTeX fragments images removed from buffer")
  17260. (throw 'exit nil))
  17261. (setq msg "Creating images for buffer...")))
  17262. ((equal arg '(4))
  17263. (org-with-limited-levels (org-back-to-heading t))
  17264. (setq beg (point))
  17265. (setq end (progn (org-end-of-subtree t) (point)))
  17266. (if (org-remove-latex-fragment-image-overlays beg end)
  17267. (progn
  17268. (message "LaTeX fragment images removed from subtree")
  17269. (throw 'exit nil))
  17270. (setq msg "Creating images for subtree...")))
  17271. ((let ((datum (org-element-context)))
  17272. (when (memq (org-element-type datum)
  17273. '(latex-environment latex-fragment))
  17274. (setq beg (org-element-property :begin datum))
  17275. (setq end (org-element-property :end datum))
  17276. (if (org-remove-latex-fragment-image-overlays beg end)
  17277. (progn (message "LaTeX fragment image removed")
  17278. (throw 'exit nil))
  17279. (setq msg "Creating image...")))))
  17280. (t
  17281. (org-with-limited-levels
  17282. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17283. (outline-previous-heading)
  17284. (point)))
  17285. (setq end (progn (outline-next-heading) (point)))
  17286. (if (org-remove-latex-fragment-image-overlays beg end)
  17287. (progn
  17288. (message "LaTeX fragment images removed from section")
  17289. (throw 'exit nil))
  17290. (setq msg "Creating images for section...")))))
  17291. (let ((file (buffer-file-name (buffer-base-buffer))))
  17292. (org-format-latex
  17293. (concat org-preview-latex-image-directory "org-ltximg")
  17294. beg end
  17295. ;; Emacs cannot overlay images from remote hosts. Create
  17296. ;; it in `temporary-file-directory' instead.
  17297. (if (or (not file) (file-remote-p file))
  17298. temporary-file-directory
  17299. default-directory)
  17300. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17301. (message (concat msg "done")))))))
  17302. (defun org-format-latex
  17303. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17304. "Replace LaTeX fragments with links to an image.
  17305. The function takes care of creating the replacement image.
  17306. Only consider fragments between BEG and END when those are
  17307. provided.
  17308. When optional argument OVERLAYS is non-nil, display the image on
  17309. top of the fragment instead of replacing it.
  17310. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17311. Some of the options can be changed using the variable
  17312. `org-format-latex-options', which see."
  17313. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17314. (unless (eq processing-type 'verbatim)
  17315. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17316. (cnt 0)
  17317. checkdir-flag)
  17318. (goto-char (or beg (point-min)))
  17319. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17320. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17321. (overlay-recenter (or end (point-max))))
  17322. (while (re-search-forward math-regexp end t)
  17323. (unless (and overlays
  17324. (eq (get-char-property (point) 'org-overlay-type)
  17325. 'org-latex-overlay))
  17326. (let* ((context (org-element-context))
  17327. (type (org-element-type context)))
  17328. (when (memq type '(latex-environment latex-fragment))
  17329. (let ((block-type (eq type 'latex-environment))
  17330. (value (org-element-property :value context))
  17331. (beg (org-element-property :begin context))
  17332. (end (save-excursion
  17333. (goto-char (org-element-property :end context))
  17334. (skip-chars-backward " \r\t\n")
  17335. (point))))
  17336. (cond
  17337. ((eq processing-type 'mathjax)
  17338. ;; Prepare for MathJax processing.
  17339. (if (not (string-match "\\`\\$\\$?" value))
  17340. (goto-char end)
  17341. (delete-region beg end)
  17342. (if (string= (match-string 0 value) "$$")
  17343. (insert "\\[" (substring value 2 -2) "\\]")
  17344. (insert "\\(" (substring value 1 -1) "\\)"))))
  17345. ((assq processing-type org-preview-latex-process-alist)
  17346. ;; Process to an image.
  17347. (cl-incf cnt)
  17348. (goto-char beg)
  17349. (let* ((processing-info
  17350. (cdr (assq processing-type org-preview-latex-process-alist)))
  17351. (face (face-at-point))
  17352. ;; Get the colors from the face at point.
  17353. (fg
  17354. (let ((color (plist-get org-format-latex-options
  17355. :foreground)))
  17356. (if (and forbuffer (eq color 'auto))
  17357. (face-attribute face :foreground nil 'default)
  17358. color)))
  17359. (bg
  17360. (let ((color (plist-get org-format-latex-options
  17361. :background)))
  17362. (if (and forbuffer (eq color 'auto))
  17363. (face-attribute face :background nil 'default)
  17364. color)))
  17365. (hash (sha1 (prin1-to-string
  17366. (list org-format-latex-header
  17367. org-latex-default-packages-alist
  17368. org-latex-packages-alist
  17369. org-format-latex-options
  17370. forbuffer value fg bg))))
  17371. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17372. (absprefix (expand-file-name prefix dir))
  17373. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17374. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17375. (sep (and block-type "\n\n"))
  17376. (link (concat sep "[[file:" linkfile "]]" sep))
  17377. (options
  17378. (org-combine-plists
  17379. org-format-latex-options
  17380. `(:foreground ,fg :background ,bg))))
  17381. (when msg (message msg cnt))
  17382. (unless checkdir-flag ; Ensure the directory exists.
  17383. (setq checkdir-flag t)
  17384. (let ((todir (file-name-directory absprefix)))
  17385. (unless (file-directory-p todir)
  17386. (make-directory todir t))))
  17387. (unless (file-exists-p movefile)
  17388. (org-create-formula-image
  17389. value movefile options forbuffer processing-type))
  17390. (if overlays
  17391. (progn
  17392. (dolist (o (overlays-in beg end))
  17393. (when (eq (overlay-get o 'org-overlay-type)
  17394. 'org-latex-overlay)
  17395. (delete-overlay o)))
  17396. (org--format-latex-make-overlay beg end movefile imagetype)
  17397. (goto-char end))
  17398. (delete-region beg end)
  17399. (insert
  17400. (org-add-props link
  17401. (list 'org-latex-src
  17402. (replace-regexp-in-string "\"" "" value)
  17403. 'org-latex-src-embed-type
  17404. (if block-type 'paragraph 'character)))))))
  17405. ((eq processing-type 'mathml)
  17406. ;; Process to MathML.
  17407. (unless (org-format-latex-mathml-available-p)
  17408. (user-error "LaTeX to MathML converter not configured"))
  17409. (cl-incf cnt)
  17410. (when msg (message msg cnt))
  17411. (goto-char beg)
  17412. (delete-region beg end)
  17413. (insert (org-format-latex-as-mathml
  17414. value block-type prefix dir)))
  17415. (t
  17416. (error "Unknown conversion process %s for LaTeX fragments"
  17417. processing-type)))))))))))
  17418. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17419. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17420. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17421. sucessful, return the portion between \"<math...> </math>\"
  17422. elements otherwise return nil. When MATHML-FILE is specified,
  17423. write the results in to that file. When invoked as an
  17424. interactive command, prompt for LATEX-FRAG, with initial value
  17425. set to the current active region and echo the results for user
  17426. inspection."
  17427. (interactive (list (let ((frag (when (org-region-active-p)
  17428. (buffer-substring-no-properties
  17429. (region-beginning) (region-end)))))
  17430. (read-string "LaTeX Fragment: " frag nil frag))))
  17431. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17432. (let* ((tmp-in-file
  17433. (let ((file (file-relative-name
  17434. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17435. (write-region latex-frag nil file)
  17436. file))
  17437. (tmp-out-file (file-relative-name
  17438. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17439. (cmd (format-spec
  17440. org-latex-to-mathml-convert-command
  17441. `((?j . ,(and org-latex-to-mathml-jar-file
  17442. (shell-quote-argument
  17443. (expand-file-name
  17444. org-latex-to-mathml-jar-file))))
  17445. (?I . ,(shell-quote-argument tmp-in-file))
  17446. (?i . ,latex-frag)
  17447. (?o . ,(shell-quote-argument tmp-out-file)))))
  17448. mathml shell-command-output)
  17449. (when (called-interactively-p 'any)
  17450. (unless (org-format-latex-mathml-available-p)
  17451. (user-error "LaTeX to MathML converter not configured")))
  17452. (message "Running %s" cmd)
  17453. (setq shell-command-output (shell-command-to-string cmd))
  17454. (setq mathml
  17455. (when (file-readable-p tmp-out-file)
  17456. (with-current-buffer (find-file-noselect tmp-out-file t)
  17457. (goto-char (point-min))
  17458. (when (re-search-forward
  17459. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17460. (regexp-quote
  17461. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17462. nil t)
  17463. (prog1 (match-string 0) (kill-buffer))))))
  17464. (cond
  17465. (mathml
  17466. (setq mathml
  17467. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17468. (when mathml-file
  17469. (write-region mathml nil mathml-file))
  17470. (when (called-interactively-p 'any)
  17471. (message mathml)))
  17472. ((message "LaTeX to MathML conversion failed")
  17473. (message shell-command-output)))
  17474. (delete-file tmp-in-file)
  17475. (when (file-exists-p tmp-out-file)
  17476. (delete-file tmp-out-file))
  17477. mathml))
  17478. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17479. prefix &optional dir)
  17480. "Use `org-create-math-formula' but check local cache first."
  17481. (let* ((absprefix (expand-file-name prefix dir))
  17482. (print-length nil) (print-level nil)
  17483. (formula-id (concat
  17484. "formula-"
  17485. (sha1
  17486. (prin1-to-string
  17487. (list latex-frag
  17488. org-latex-to-mathml-convert-command)))))
  17489. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17490. (formula-cache-dir (file-name-directory formula-cache)))
  17491. (unless (file-directory-p formula-cache-dir)
  17492. (make-directory formula-cache-dir t))
  17493. (unless (file-exists-p formula-cache)
  17494. (org-create-math-formula latex-frag formula-cache))
  17495. (if (file-exists-p formula-cache)
  17496. ;; Successful conversion. Return the link to MathML file.
  17497. (org-add-props
  17498. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17499. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17500. 'org-latex-src-embed-type (if latex-frag-type
  17501. 'paragraph 'character)))
  17502. ;; Failed conversion. Return the LaTeX fragment verbatim
  17503. latex-frag)))
  17504. (defun org--get-display-dpi ()
  17505. "Get the DPI of the display.
  17506. The function assumes that the display has the same pixel width in
  17507. the horizontal and vertical directions."
  17508. (if (display-graphic-p)
  17509. (round (/ (display-pixel-height)
  17510. (/ (display-mm-height) 25.4)))
  17511. (error "Attempt to calculate the dpi of a non-graphic display")))
  17512. (defun org-create-formula-image
  17513. (string tofile options buffer &optional processing-type)
  17514. "Create an image from LaTeX source using external processes.
  17515. The LaTeX STRING is saved to a temporary LaTeX file, then
  17516. converted to an image file by process PROCESSING-TYPE defined in
  17517. `org-preview-latex-process-alist'. A nil value defaults to
  17518. `org-preview-latex-default-process'.
  17519. The generated image file is eventually moved to TOFILE.
  17520. The OPTIONS argument controls the size, foreground color and
  17521. background color of the generated image.
  17522. When BUFFER non-nil, this function is used for LaTeX previewing.
  17523. Otherwise, it is used to deal with LaTeX snippets showed in
  17524. a HTML file."
  17525. (let* ((processing-type (or processing-type
  17526. org-preview-latex-default-process))
  17527. (processing-info
  17528. (cdr (assq processing-type org-preview-latex-process-alist)))
  17529. (programs (plist-get processing-info :programs))
  17530. (error-message (or (plist-get processing-info :message) ""))
  17531. (use-xcolor (plist-get processing-info :use-xcolor))
  17532. (image-input-type (plist-get processing-info :image-input-type))
  17533. (image-output-type (plist-get processing-info :image-output-type))
  17534. (post-clean (or (plist-get processing-info :post-clean)
  17535. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17536. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17537. (latex-header
  17538. (or (plist-get processing-info :latex-header)
  17539. (org-latex-make-preamble
  17540. (org-export-get-environment (org-export-get-backend 'latex))
  17541. org-format-latex-header
  17542. 'snippet)))
  17543. (latex-compiler (plist-get processing-info :latex-compiler))
  17544. (image-converter (plist-get processing-info :image-converter))
  17545. (tmpdir temporary-file-directory)
  17546. (texfilebase (make-temp-name
  17547. (expand-file-name "orgtex" tmpdir)))
  17548. (texfile (concat texfilebase ".tex"))
  17549. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17550. '(1.0 . 1.0)))
  17551. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17552. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17553. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17554. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17555. "Black"))
  17556. (bg (or (plist-get options (if buffer :background :html-background))
  17557. "Transparent"))
  17558. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17559. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17560. (dolist (program programs)
  17561. (org-check-external-command program error-message))
  17562. (if use-xcolor
  17563. (progn (if (eq fg 'default)
  17564. (setq fg (org-latex-color :foreground))
  17565. (setq fg (org-latex-color-format fg)))
  17566. (if (eq bg 'default)
  17567. (setq bg (org-latex-color :background))
  17568. (setq bg (org-latex-color-format
  17569. (if (string= bg "Transparent") "white" bg))))
  17570. (with-temp-file texfile
  17571. (insert latex-header)
  17572. (insert "\n\\begin{document}\n"
  17573. "\\definecolor{fg}{rgb}{" fg "}\n"
  17574. "\\definecolor{bg}{rgb}{" bg "}\n"
  17575. "\n\\pagecolor{bg}\n"
  17576. "\n{\\color{fg}\n"
  17577. string
  17578. "\n}\n"
  17579. "\n\\end{document}\n")))
  17580. (if (eq fg 'default)
  17581. (setq fg (org-dvipng-color :foreground))
  17582. (unless (string= fg "Transparent")
  17583. (setq fg (org-dvipng-color-format fg))))
  17584. (if (eq bg 'default)
  17585. (setq bg (org-dvipng-color :background))
  17586. (unless (string= bg "Transparent")
  17587. (setq bg (org-dvipng-color-format bg))))
  17588. (with-temp-file texfile
  17589. (insert latex-header)
  17590. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17591. (let* ((err-msg (format "Please adjust '%s' part of \
  17592. `org-preview-latex-process-alist'."
  17593. processing-type))
  17594. (image-input-file
  17595. (org-compile-file
  17596. texfile latex-compiler image-input-type err-msg log-buf))
  17597. (image-output-file
  17598. (org-compile-file
  17599. image-input-file image-converter image-output-type err-msg log-buf
  17600. `((?F . ,(shell-quote-argument fg))
  17601. (?B . ,(shell-quote-argument bg))
  17602. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17603. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17604. (copy-file image-output-file tofile 'replace)
  17605. (dolist (e post-clean)
  17606. (when (file-exists-p (concat texfilebase e))
  17607. (delete-file (concat texfilebase e))))
  17608. image-output-file)))
  17609. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17610. "Fill a LaTeX header template TPL.
  17611. In the template, the following place holders will be recognized:
  17612. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17613. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17614. [PACKAGES] \\usepackage statements for PKG
  17615. [NO-PACKAGES] do not include PKG
  17616. [EXTRA] the string EXTRA
  17617. [NO-EXTRA] do not include EXTRA
  17618. For backward compatibility, if both the positive and the negative place
  17619. holder is missing, the positive one (without the \"NO-\") will be
  17620. assumed to be present at the end of the template.
  17621. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17622. EXTRA is a string.
  17623. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17624. (let (rpl (end ""))
  17625. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17626. (setq rpl (if (or (match-end 1) (not def-pkg))
  17627. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17628. tpl (replace-match rpl t t tpl))
  17629. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17630. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17631. (setq rpl (if (or (match-end 1) (not pkg))
  17632. "" (org-latex-packages-to-string pkg snippets-p t))
  17633. tpl (replace-match rpl t t tpl))
  17634. (when pkg (setq end
  17635. (concat end "\n"
  17636. (org-latex-packages-to-string pkg snippets-p)))))
  17637. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17638. (setq rpl (if (or (match-end 1) (not extra))
  17639. "" (concat extra "\n"))
  17640. tpl (replace-match rpl t t tpl))
  17641. (when (and extra (string-match "\\S-" extra))
  17642. (setq end (concat end "\n" extra))))
  17643. (if (string-match "\\S-" end)
  17644. (concat tpl "\n" end)
  17645. tpl)))
  17646. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17647. "Turn an alist of packages into a string with the \\usepackage macros."
  17648. (setq pkg (mapconcat (lambda(p)
  17649. (cond
  17650. ((stringp p) p)
  17651. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17652. (format "%% Package %s omitted" (cadr p)))
  17653. ((equal "" (car p))
  17654. (format "\\usepackage{%s}" (cadr p)))
  17655. (t
  17656. (format "\\usepackage[%s]{%s}"
  17657. (car p) (cadr p)))))
  17658. pkg
  17659. "\n"))
  17660. (if newline (concat pkg "\n") pkg))
  17661. (defun org-dvipng-color (attr)
  17662. "Return a RGB color specification for dvipng."
  17663. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17664. (defun org-dvipng-color-format (color-name)
  17665. "Convert COLOR-NAME to a RGB color value for dvipng."
  17666. (apply #'format "rgb %s %s %s"
  17667. (mapcar 'org-normalize-color
  17668. (color-values color-name))))
  17669. (defun org-latex-color (attr)
  17670. "Return a RGB color for the LaTeX color package."
  17671. (org-latex-color-format (face-attribute 'default attr nil)))
  17672. (defun org-latex-color-format (color-name)
  17673. "Convert COLOR-NAME to a RGB color value."
  17674. (apply #'format "%s,%s,%s"
  17675. (mapcar 'org-normalize-color
  17676. (color-values color-name))))
  17677. (defun org-normalize-color (value)
  17678. "Return string to be used as color value for an RGB component."
  17679. (format "%g" (/ value 65535.0)))
  17680. ;; Image display
  17681. (defvar-local org-inline-image-overlays nil)
  17682. (defun org-toggle-inline-images (&optional include-linked)
  17683. "Toggle the display of inline images.
  17684. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17685. (interactive "P")
  17686. (if org-inline-image-overlays
  17687. (progn
  17688. (org-remove-inline-images)
  17689. (when (called-interactively-p 'interactive)
  17690. (message "Inline image display turned off")))
  17691. (org-display-inline-images include-linked)
  17692. (when (called-interactively-p 'interactive)
  17693. (message (if org-inline-image-overlays
  17694. (format "%d images displayed inline"
  17695. (length org-inline-image-overlays))
  17696. "No images to display inline")))))
  17697. (defun org-redisplay-inline-images ()
  17698. "Refresh the display of inline images."
  17699. (interactive)
  17700. (if (not org-inline-image-overlays)
  17701. (org-toggle-inline-images)
  17702. (org-toggle-inline-images)
  17703. (org-toggle-inline-images)))
  17704. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17705. "Display inline images.
  17706. An inline image is a link which follows either of these
  17707. conventions:
  17708. 1. Its path is a file with an extension matching return value
  17709. from `image-file-name-regexp' and it has no contents.
  17710. 2. Its description consists in a single link of the previous
  17711. type.
  17712. When optional argument INCLUDE-LINKED is non-nil, also links with
  17713. a text description part will be inlined. This can be nice for
  17714. a quick look at those images, but it does not reflect what
  17715. exported files will look like.
  17716. When optional argument REFRESH is non-nil, refresh existing
  17717. images between BEG and END. This will create new image displays
  17718. only if necessary. BEG and END default to the buffer
  17719. boundaries."
  17720. (interactive "P")
  17721. (when (display-graphic-p)
  17722. (unless refresh
  17723. (org-remove-inline-images)
  17724. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17725. (org-with-wide-buffer
  17726. (goto-char (or beg (point-min)))
  17727. (let ((case-fold-search t)
  17728. (file-extension-re (image-file-name-regexp)))
  17729. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17730. (let ((link (save-match-data (org-element-context))))
  17731. ;; Check if we're at an inline image.
  17732. (when (and (equal (org-element-property :type link) "file")
  17733. (or include-linked
  17734. (not (org-element-property :contents-begin link)))
  17735. (let ((parent (org-element-property :parent link)))
  17736. (or (not (eq (org-element-type parent) 'link))
  17737. (not (cdr (org-element-contents parent)))))
  17738. (string-match-p file-extension-re
  17739. (org-element-property :path link)))
  17740. (let ((file (expand-file-name
  17741. (org-link-unescape
  17742. (org-element-property :path link)))))
  17743. (when (file-exists-p file)
  17744. (let ((width
  17745. ;; Apply `org-image-actual-width' specifications.
  17746. (cond
  17747. ((not (image-type-available-p 'imagemagick)) nil)
  17748. ((eq org-image-actual-width t) nil)
  17749. ((listp org-image-actual-width)
  17750. (or
  17751. ;; First try to find a width among
  17752. ;; attributes associated to the paragraph
  17753. ;; containing link.
  17754. (let ((paragraph
  17755. (let ((e link))
  17756. (while (and (setq e (org-element-property
  17757. :parent e))
  17758. (not (eq (org-element-type e)
  17759. 'paragraph))))
  17760. e)))
  17761. (when paragraph
  17762. (save-excursion
  17763. (goto-char (org-element-property :begin paragraph))
  17764. (when
  17765. (re-search-forward
  17766. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17767. (org-element-property
  17768. :post-affiliated paragraph)
  17769. t)
  17770. (string-to-number (match-string 1))))))
  17771. ;; Otherwise, fall-back to provided number.
  17772. (car org-image-actual-width)))
  17773. ((numberp org-image-actual-width)
  17774. org-image-actual-width)))
  17775. (old (get-char-property-and-overlay
  17776. (org-element-property :begin link)
  17777. 'org-image-overlay)))
  17778. (if (and (car-safe old) refresh)
  17779. (image-refresh (overlay-get (cdr old) 'display))
  17780. (let ((image (create-image file
  17781. (and width 'imagemagick)
  17782. nil
  17783. :width width)))
  17784. (when image
  17785. (let* ((link
  17786. ;; If inline image is the description
  17787. ;; of another link, be sure to
  17788. ;; consider the latter as the one to
  17789. ;; apply the overlay on.
  17790. (let ((parent
  17791. (org-element-property :parent link)))
  17792. (if (eq (org-element-type parent) 'link)
  17793. parent
  17794. link)))
  17795. (ov (make-overlay
  17796. (org-element-property :begin link)
  17797. (progn
  17798. (goto-char
  17799. (org-element-property :end link))
  17800. (skip-chars-backward " \t")
  17801. (point)))))
  17802. (overlay-put ov 'display image)
  17803. (overlay-put ov 'face 'default)
  17804. (overlay-put ov 'org-image-overlay t)
  17805. (overlay-put
  17806. ov 'modification-hooks
  17807. (list 'org-display-inline-remove-overlay))
  17808. (push ov org-inline-image-overlays)))))))))))))))
  17809. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17810. "Remove inline-display overlay if a corresponding region is modified."
  17811. (let ((inhibit-modification-hooks t))
  17812. (when (and ov after)
  17813. (delete ov org-inline-image-overlays)
  17814. (delete-overlay ov))))
  17815. (defun org-remove-inline-images ()
  17816. "Remove inline display of images."
  17817. (interactive)
  17818. (mapc #'delete-overlay org-inline-image-overlays)
  17819. (setq org-inline-image-overlays nil))
  17820. ;;;; Key bindings
  17821. ;; Outline functions from `outline-mode-prefix-map'
  17822. ;; that can be remapped in Org:
  17823. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17824. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17825. (define-key org-mode-map [remap outline-forward-same-level]
  17826. 'org-forward-heading-same-level)
  17827. (define-key org-mode-map [remap outline-backward-same-level]
  17828. 'org-backward-heading-same-level)
  17829. (define-key org-mode-map [remap outline-show-branches]
  17830. 'org-kill-note-or-show-branches)
  17831. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17832. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17833. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17834. (define-key org-mode-map [remap outline-next-visible-heading]
  17835. 'org-next-visible-heading)
  17836. (define-key org-mode-map [remap outline-previous-visible-heading]
  17837. 'org-previous-visible-heading)
  17838. (define-key org-mode-map [remap show-children] 'org-show-children)
  17839. ;; Outline functions from `outline-mode-prefix-map' that can not
  17840. ;; be remapped in Org:
  17841. ;; - the column "key binding" shows whether the Outline function is still
  17842. ;; available in Org mode on the same key that it has been bound to in
  17843. ;; Outline mode:
  17844. ;; - "overridden": key used for a different functionality in Org mode
  17845. ;; - else: key still bound to the same Outline function in Org mode
  17846. ;; | Outline function | key binding | Org replacement |
  17847. ;; |------------------------------------+-------------+--------------------------|
  17848. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17849. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17850. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17851. ;; | `show-entry' | overridden | no replacement |
  17852. ;; | `show-branches' | `C-c C-k' | still same function |
  17853. ;; | `show-subtree' | overridden | visibility cycling |
  17854. ;; | `show-all' | overridden | no replacement |
  17855. ;; | `hide-subtree' | overridden | visibility cycling |
  17856. ;; | `hide-body' | overridden | no replacement |
  17857. ;; | `hide-entry' | overridden | visibility cycling |
  17858. ;; | `hide-leaves' | overridden | no replacement |
  17859. ;; | `hide-sublevels' | overridden | no replacement |
  17860. ;; | `hide-other' | overridden | no replacement |
  17861. ;; Make `C-c C-x' a prefix key
  17862. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17863. ;; TAB key with modifiers
  17864. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17865. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17866. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17867. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17868. ;; The following line is necessary under Suse GNU/Linux
  17869. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17870. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17871. (define-key org-mode-map [backtab] 'org-shifttab)
  17872. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17873. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17874. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  17875. ;; Cursor keys with modifiers
  17876. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17877. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17878. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17879. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17880. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17881. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17882. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17883. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17884. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17885. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17886. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17887. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17888. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17889. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17890. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17891. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17892. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17893. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17894. ;; Babel keys
  17895. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17896. (dolist (pair org-babel-key-bindings)
  17897. (define-key org-babel-map (car pair) (cdr pair)))
  17898. ;;; Extra keys for tty access.
  17899. ;; We only set them when really needed because otherwise the
  17900. ;; menus don't show the simple keys
  17901. (when (or org-use-extra-keys (not window-system))
  17902. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17903. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17904. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17905. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17906. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17907. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17908. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17909. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17910. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17911. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17912. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17913. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17914. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17915. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17916. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17917. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17918. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17919. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17920. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17921. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17922. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17923. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17924. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17925. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17926. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17927. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17928. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17929. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17930. ;; All the other keys
  17931. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17932. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17933. (if (boundp 'narrow-map)
  17934. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17935. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17936. (if (boundp 'narrow-map)
  17937. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17938. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17939. (if (boundp 'narrow-map)
  17940. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17941. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17942. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17943. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17944. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17945. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17946. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17947. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17948. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17949. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17950. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17951. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17952. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17953. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17954. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17955. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17956. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17957. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17958. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17959. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17960. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17961. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17962. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17963. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17964. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17965. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17966. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17967. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17968. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17969. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17970. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17971. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17972. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17973. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17974. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17975. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17976. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17977. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17978. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17979. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17980. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17981. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17982. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17983. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17984. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17985. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17986. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17987. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17988. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17989. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17990. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17991. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17992. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17993. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17994. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17995. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17996. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17997. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17998. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17999. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18000. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18001. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18002. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18003. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18004. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18005. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18006. (org-defkey org-mode-map "\C-m" 'org-return)
  18007. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18008. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18009. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18010. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18011. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18012. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18013. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18014. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18015. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18016. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18017. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18018. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18019. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18020. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18021. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18022. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18023. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18024. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18025. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18026. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18027. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18028. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18029. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18030. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18031. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18032. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18033. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18034. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18035. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18036. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18037. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18038. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18039. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18040. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18041. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18042. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18043. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18044. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18045. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18046. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18047. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18048. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18049. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18050. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18051. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18052. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18053. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18054. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18055. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18056. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18057. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18058. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18059. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18060. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18061. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18062. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18063. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18064. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18065. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18066. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18067. (defconst org-speed-commands-default
  18068. '(
  18069. ("Outline Navigation")
  18070. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18071. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18072. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18073. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18074. ("F" . org-next-block)
  18075. ("B" . org-previous-block)
  18076. ("u" . (org-speed-move-safe 'outline-up-heading))
  18077. ("j" . org-goto)
  18078. ("g" . (org-refile t))
  18079. ("Outline Visibility")
  18080. ("c" . org-cycle)
  18081. ("C" . org-shifttab)
  18082. (" " . org-display-outline-path)
  18083. ("s" . org-narrow-to-subtree)
  18084. ("=" . org-columns)
  18085. ("Outline Structure Editing")
  18086. ("U" . org-metaup)
  18087. ("D" . org-metadown)
  18088. ("r" . org-metaright)
  18089. ("l" . org-metaleft)
  18090. ("R" . org-shiftmetaright)
  18091. ("L" . org-shiftmetaleft)
  18092. ("i" . (progn (forward-char 1) (call-interactively
  18093. 'org-insert-heading-respect-content)))
  18094. ("^" . org-sort)
  18095. ("w" . org-refile)
  18096. ("a" . org-archive-subtree-default-with-confirmation)
  18097. ("@" . org-mark-subtree)
  18098. ("#" . org-toggle-comment)
  18099. ("Clock Commands")
  18100. ("I" . org-clock-in)
  18101. ("O" . org-clock-out)
  18102. ("Meta Data Editing")
  18103. ("t" . org-todo)
  18104. ("," . (org-priority))
  18105. ("0" . (org-priority ?\ ))
  18106. ("1" . (org-priority ?A))
  18107. ("2" . (org-priority ?B))
  18108. ("3" . (org-priority ?C))
  18109. (":" . org-set-tags-command)
  18110. ("e" . org-set-effort)
  18111. ("E" . org-inc-effort)
  18112. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18113. (org-entry-put (point) "APPT_WARNTIME" m)))
  18114. ("Agenda Views etc")
  18115. ("v" . org-agenda)
  18116. ("/" . org-sparse-tree)
  18117. ("Misc")
  18118. ("o" . org-open-at-point)
  18119. ("?" . org-speed-command-help)
  18120. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18121. (">" . (org-agenda-remove-restriction-lock))
  18122. )
  18123. "The default speed commands.")
  18124. (defun org-print-speed-command (e)
  18125. (if (> (length (car e)) 1)
  18126. (progn
  18127. (princ "\n")
  18128. (princ (car e))
  18129. (princ "\n")
  18130. (princ (make-string (length (car e)) ?-))
  18131. (princ "\n"))
  18132. (princ (car e))
  18133. (princ " ")
  18134. (if (symbolp (cdr e))
  18135. (princ (symbol-name (cdr e)))
  18136. (prin1 (cdr e)))
  18137. (princ "\n")))
  18138. (defun org-speed-command-help ()
  18139. "Show the available speed commands."
  18140. (interactive)
  18141. (if (not org-use-speed-commands)
  18142. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18143. (with-output-to-temp-buffer "*Help*"
  18144. (princ "User-defined Speed commands\n===========================\n")
  18145. (mapc #'org-print-speed-command org-speed-commands-user)
  18146. (princ "\n")
  18147. (princ "Built-in Speed commands\n=======================\n")
  18148. (mapc #'org-print-speed-command org-speed-commands-default))
  18149. (with-current-buffer "*Help*"
  18150. (setq truncate-lines t))))
  18151. (defun org-speed-move-safe (cmd)
  18152. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18153. If not, return to the original position and throw an error."
  18154. (interactive)
  18155. (let ((pos (point)))
  18156. (call-interactively cmd)
  18157. (unless (and (bolp) (org-at-heading-p))
  18158. (goto-char pos)
  18159. (error "Boundary reached while executing %s" cmd))))
  18160. (defvar org-self-insert-command-undo-counter 0)
  18161. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18162. (defvar org-speed-command nil)
  18163. (defun org-speed-command-activate (keys)
  18164. "Hook for activating single-letter speed commands.
  18165. `org-speed-commands-default' specifies a minimal command set.
  18166. Use `org-speed-commands-user' for further customization."
  18167. (when (or (and (bolp) (looking-at org-outline-regexp))
  18168. (and (functionp org-use-speed-commands)
  18169. (funcall org-use-speed-commands)))
  18170. (cdr (assoc keys (append org-speed-commands-user
  18171. org-speed-commands-default)))))
  18172. (defun org-babel-speed-command-activate (keys)
  18173. "Hook for activating single-letter code block commands."
  18174. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18175. (cdr (assoc keys org-babel-key-bindings))))
  18176. (defcustom org-speed-command-hook
  18177. '(org-speed-command-activate org-babel-speed-command-activate)
  18178. "Hook for activating speed commands at strategic locations.
  18179. Hook functions are called in sequence until a valid handler is
  18180. found.
  18181. Each hook takes a single argument, a user-pressed command key
  18182. which is also a `self-insert-command' from the global map.
  18183. Within the hook, examine the cursor position and the command key
  18184. and return nil or a valid handler as appropriate. Handler could
  18185. be one of an interactive command, a function, or a form.
  18186. Set `org-use-speed-commands' to non-nil value to enable this
  18187. hook. The default setting is `org-speed-command-activate'."
  18188. :group 'org-structure
  18189. :version "24.1"
  18190. :type 'hook)
  18191. (defun org-self-insert-command (N)
  18192. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18193. If the cursor is in a table looking at whitespace, the whitespace is
  18194. overwritten, and the table is not marked as requiring realignment."
  18195. (interactive "p")
  18196. (org-check-before-invisible-edit 'insert)
  18197. (cond
  18198. ((and org-use-speed-commands
  18199. (let ((kv (this-command-keys-vector)))
  18200. (setq org-speed-command
  18201. (run-hook-with-args-until-success
  18202. 'org-speed-command-hook
  18203. (make-string 1 (aref kv (1- (length kv))))))))
  18204. (cond
  18205. ((commandp org-speed-command)
  18206. (setq this-command org-speed-command)
  18207. (call-interactively org-speed-command))
  18208. ((functionp org-speed-command)
  18209. (funcall org-speed-command))
  18210. ((and org-speed-command (listp org-speed-command))
  18211. (eval org-speed-command))
  18212. (t (let (org-use-speed-commands)
  18213. (call-interactively 'org-self-insert-command)))))
  18214. ((and
  18215. (org-at-table-p)
  18216. (progn
  18217. ;; Check if we blank the field, and if that triggers align.
  18218. (and (featurep 'org-table) org-table-auto-blank-field
  18219. (memq last-command
  18220. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18221. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18222. ;; Got extra space, this field does not determine
  18223. ;; column width.
  18224. (let (org-table-may-need-update) (org-table-blank-field))
  18225. ;; No extra space, this field may determine column
  18226. ;; width.
  18227. (org-table-blank-field)))
  18228. t)
  18229. (eq N 1)
  18230. (looking-at "[^|\n]* \\( \\)|"))
  18231. ;; There is room for insertion without re-aligning the table.
  18232. (delete-region (match-beginning 1) (match-end 1))
  18233. (self-insert-command N))
  18234. (t
  18235. (setq org-table-may-need-update t)
  18236. (self-insert-command N)
  18237. (org-fix-tags-on-the-fly)
  18238. (when org-self-insert-cluster-for-undo
  18239. (if (not (eq last-command 'org-self-insert-command))
  18240. (setq org-self-insert-command-undo-counter 1)
  18241. (if (>= org-self-insert-command-undo-counter 20)
  18242. (setq org-self-insert-command-undo-counter 1)
  18243. (and (> org-self-insert-command-undo-counter 0)
  18244. buffer-undo-list (listp buffer-undo-list)
  18245. (not (cadr buffer-undo-list)) ; remove nil entry
  18246. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18247. (setq org-self-insert-command-undo-counter
  18248. (1+ org-self-insert-command-undo-counter))))))))
  18249. (defun org-check-before-invisible-edit (kind)
  18250. "Check is editing if kind KIND would be dangerous with invisible text around.
  18251. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18252. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18253. (when (and org-catch-invisible-edits
  18254. (or (not (boundp 'visible-mode)) (not visible-mode))
  18255. (or (get-char-property (point) 'invisible)
  18256. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18257. ;; OK, we need to take a closer look
  18258. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18259. (invisible-before-point (unless (bobp) (get-char-property
  18260. (1- (point)) 'invisible)))
  18261. (border-and-ok-direction
  18262. (or
  18263. ;; Check if we are acting predictably before invisible text
  18264. (and invisible-at-point (not invisible-before-point)
  18265. (memq kind '(insert delete-backward)))
  18266. ;; Check if we are acting predictably after invisible text
  18267. ;; This works not well, and I have turned it off. It seems
  18268. ;; better to always show and stop after invisible text.
  18269. ;; (and (not invisible-at-point) invisible-before-point
  18270. ;; (memq kind '(insert delete)))
  18271. )))
  18272. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18273. (memq invisible-before-point '(outline org-hide-block t)))
  18274. (when (eq org-catch-invisible-edits 'error)
  18275. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18276. (if (and org-custom-properties-overlays
  18277. (y-or-n-p "Display invisible properties in this buffer? "))
  18278. (org-toggle-custom-properties-visibility)
  18279. ;; Make the area visible
  18280. (save-excursion
  18281. (when invisible-before-point
  18282. (goto-char (previous-single-char-property-change
  18283. (point) 'invisible)))
  18284. (outline-show-subtree))
  18285. (cond
  18286. ((eq org-catch-invisible-edits 'show)
  18287. ;; That's it, we do the edit after showing
  18288. (message
  18289. "Unfolding invisible region around point before editing")
  18290. (sit-for 1))
  18291. ((and (eq org-catch-invisible-edits 'smart)
  18292. border-and-ok-direction)
  18293. (message "Unfolding invisible region around point before editing"))
  18294. (t
  18295. ;; Don't do the edit, make the user repeat it in full visibility
  18296. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18297. (defun org-fix-tags-on-the-fly ()
  18298. "Align tags in headline at point.
  18299. Unlike to `org-set-tags', it ignores region and sorting."
  18300. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18301. (org-at-heading-p))
  18302. (let ((org-ignore-region t)
  18303. (org-tags-sort-function nil))
  18304. (org-set-tags nil t))))
  18305. (defun org-delete-backward-char (N)
  18306. "Like `delete-backward-char', insert whitespace at field end in tables.
  18307. When deleting backwards, in tables this function will insert whitespace in
  18308. front of the next \"|\" separator, to keep the table aligned. The table will
  18309. still be marked for re-alignment if the field did fill the entire column,
  18310. because, in this case the deletion might narrow the column."
  18311. (interactive "p")
  18312. (save-match-data
  18313. (org-check-before-invisible-edit 'delete-backward)
  18314. (if (and (org-at-table-p)
  18315. (eq N 1)
  18316. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18317. (looking-at ".*?|"))
  18318. (let ((pos (point))
  18319. (noalign (looking-at "[^|\n\r]* |"))
  18320. (c org-table-may-need-update))
  18321. (backward-delete-char N)
  18322. (unless overwrite-mode
  18323. (skip-chars-forward "^|")
  18324. (insert " ")
  18325. (goto-char (1- pos)))
  18326. ;; noalign: if there were two spaces at the end, this field
  18327. ;; does not determine the width of the column.
  18328. (when noalign (setq org-table-may-need-update c)))
  18329. (backward-delete-char N)
  18330. (org-fix-tags-on-the-fly))))
  18331. (defun org-delete-char (N)
  18332. "Like `delete-char', but insert whitespace at field end in tables.
  18333. When deleting characters, in tables this function will insert whitespace in
  18334. front of the next \"|\" separator, to keep the table aligned. The table will
  18335. still be marked for re-alignment if the field did fill the entire column,
  18336. because, in this case the deletion might narrow the column."
  18337. (interactive "p")
  18338. (save-match-data
  18339. (org-check-before-invisible-edit 'delete)
  18340. (if (and (org-at-table-p)
  18341. (not (bolp))
  18342. (not (= (char-after) ?|))
  18343. (eq N 1))
  18344. (if (looking-at ".*?|")
  18345. (let ((pos (point))
  18346. (noalign (looking-at "[^|\n\r]* |"))
  18347. (c org-table-may-need-update))
  18348. (replace-match
  18349. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18350. (goto-char pos)
  18351. ;; noalign: if there were two spaces at the end, this field
  18352. ;; does not determine the width of the column.
  18353. (when noalign (setq org-table-may-need-update c)))
  18354. (delete-char N))
  18355. (delete-char N)
  18356. (org-fix-tags-on-the-fly))))
  18357. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18358. (put 'org-self-insert-command 'delete-selection
  18359. (lambda ()
  18360. (not (run-hook-with-args-until-success
  18361. 'self-insert-uses-region-functions))))
  18362. (put 'orgtbl-self-insert-command 'delete-selection
  18363. (lambda ()
  18364. (not (run-hook-with-args-until-success
  18365. 'self-insert-uses-region-functions))))
  18366. (put 'org-delete-char 'delete-selection 'supersede)
  18367. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18368. (put 'org-yank 'delete-selection 'yank)
  18369. ;; Make `flyspell-mode' delay after some commands
  18370. (put 'org-self-insert-command 'flyspell-delayed t)
  18371. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18372. (put 'org-delete-char 'flyspell-delayed t)
  18373. (put 'org-delete-backward-char 'flyspell-delayed t)
  18374. ;; Make pabbrev-mode expand after Org mode commands
  18375. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18376. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18377. (defun org-remap (map &rest commands)
  18378. "In MAP, remap the functions given in COMMANDS.
  18379. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18380. (let (new old)
  18381. (while commands
  18382. (setq old (pop commands) new (pop commands))
  18383. (org-defkey map (vector 'remap old) new))))
  18384. (defun org-transpose-words ()
  18385. "Transpose words for Org.
  18386. This uses the `org-mode-transpose-word-syntax-table' syntax
  18387. table, which interprets characters in `org-emphasis-alist' as
  18388. word constituents."
  18389. (interactive)
  18390. (with-syntax-table org-mode-transpose-word-syntax-table
  18391. (call-interactively 'transpose-words)))
  18392. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18393. (when (eq org-enable-table-editor 'optimized)
  18394. ;; If the user wants maximum table support, we need to hijack
  18395. ;; some standard editing functions
  18396. (org-remap org-mode-map
  18397. 'self-insert-command 'org-self-insert-command
  18398. 'delete-char 'org-delete-char
  18399. 'delete-backward-char 'org-delete-backward-char)
  18400. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18401. (defvar org-ctrl-c-ctrl-c-hook nil
  18402. "Hook for functions attaching themselves to `C-c C-c'.
  18403. This can be used to add additional functionality to the C-c C-c
  18404. key which executes context-dependent commands. This hook is run
  18405. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18406. run after the last test.
  18407. Each function will be called with no arguments. The function
  18408. must check if the context is appropriate for it to act. If yes,
  18409. it should do its thing and then return a non-nil value. If the
  18410. context is wrong, just do nothing and return nil.")
  18411. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18412. "Hook for functions attaching themselves to `C-c C-c'.
  18413. This can be used to add additional functionality to the C-c C-c
  18414. key which executes context-dependent commands. This hook is run
  18415. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18416. before the first test.
  18417. Each function will be called with no arguments. The function
  18418. must check if the context is appropriate for it to act. If yes,
  18419. it should do its thing and then return a non-nil value. If the
  18420. context is wrong, just do nothing and return nil.")
  18421. (defvar org-tab-first-hook nil
  18422. "Hook for functions to attach themselves to TAB.
  18423. See `org-ctrl-c-ctrl-c-hook' for more information.
  18424. This hook runs as the first action when TAB is pressed, even before
  18425. `org-cycle' messes around with the `outline-regexp' to cater for
  18426. inline tasks and plain list item folding.
  18427. If any function in this hook returns t, any other actions that
  18428. would have been caused by TAB (such as table field motion or visibility
  18429. cycling) will not occur.")
  18430. (defvar org-tab-after-check-for-table-hook nil
  18431. "Hook for functions to attach themselves to TAB.
  18432. See `org-ctrl-c-ctrl-c-hook' for more information.
  18433. This hook runs after it has been established that the cursor is not in a
  18434. table, but before checking if the cursor is in a headline or if global cycling
  18435. should be done.
  18436. If any function in this hook returns t, not other actions like visibility
  18437. cycling will be done.")
  18438. (defvar org-tab-after-check-for-cycling-hook nil
  18439. "Hook for functions to attach themselves to TAB.
  18440. See `org-ctrl-c-ctrl-c-hook' for more information.
  18441. This hook runs after it has been established that not table field motion and
  18442. not visibility should be done because of current context. This is probably
  18443. the place where a package like yasnippets can hook in.")
  18444. (defvar org-tab-before-tab-emulation-hook nil
  18445. "Hook for functions to attach themselves to TAB.
  18446. See `org-ctrl-c-ctrl-c-hook' for more information.
  18447. This hook runs after every other options for TAB have been exhausted, but
  18448. before indentation and \t insertion takes place.")
  18449. (defvar org-metaleft-hook nil
  18450. "Hook for functions attaching themselves to `M-left'.
  18451. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18452. (defvar org-metaright-hook nil
  18453. "Hook for functions attaching themselves to `M-right'.
  18454. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18455. (defvar org-metaup-hook nil
  18456. "Hook for functions attaching themselves to `M-up'.
  18457. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18458. (defvar org-metadown-hook nil
  18459. "Hook for functions attaching themselves to `M-down'.
  18460. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18461. (defvar org-shiftmetaleft-hook nil
  18462. "Hook for functions attaching themselves to `M-S-left'.
  18463. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18464. (defvar org-shiftmetaright-hook nil
  18465. "Hook for functions attaching themselves to `M-S-right'.
  18466. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18467. (defvar org-shiftmetaup-hook nil
  18468. "Hook for functions attaching themselves to `M-S-up'.
  18469. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18470. (defvar org-shiftmetadown-hook nil
  18471. "Hook for functions attaching themselves to `M-S-down'.
  18472. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18473. (defvar org-metareturn-hook nil
  18474. "Hook for functions attaching themselves to `M-RET'.
  18475. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18476. (defvar org-shiftup-hook nil
  18477. "Hook for functions attaching themselves to `S-up'.
  18478. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18479. (defvar org-shiftup-final-hook nil
  18480. "Hook for functions attaching themselves to `S-up'.
  18481. This one runs after all other options except shift-select have been excluded.
  18482. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18483. (defvar org-shiftdown-hook nil
  18484. "Hook for functions attaching themselves to `S-down'.
  18485. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18486. (defvar org-shiftdown-final-hook nil
  18487. "Hook for functions attaching themselves to `S-down'.
  18488. This one runs after all other options except shift-select have been excluded.
  18489. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18490. (defvar org-shiftleft-hook nil
  18491. "Hook for functions attaching themselves to `S-left'.
  18492. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18493. (defvar org-shiftleft-final-hook nil
  18494. "Hook for functions attaching themselves to `S-left'.
  18495. This one runs after all other options except shift-select have been excluded.
  18496. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18497. (defvar org-shiftright-hook nil
  18498. "Hook for functions attaching themselves to `S-right'.
  18499. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18500. (defvar org-shiftright-final-hook nil
  18501. "Hook for functions attaching themselves to `S-right'.
  18502. This one runs after all other options except shift-select have been excluded.
  18503. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18504. (defun org-modifier-cursor-error ()
  18505. "Throw an error, a modified cursor command was applied in wrong context."
  18506. (user-error "This command is active in special context like tables, headlines or items"))
  18507. (defun org-shiftselect-error ()
  18508. "Throw an error because Shift-Cursor command was applied in wrong context."
  18509. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18510. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18511. (user-error "This command works only in special context like headlines or timestamps")))
  18512. (defun org-call-for-shift-select (cmd)
  18513. (let ((this-command-keys-shift-translated t))
  18514. (call-interactively cmd)))
  18515. (defun org-shifttab (&optional arg)
  18516. "Global visibility cycling or move to previous table field.
  18517. Call `org-table-previous-field' within a table.
  18518. When ARG is nil, cycle globally through visibility states.
  18519. When ARG is a numeric prefix, show contents of this level."
  18520. (interactive "P")
  18521. (cond
  18522. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18523. ((integerp arg)
  18524. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18525. (message "Content view to level: %d" arg)
  18526. (org-content (prefix-numeric-value arg2))
  18527. (org-cycle-show-empty-lines t)
  18528. (setq org-cycle-global-status 'overview)))
  18529. (t (call-interactively 'org-global-cycle))))
  18530. (defun org-shiftmetaleft ()
  18531. "Promote subtree or delete table column.
  18532. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18533. `org-table-delete-column', depending on context. See the
  18534. individual commands for more information."
  18535. (interactive)
  18536. (cond
  18537. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18538. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18539. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18540. ((if (not (org-region-active-p)) (org-at-item-p)
  18541. (save-excursion (goto-char (region-beginning))
  18542. (org-at-item-p)))
  18543. (call-interactively 'org-outdent-item-tree))
  18544. (t (org-modifier-cursor-error))))
  18545. (defun org-shiftmetaright ()
  18546. "Demote subtree or insert table column.
  18547. Calls `org-demote-subtree', `org-indent-item-tree', or
  18548. `org-table-insert-column', depending on context. See the
  18549. individual commands for more information."
  18550. (interactive)
  18551. (cond
  18552. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18553. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18554. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18555. ((if (not (org-region-active-p)) (org-at-item-p)
  18556. (save-excursion (goto-char (region-beginning))
  18557. (org-at-item-p)))
  18558. (call-interactively 'org-indent-item-tree))
  18559. (t (org-modifier-cursor-error))))
  18560. (defun org-shiftmetaup (&optional _arg)
  18561. "Drag the line at point up.
  18562. In a table, kill the current row.
  18563. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18564. but also adjust the previous clocked item in the clock history.
  18565. Everywhere else, drag the line at point up."
  18566. (interactive "P")
  18567. (cond
  18568. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18569. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18570. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18571. (call-interactively 'org-timestamp-up)))
  18572. (t (call-interactively 'org-drag-line-backward))))
  18573. (defun org-shiftmetadown (&optional _arg)
  18574. "Drag the line at point down.
  18575. In a table, insert an empty row at the current line.
  18576. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18577. but also adjust the previous clocked item in the clock history.
  18578. Everywhere else, drag the line at point down."
  18579. (interactive "P")
  18580. (cond
  18581. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18582. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18583. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18584. (call-interactively 'org-timestamp-down)))
  18585. (t (call-interactively 'org-drag-line-forward))))
  18586. (defsubst org-hidden-tree-error ()
  18587. (user-error
  18588. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18589. (defun org-metaleft (&optional _arg)
  18590. "Promote heading, list item at point or move table column left.
  18591. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18592. depending on context. With no specific context, calls the Emacs
  18593. default `backward-word'. See the individual commands for more
  18594. information.
  18595. This function runs the hook `org-metaleft-hook' as a first step,
  18596. and returns at first non-nil value."
  18597. (interactive "P")
  18598. (cond
  18599. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18600. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18601. ((org-with-limited-levels
  18602. (or (org-at-heading-p)
  18603. (and (org-region-active-p)
  18604. (save-excursion
  18605. (goto-char (region-beginning))
  18606. (org-at-heading-p)))))
  18607. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18608. (call-interactively 'org-do-promote))
  18609. ;; At an inline task.
  18610. ((org-at-heading-p)
  18611. (call-interactively 'org-inlinetask-promote))
  18612. ((or (org-at-item-p)
  18613. (and (org-region-active-p)
  18614. (save-excursion
  18615. (goto-char (region-beginning))
  18616. (org-at-item-p))))
  18617. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18618. (call-interactively 'org-outdent-item))
  18619. (t (call-interactively 'backward-word))))
  18620. (defun org-metaright (&optional _arg)
  18621. "Demote heading, list item at point or move table column right.
  18622. In front of a drawer or a block keyword, indent it correctly.
  18623. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18624. `org-indent-drawer' or `org-indent-block' depending on context.
  18625. With no specific context, calls the Emacs default `forward-word'.
  18626. See the individual commands for more information.
  18627. This function runs the hook `org-metaright-hook' as a first step,
  18628. and returns at first non-nil value."
  18629. (interactive "P")
  18630. (cond
  18631. ((run-hook-with-args-until-success 'org-metaright-hook))
  18632. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18633. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18634. ((org-at-block-p) (call-interactively 'org-indent-block))
  18635. ((org-with-limited-levels
  18636. (or (org-at-heading-p)
  18637. (and (org-region-active-p)
  18638. (save-excursion
  18639. (goto-char (region-beginning))
  18640. (org-at-heading-p)))))
  18641. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18642. (call-interactively 'org-do-demote))
  18643. ;; At an inline task.
  18644. ((org-at-heading-p)
  18645. (call-interactively 'org-inlinetask-demote))
  18646. ((or (org-at-item-p)
  18647. (and (org-region-active-p)
  18648. (save-excursion
  18649. (goto-char (region-beginning))
  18650. (org-at-item-p))))
  18651. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18652. (call-interactively 'org-indent-item))
  18653. (t (call-interactively 'forward-word))))
  18654. (defun org-check-for-hidden (what)
  18655. "Check if there are hidden headlines/items in the current visual line.
  18656. WHAT can be either `headlines' or `items'. If the current line is
  18657. an outline or item heading and it has a folded subtree below it,
  18658. this function returns t, nil otherwise."
  18659. (let ((re (cond
  18660. ((eq what 'headlines) org-outline-regexp-bol)
  18661. ((eq what 'items) (org-item-beginning-re))
  18662. (t (error "This should not happen"))))
  18663. beg end)
  18664. (save-excursion
  18665. (catch 'exit
  18666. (unless (org-region-active-p)
  18667. (setq beg (point-at-bol))
  18668. (beginning-of-line 2)
  18669. (while (and (not (eobp)) ;; this is like `next-line'
  18670. (get-char-property (1- (point)) 'invisible))
  18671. (beginning-of-line 2))
  18672. (setq end (point))
  18673. (goto-char beg)
  18674. (goto-char (point-at-eol))
  18675. (setq end (max end (point)))
  18676. (while (re-search-forward re end t)
  18677. (when (get-char-property (match-beginning 0) 'invisible)
  18678. (throw 'exit t))))
  18679. nil))))
  18680. (defun org-metaup (&optional _arg)
  18681. "Move subtree up or move table row up.
  18682. Calls `org-move-subtree-up' or `org-table-move-row' or
  18683. `org-move-item-up', depending on context. See the individual commands
  18684. for more information."
  18685. (interactive "P")
  18686. (cond
  18687. ((run-hook-with-args-until-success 'org-metaup-hook))
  18688. ((org-region-active-p)
  18689. (let* ((a (min (region-beginning) (region-end)))
  18690. (b (1- (max (region-beginning) (region-end))))
  18691. (c (save-excursion (goto-char a)
  18692. (move-beginning-of-line 0)))
  18693. (d (save-excursion (goto-char a)
  18694. (move-end-of-line 0) (point))))
  18695. (transpose-regions a b c d)
  18696. (goto-char c)))
  18697. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18698. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18699. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18700. (t (org-drag-element-backward))))
  18701. (defun org-metadown (&optional _arg)
  18702. "Move subtree down or move table row down.
  18703. Calls `org-move-subtree-down' or `org-table-move-row' or
  18704. `org-move-item-down', depending on context. See the individual
  18705. commands for more information."
  18706. (interactive "P")
  18707. (cond
  18708. ((run-hook-with-args-until-success 'org-metadown-hook))
  18709. ((org-region-active-p)
  18710. (let* ((a (min (region-beginning) (region-end)))
  18711. (b (max (region-beginning) (region-end)))
  18712. (c (save-excursion (goto-char b)
  18713. (move-beginning-of-line 1)))
  18714. (d (save-excursion (goto-char b)
  18715. (move-end-of-line 1) (1+ (point)))))
  18716. (transpose-regions a b c d)
  18717. (goto-char d)))
  18718. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18719. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18720. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18721. (t (org-drag-element-forward))))
  18722. (defun org-shiftup (&optional arg)
  18723. "Increase item in timestamp or increase priority of current headline.
  18724. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18725. depending on context. See the individual commands for more information."
  18726. (interactive "P")
  18727. (cond
  18728. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18729. ((and org-support-shift-select (org-region-active-p))
  18730. (org-call-for-shift-select 'previous-line))
  18731. ((org-at-timestamp-p 'lax)
  18732. (call-interactively (if org-edit-timestamp-down-means-later
  18733. 'org-timestamp-down 'org-timestamp-up)))
  18734. ((and (not (eq org-support-shift-select 'always))
  18735. org-enable-priority-commands
  18736. (org-at-heading-p))
  18737. (call-interactively 'org-priority-up))
  18738. ((and (not org-support-shift-select) (org-at-item-p))
  18739. (call-interactively 'org-previous-item))
  18740. ((org-clocktable-try-shift 'up arg))
  18741. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18742. (org-support-shift-select
  18743. (org-call-for-shift-select 'previous-line))
  18744. (t (org-shiftselect-error))))
  18745. (defun org-shiftdown (&optional arg)
  18746. "Decrease item in timestamp or decrease priority of current headline.
  18747. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18748. depending on context. See the individual commands for more information."
  18749. (interactive "P")
  18750. (cond
  18751. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18752. ((and org-support-shift-select (org-region-active-p))
  18753. (org-call-for-shift-select 'next-line))
  18754. ((org-at-timestamp-p 'lax)
  18755. (call-interactively (if org-edit-timestamp-down-means-later
  18756. 'org-timestamp-up 'org-timestamp-down)))
  18757. ((and (not (eq org-support-shift-select 'always))
  18758. org-enable-priority-commands
  18759. (org-at-heading-p))
  18760. (call-interactively 'org-priority-down))
  18761. ((and (not org-support-shift-select) (org-at-item-p))
  18762. (call-interactively 'org-next-item))
  18763. ((org-clocktable-try-shift 'down arg))
  18764. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18765. (org-support-shift-select
  18766. (org-call-for-shift-select 'next-line))
  18767. (t (org-shiftselect-error))))
  18768. (defun org-shiftright (&optional arg)
  18769. "Cycle the thing at point or in the current line, depending on context.
  18770. Depending on context, this does one of the following:
  18771. - switch a timestamp at point one day into the future
  18772. - on a headline, switch to the next TODO keyword.
  18773. - on an item, switch entire list to the next bullet type
  18774. - on a property line, switch to the next allowed value
  18775. - on a clocktable definition line, move time block into the future"
  18776. (interactive "P")
  18777. (cond
  18778. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18779. ((and org-support-shift-select (org-region-active-p))
  18780. (org-call-for-shift-select 'forward-char))
  18781. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18782. ((and (not (eq org-support-shift-select 'always))
  18783. (org-at-heading-p))
  18784. (let ((org-inhibit-logging
  18785. (not org-treat-S-cursor-todo-selection-as-state-change))
  18786. (org-inhibit-blocking
  18787. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18788. (org-call-with-arg 'org-todo 'right)))
  18789. ((or (and org-support-shift-select
  18790. (not (eq org-support-shift-select 'always))
  18791. (org-at-item-bullet-p))
  18792. (and (not org-support-shift-select) (org-at-item-p)))
  18793. (org-call-with-arg 'org-cycle-list-bullet nil))
  18794. ((and (not (eq org-support-shift-select 'always))
  18795. (org-at-property-p))
  18796. (call-interactively 'org-property-next-allowed-value))
  18797. ((org-clocktable-try-shift 'right arg))
  18798. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18799. (org-support-shift-select
  18800. (org-call-for-shift-select 'forward-char))
  18801. (t (org-shiftselect-error))))
  18802. (defun org-shiftleft (&optional arg)
  18803. "Cycle the thing at point or in the current line, depending on context.
  18804. Depending on context, this does one of the following:
  18805. - switch a timestamp at point one day into the past
  18806. - on a headline, switch to the previous TODO keyword.
  18807. - on an item, switch entire list to the previous bullet type
  18808. - on a property line, switch to the previous allowed value
  18809. - on a clocktable definition line, move time block into the past"
  18810. (interactive "P")
  18811. (cond
  18812. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18813. ((and org-support-shift-select (org-region-active-p))
  18814. (org-call-for-shift-select 'backward-char))
  18815. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18816. ((and (not (eq org-support-shift-select 'always))
  18817. (org-at-heading-p))
  18818. (let ((org-inhibit-logging
  18819. (not org-treat-S-cursor-todo-selection-as-state-change))
  18820. (org-inhibit-blocking
  18821. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18822. (org-call-with-arg 'org-todo 'left)))
  18823. ((or (and org-support-shift-select
  18824. (not (eq org-support-shift-select 'always))
  18825. (org-at-item-bullet-p))
  18826. (and (not org-support-shift-select) (org-at-item-p)))
  18827. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18828. ((and (not (eq org-support-shift-select 'always))
  18829. (org-at-property-p))
  18830. (call-interactively 'org-property-previous-allowed-value))
  18831. ((org-clocktable-try-shift 'left arg))
  18832. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18833. (org-support-shift-select
  18834. (org-call-for-shift-select 'backward-char))
  18835. (t (org-shiftselect-error))))
  18836. (defun org-shiftcontrolright ()
  18837. "Switch to next TODO set."
  18838. (interactive)
  18839. (cond
  18840. ((and org-support-shift-select (org-region-active-p))
  18841. (org-call-for-shift-select 'forward-word))
  18842. ((and (not (eq org-support-shift-select 'always))
  18843. (org-at-heading-p))
  18844. (org-call-with-arg 'org-todo 'nextset))
  18845. (org-support-shift-select
  18846. (org-call-for-shift-select 'forward-word))
  18847. (t (org-shiftselect-error))))
  18848. (defun org-shiftcontrolleft ()
  18849. "Switch to previous TODO set."
  18850. (interactive)
  18851. (cond
  18852. ((and org-support-shift-select (org-region-active-p))
  18853. (org-call-for-shift-select 'backward-word))
  18854. ((and (not (eq org-support-shift-select 'always))
  18855. (org-at-heading-p))
  18856. (org-call-with-arg 'org-todo 'previousset))
  18857. (org-support-shift-select
  18858. (org-call-for-shift-select 'backward-word))
  18859. (t (org-shiftselect-error))))
  18860. (defun org-shiftcontrolup (&optional n)
  18861. "Change timestamps synchronously up in CLOCK log lines.
  18862. Optional argument N tells to change by that many units."
  18863. (interactive "P")
  18864. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18865. (let (org-support-shift-select)
  18866. (org-clock-timestamps-up n))
  18867. (user-error "Not at a clock log")))
  18868. (defun org-shiftcontroldown (&optional n)
  18869. "Change timestamps synchronously down in CLOCK log lines.
  18870. Optional argument N tells to change by that many units."
  18871. (interactive "P")
  18872. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18873. (let (org-support-shift-select)
  18874. (org-clock-timestamps-down n))
  18875. (user-error "Not at a clock log")))
  18876. (defun org-increase-number-at-point (&optional inc)
  18877. "Increment the number at point.
  18878. With an optional prefix numeric argument INC, increment using
  18879. this numeric value."
  18880. (interactive "p")
  18881. (if (not (number-at-point))
  18882. (user-error "Not on a number")
  18883. (unless inc (setq inc 1))
  18884. (let ((pos (point))
  18885. (beg (skip-chars-backward "-+^/*0-9eE."))
  18886. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18887. (setq nap (buffer-substring-no-properties
  18888. (+ pos beg) (+ pos beg end)))
  18889. (delete-region (+ pos beg) (+ pos beg end))
  18890. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18891. (when (org-at-table-p)
  18892. (org-table-align)
  18893. (org-table-end-of-field 1))))
  18894. (defun org-decrease-number-at-point (&optional inc)
  18895. "Decrement the number at point.
  18896. With an optional prefix numeric argument INC, decrement using
  18897. this numeric value."
  18898. (interactive "p")
  18899. (org-increase-number-at-point (- (or inc 1))))
  18900. (defun org-ctrl-c-ret ()
  18901. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18902. (interactive)
  18903. (cond
  18904. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18905. (t (call-interactively 'org-insert-heading))))
  18906. (defun org-find-visible ()
  18907. (let ((s (point)))
  18908. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18909. (get-char-property s 'invisible)))
  18910. s))
  18911. (defun org-find-invisible ()
  18912. (let ((s (point)))
  18913. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18914. (not (get-char-property s 'invisible))))
  18915. s))
  18916. (defun org-copy-visible (beg end)
  18917. "Copy the visible parts of the region."
  18918. (interactive "r")
  18919. (let (snippets s)
  18920. (save-excursion
  18921. (save-restriction
  18922. (narrow-to-region beg end)
  18923. (setq s (goto-char (point-min)))
  18924. (while (not (= (point) (point-max)))
  18925. (goto-char (org-find-invisible))
  18926. (push (buffer-substring s (point)) snippets)
  18927. (setq s (goto-char (org-find-visible))))))
  18928. (kill-new (apply 'concat (nreverse snippets)))))
  18929. (defun org-copy-special ()
  18930. "Copy region in table or copy current subtree.
  18931. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18932. context. See the individual commands for more information."
  18933. (interactive)
  18934. (call-interactively
  18935. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18936. (defun org-cut-special ()
  18937. "Cut region in table or cut current subtree.
  18938. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18939. context. See the individual commands for more information."
  18940. (interactive)
  18941. (call-interactively
  18942. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18943. (defun org-paste-special (arg)
  18944. "Paste rectangular region into table, or past subtree relative to level.
  18945. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18946. See the individual commands for more information."
  18947. (interactive "P")
  18948. (if (org-at-table-p)
  18949. (org-table-paste-rectangle)
  18950. (org-paste-subtree arg)))
  18951. (defun org-edit-special (&optional arg)
  18952. "Call a special editor for the element at point.
  18953. When at a table, call the formula editor with `org-table-edit-formulas'.
  18954. When in a source code block, call `org-edit-src-code'.
  18955. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18956. When in an export block, call `org-edit-export-block'.
  18957. When in a LaTeX environment, call `org-edit-latex-environment'.
  18958. When at an #+INCLUDE keyword, visit the included file.
  18959. When at a footnote reference, call `org-edit-footnote-reference'
  18960. On a link, call `ffap' to visit the link at point.
  18961. Otherwise, return a user error."
  18962. (interactive "P")
  18963. (let ((element (org-element-at-point)))
  18964. (barf-if-buffer-read-only)
  18965. (pcase (org-element-type element)
  18966. (`src-block
  18967. (if (not arg) (org-edit-src-code)
  18968. (let* ((info (org-babel-get-src-block-info))
  18969. (lang (nth 0 info))
  18970. (params (nth 2 info))
  18971. (session (cdr (assq :session params))))
  18972. (if (not session) (org-edit-src-code)
  18973. ;; At a src-block with a session and function called with
  18974. ;; an ARG: switch to the buffer related to the inferior
  18975. ;; process.
  18976. (switch-to-buffer
  18977. (funcall (intern (concat "org-babel-prep-session:" lang))
  18978. session params))))))
  18979. (`keyword
  18980. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18981. (org-open-link-from-string
  18982. (format "[[%s]]"
  18983. (expand-file-name
  18984. (let ((value (org-element-property :value element)))
  18985. (cond ((not (org-string-nw-p value))
  18986. (user-error "No file to edit"))
  18987. ((string-match "\\`\"\\(.*?\\)\"" value)
  18988. (match-string 1 value))
  18989. ((string-match "\\`[^ \t\"]\\S-*" value)
  18990. (match-string 0 value))
  18991. (t (user-error "No valid file specified")))))))
  18992. (user-error "No special environment to edit here")))
  18993. (`table
  18994. (if (eq (org-element-property :type element) 'table.el)
  18995. (org-edit-table.el)
  18996. (call-interactively 'org-table-edit-formulas)))
  18997. ;; Only Org tables contain `table-row' type elements.
  18998. (`table-row (call-interactively 'org-table-edit-formulas))
  18999. (`example-block (org-edit-src-code))
  19000. (`export-block (org-edit-export-block))
  19001. (`fixed-width (org-edit-fixed-width-region))
  19002. (`latex-environment (org-edit-latex-environment))
  19003. (_
  19004. ;; No notable element at point. Though, we may be at a link or
  19005. ;; a footnote reference, which are objects. Thus, scan deeper.
  19006. (let ((context (org-element-context element)))
  19007. (pcase (org-element-type context)
  19008. (`footnote-reference (org-edit-footnote-reference))
  19009. (`inline-src-block (org-edit-inline-src-code))
  19010. (`link (call-interactively #'ffap))
  19011. (_ (user-error "No special environment to edit here"))))))))
  19012. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19013. (defun org-ctrl-c-ctrl-c (&optional arg)
  19014. "Set tags in headline, or update according to changed information at point.
  19015. This command does many different things, depending on context:
  19016. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19017. this is what we do.
  19018. - If the cursor is on a statistics cookie, update it.
  19019. - If the cursor is in a headline, prompt for tags and insert them
  19020. into the current line, aligned to `org-tags-column'. When called
  19021. with prefix arg, realign all tags in the current buffer.
  19022. - If the cursor is in one of the special #+KEYWORD lines, this
  19023. triggers scanning the buffer for these lines and updating the
  19024. information.
  19025. - If the cursor is inside a table, realign the table. This command
  19026. works even if the automatic table editor has been turned off.
  19027. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19028. the entire table.
  19029. - If the cursor is at a footnote reference or definition, jump to
  19030. the corresponding definition or references, respectively.
  19031. - If the cursor is a the beginning of a dynamic block, update it.
  19032. - If the current buffer is a capture buffer, close note and file it.
  19033. - If the cursor is on a <<<target>>>, update radio targets and
  19034. corresponding links in this buffer.
  19035. - If the cursor is on a numbered item in a plain list, renumber the
  19036. ordered list.
  19037. - If the cursor is on a checkbox, toggle it.
  19038. - If the cursor is on a code block, evaluate it. The variable
  19039. `org-confirm-babel-evaluate' can be used to control prompting
  19040. before code block evaluation, by default every code block
  19041. evaluation requires confirmation. Code block evaluation can be
  19042. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19043. (interactive "P")
  19044. (cond
  19045. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  19046. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19047. (org-remove-occur-highlights)
  19048. (message "Temporary highlights/overlays removed from current buffer"))
  19049. ((and (local-variable-p 'org-finish-function)
  19050. (fboundp org-finish-function))
  19051. (funcall org-finish-function))
  19052. ((org-babel-hash-at-point))
  19053. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19054. (t
  19055. (let* ((context
  19056. (org-element-lineage
  19057. (org-element-context)
  19058. ;; Limit to supported contexts.
  19059. '(babel-call clock dynamic-block footnote-definition
  19060. footnote-reference inline-babel-call inline-src-block
  19061. inlinetask item keyword node-property paragraph
  19062. plain-list property-drawer radio-target src-block
  19063. statistics-cookie table table-cell table-row
  19064. timestamp)
  19065. t))
  19066. (type (org-element-type context)))
  19067. ;; For convenience: at the first line of a paragraph on the same
  19068. ;; line as an item, apply function on that item instead.
  19069. (when (eq type 'paragraph)
  19070. (let ((parent (org-element-property :parent context)))
  19071. (when (and (eq (org-element-type parent) 'item)
  19072. (= (line-beginning-position)
  19073. (org-element-property :begin parent)))
  19074. (setq context parent)
  19075. (setq type 'item))))
  19076. ;; Act according to type of element or object at point.
  19077. ;;
  19078. ;; Do nothing on a blank line, except if it is contained in
  19079. ;; a src block. Hence, we first check if point is in such
  19080. ;; a block and then if it is at a blank line.
  19081. (pcase type
  19082. ((or `inline-src-block `src-block)
  19083. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19084. (org-babel-eval-wipe-error-buffer)
  19085. (org-babel-execute-src-block
  19086. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19087. ((guard (org-match-line "[ \t]*$"))
  19088. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19089. (user-error
  19090. (substitute-command-keys
  19091. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19092. ((or `babel-call `inline-babel-call)
  19093. (let ((info (org-babel-lob-get-info context)))
  19094. (when info (org-babel-execute-src-block nil info))))
  19095. (`clock (org-clock-update-time-maybe))
  19096. (`dynamic-block
  19097. (save-excursion
  19098. (goto-char (org-element-property :post-affiliated context))
  19099. (org-update-dblock)))
  19100. (`footnote-definition
  19101. (goto-char (org-element-property :post-affiliated context))
  19102. (call-interactively 'org-footnote-action))
  19103. (`footnote-reference (call-interactively #'org-footnote-action))
  19104. ((or `headline `inlinetask)
  19105. (save-excursion (goto-char (org-element-property :begin context))
  19106. (call-interactively #'org-set-tags)))
  19107. (`item
  19108. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19109. ;; unconditionally, whereas `C-u' will toggle its presence.
  19110. ;; Without a universal argument, if the item has a checkbox,
  19111. ;; toggle it. Otherwise repair the list.
  19112. (let* ((box (org-element-property :checkbox context))
  19113. (struct (org-element-property :structure context))
  19114. (old-struct (copy-tree struct))
  19115. (parents (org-list-parents-alist struct))
  19116. (prevs (org-list-prevs-alist struct))
  19117. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19118. (org-list-set-checkbox
  19119. (org-element-property :begin context) struct
  19120. (cond ((equal arg '(16)) "[-]")
  19121. ((and (not box) (equal arg '(4))) "[ ]")
  19122. ((or (not box) (equal arg '(4))) nil)
  19123. ((eq box 'on) "[ ]")
  19124. (t "[X]")))
  19125. ;; Mimic `org-list-write-struct' but with grabbing a return
  19126. ;; value from `org-list-struct-fix-box'.
  19127. (org-list-struct-fix-ind struct parents 2)
  19128. (org-list-struct-fix-item-end struct)
  19129. (org-list-struct-fix-bul struct prevs)
  19130. (org-list-struct-fix-ind struct parents)
  19131. (let ((block-item
  19132. (org-list-struct-fix-box struct parents prevs orderedp)))
  19133. (if (and box (equal struct old-struct))
  19134. (if (equal arg '(16))
  19135. (message "Checkboxes already reset")
  19136. (user-error "Cannot toggle this checkbox: %s"
  19137. (if (eq box 'on)
  19138. "all subitems checked"
  19139. "unchecked subitems")))
  19140. (org-list-struct-apply-struct struct old-struct)
  19141. (org-update-checkbox-count-maybe))
  19142. (when block-item
  19143. (message "Checkboxes were removed due to empty box at line %d"
  19144. (org-current-line block-item))))))
  19145. (`keyword
  19146. (let ((org-inhibit-startup-visibility-stuff t)
  19147. (org-startup-align-all-tables nil))
  19148. (when (boundp 'org-table-coordinate-overlays)
  19149. (mapc #'delete-overlay org-table-coordinate-overlays)
  19150. (setq org-table-coordinate-overlays nil))
  19151. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19152. (message "Local setup has been refreshed"))
  19153. (`plain-list
  19154. ;; At a plain list, with a double C-u argument, set
  19155. ;; checkboxes of each item to "[-]", whereas a single one
  19156. ;; will toggle their presence according to the state of the
  19157. ;; first item in the list. Without an argument, repair the
  19158. ;; list.
  19159. (let* ((begin (org-element-property :contents-begin context))
  19160. (beginm (move-marker (make-marker) begin))
  19161. (struct (org-element-property :structure context))
  19162. (old-struct (copy-tree struct))
  19163. (first-box (save-excursion
  19164. (goto-char begin)
  19165. (looking-at org-list-full-item-re)
  19166. (match-string-no-properties 3)))
  19167. (new-box (cond ((equal arg '(16)) "[-]")
  19168. ((equal arg '(4)) (unless first-box "[ ]"))
  19169. ((equal first-box "[X]") "[ ]")
  19170. (t "[X]"))))
  19171. (cond
  19172. (arg
  19173. (dolist (pos
  19174. (org-list-get-all-items
  19175. begin struct (org-list-prevs-alist struct)))
  19176. (org-list-set-checkbox pos struct new-box)))
  19177. ((and first-box (eq (point) begin))
  19178. ;; For convenience, when point is at bol on the first
  19179. ;; item of the list and no argument is provided, simply
  19180. ;; toggle checkbox of that item, if any.
  19181. (org-list-set-checkbox begin struct new-box)))
  19182. (org-list-write-struct
  19183. struct (org-list-parents-alist struct) old-struct)
  19184. (org-update-checkbox-count-maybe)
  19185. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19186. ((or `property-drawer `node-property)
  19187. (call-interactively #'org-property-action))
  19188. (`radio-target
  19189. (call-interactively #'org-update-radio-target-regexp))
  19190. (`statistics-cookie
  19191. (call-interactively #'org-update-statistics-cookies))
  19192. ((or `table `table-cell `table-row)
  19193. ;; At a table, recalculate every field and align it. Also
  19194. ;; send the table if necessary. If the table has
  19195. ;; a `table.el' type, just give up. At a table row or cell,
  19196. ;; maybe recalculate line but always align table.
  19197. (if (eq (org-element-property :type context) 'table.el)
  19198. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19199. Use `\\[org-edit-special]' to edit table.el tables"))
  19200. (let ((org-enable-table-editor t))
  19201. (if (or (eq type 'table)
  19202. ;; Check if point is at a TBLFM line.
  19203. (and (eq type 'table-row)
  19204. (= (point) (org-element-property :end context))))
  19205. (save-excursion
  19206. (if (org-at-TBLFM-p)
  19207. (progn (require 'org-table)
  19208. (org-table-calc-current-TBLFM))
  19209. (goto-char (org-element-property :contents-begin context))
  19210. (org-call-with-arg 'org-table-recalculate (or arg t))
  19211. (orgtbl-send-table 'maybe)))
  19212. (org-table-maybe-eval-formula)
  19213. (cond (arg (call-interactively #'org-table-recalculate))
  19214. ((org-table-maybe-recalculate-line))
  19215. (t (org-table-align)))))))
  19216. (`timestamp (org-timestamp-change 0 'day))
  19217. ((and `nil (guard (org-at-heading-p)))
  19218. ;; When point is on an unsupported object type, we can miss
  19219. ;; the fact that it also is at a heading. Handle it here.
  19220. (call-interactively #'org-set-tags))
  19221. ((guard
  19222. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19223. (_
  19224. (user-error
  19225. (substitute-command-keys
  19226. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19227. (defun org-mode-restart ()
  19228. (interactive)
  19229. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19230. (funcall major-mode)
  19231. (hack-local-variables)
  19232. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19233. (org-indent-mode -1)))
  19234. (message "%s restarted" major-mode))
  19235. (defun org-kill-note-or-show-branches ()
  19236. "Abort storing current note, or call `outline-show-branches'."
  19237. (interactive)
  19238. (if (not org-finish-function)
  19239. (progn
  19240. (outline-hide-subtree)
  19241. (call-interactively 'outline-show-branches))
  19242. (let ((org-note-abort t))
  19243. (funcall org-finish-function))))
  19244. (defun org-delete-indentation (&optional arg)
  19245. "Join current line to previous and fix whitespace at join.
  19246. If previous line is a headline add to headline title. Otherwise
  19247. the function calls `delete-indentation'.
  19248. With a non-nil optional argument, join it to the following one."
  19249. (interactive "*P")
  19250. (if (save-excursion
  19251. (beginning-of-line (if arg 1 0))
  19252. (let ((case-fold-search nil))
  19253. (looking-at org-complex-heading-regexp)))
  19254. ;; At headline.
  19255. (let ((tags-column (when (match-beginning 5)
  19256. (save-excursion (goto-char (match-beginning 5))
  19257. (current-column))))
  19258. (string (concat " " (progn (when arg (forward-line 1))
  19259. (org-trim (delete-and-extract-region
  19260. (line-beginning-position)
  19261. (line-end-position)))))))
  19262. (unless (bobp) (delete-region (point) (1- (point))))
  19263. (goto-char (or (match-end 4)
  19264. (match-beginning 5)
  19265. (match-end 0)))
  19266. (skip-chars-backward " \t")
  19267. (save-excursion (insert string))
  19268. ;; Adjust alignment of tags.
  19269. (cond
  19270. ((not tags-column)) ;no tags
  19271. (org-auto-align-tags (org-set-tags nil t))
  19272. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19273. (delete-indentation arg)))
  19274. (defun org-open-line (n)
  19275. "Insert a new row in tables, call `open-line' elsewhere.
  19276. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19277. As a special case, when a document starts with a table, allow to
  19278. call `open-line' on the very first character."
  19279. (interactive "*p")
  19280. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19281. (org-table-insert-row)
  19282. (open-line n)))
  19283. (defun org-return (&optional indent)
  19284. "Goto next table row or insert a newline.
  19285. Calls `org-table-next-row' or `newline', depending on context.
  19286. When optional INDENT argument is non-nil, call
  19287. `newline-and-indent' instead of `newline'.
  19288. When `org-return-follows-link' is non-nil and point is on
  19289. a timestamp or a link, call `org-open-at-point'. However, it
  19290. will not happen if point is in a table or on a \"dead\"
  19291. object (e.g., within a comment). In these case, you need to use
  19292. `org-open-at-point' directly."
  19293. (interactive)
  19294. (let ((context (if org-return-follows-link (org-element-context)
  19295. (org-element-at-point))))
  19296. (cond
  19297. ;; In a table, call `org-table-next-row'.
  19298. ((or (and (eq (org-element-type context) 'table)
  19299. (>= (point) (org-element-property :contents-begin context))
  19300. (< (point) (org-element-property :contents-end context)))
  19301. (org-element-lineage context '(table-row table-cell) t))
  19302. (org-table-justify-field-maybe)
  19303. (call-interactively #'org-table-next-row))
  19304. ;; On a link or a timestamp, call `org-open-at-point' if
  19305. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19306. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19307. ((and org-return-follows-link
  19308. (or (org-in-regexp org-ts-regexp-both nil t)
  19309. (org-in-regexp org-tsr-regexp-both nil t)
  19310. (org-in-regexp org-any-link-re nil t)))
  19311. (call-interactively #'org-open-at-point))
  19312. ;; Insert newline in heading, but preserve tags.
  19313. ((and (not (bolp))
  19314. (save-excursion (beginning-of-line)
  19315. (let ((case-fold-search nil))
  19316. (looking-at org-complex-heading-regexp))))
  19317. ;; At headline. Split line. However, if point is on keyword,
  19318. ;; priority cookie or tags, do not break any of them: add
  19319. ;; a newline after the headline instead.
  19320. (let ((tags-column (and (match-beginning 5)
  19321. (save-excursion (goto-char (match-beginning 5))
  19322. (current-column))))
  19323. (string
  19324. (when (and (match-end 4) (org-point-in-group (point) 4))
  19325. (delete-and-extract-region (point) (match-end 4)))))
  19326. ;; Adjust tag alignment.
  19327. (cond
  19328. ((not (and tags-column string)))
  19329. (org-auto-align-tags (org-set-tags nil t))
  19330. (t (org--align-tags-here tags-column))) ;preserve tags column
  19331. (end-of-line)
  19332. (org-show-entry)
  19333. (if indent (newline-and-indent) (newline))
  19334. (when string (save-excursion (insert (org-trim string))))))
  19335. ;; In a list, make sure indenting keeps trailing text within.
  19336. ((and indent
  19337. (not (eolp))
  19338. (org-element-lineage context '(item)))
  19339. (let ((trailing-data
  19340. (delete-and-extract-region (point) (line-end-position))))
  19341. (newline-and-indent)
  19342. (save-excursion (insert trailing-data))))
  19343. (t (if indent (newline-and-indent) (newline))))))
  19344. (defun org-return-indent ()
  19345. "Goto next table row or insert a newline and indent.
  19346. Calls `org-table-next-row' or `newline-and-indent', depending on
  19347. context. See the individual commands for more information."
  19348. (interactive)
  19349. (org-return t))
  19350. (defun org-ctrl-c-star ()
  19351. "Compute table, or change heading status of lines.
  19352. Calls `org-table-recalculate' or `org-toggle-heading',
  19353. depending on context."
  19354. (interactive)
  19355. (cond
  19356. ((org-at-table-p)
  19357. (call-interactively 'org-table-recalculate))
  19358. (t
  19359. ;; Convert all lines in region to list items
  19360. (call-interactively 'org-toggle-heading))))
  19361. (defun org-ctrl-c-minus ()
  19362. "Insert separator line in table or modify bullet status of line.
  19363. Also turns a plain line or a region of lines into list items.
  19364. Calls `org-table-insert-hline', `org-toggle-item', or
  19365. `org-cycle-list-bullet', depending on context."
  19366. (interactive)
  19367. (cond
  19368. ((org-at-table-p)
  19369. (call-interactively 'org-table-insert-hline))
  19370. ((org-region-active-p)
  19371. (call-interactively 'org-toggle-item))
  19372. ((org-in-item-p)
  19373. (call-interactively 'org-cycle-list-bullet))
  19374. (t
  19375. (call-interactively 'org-toggle-item))))
  19376. (defun org-toggle-heading (&optional nstars)
  19377. "Convert headings to normal text, or items or text to headings.
  19378. If there is no active region, only convert the current line.
  19379. With a `\\[universal-argument]' prefix, convert the whole list at
  19380. point into heading.
  19381. In a region:
  19382. - If the first non blank line is a headline, remove the stars
  19383. from all headlines in the region.
  19384. - If it is a normal line, turn each and every normal line (i.e.,
  19385. not an heading or an item) in the region into headings. If you
  19386. want to convert only the first line of this region, use one
  19387. universal prefix argument.
  19388. - If it is a plain list item, turn all plain list items into headings.
  19389. When converting a line into a heading, the number of stars is chosen
  19390. such that the lines become children of the current entry. However,
  19391. when a numeric prefix argument is given, its value determines the
  19392. number of stars to add."
  19393. (interactive "P")
  19394. (let ((skip-blanks
  19395. (function
  19396. ;; Return beginning of first non-blank line, starting from
  19397. ;; line at POS.
  19398. (lambda (pos)
  19399. (save-excursion
  19400. (goto-char pos)
  19401. (while (org-at-comment-p) (forward-line))
  19402. (skip-chars-forward " \r\t\n")
  19403. (point-at-bol)))))
  19404. beg end toggled)
  19405. ;; Determine boundaries of changes. If a universal prefix has
  19406. ;; been given, put the list in a region. If region ends at a bol,
  19407. ;; do not consider the last line to be in the region.
  19408. (when (and current-prefix-arg (org-at-item-p))
  19409. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19410. (org-mark-element))
  19411. (if (org-region-active-p)
  19412. (setq beg (funcall skip-blanks (region-beginning))
  19413. end (copy-marker (save-excursion
  19414. (goto-char (region-end))
  19415. (if (bolp) (point) (point-at-eol)))))
  19416. (setq beg (funcall skip-blanks (point-at-bol))
  19417. end (copy-marker (point-at-eol))))
  19418. ;; Ensure inline tasks don't count as headings.
  19419. (org-with-limited-levels
  19420. (save-excursion
  19421. (goto-char beg)
  19422. (cond
  19423. ;; Case 1. Started at an heading: de-star headings.
  19424. ((org-at-heading-p)
  19425. (while (< (point) end)
  19426. (when (org-at-heading-p t)
  19427. (looking-at org-outline-regexp) (replace-match "")
  19428. (setq toggled t))
  19429. (forward-line)))
  19430. ;; Case 2. Started at an item: change items into headlines.
  19431. ;; One star will be added by `org-list-to-subtree'.
  19432. ((org-at-item-p)
  19433. (while (< (point) end)
  19434. (when (org-at-item-p)
  19435. ;; Pay attention to cases when region ends before list.
  19436. (let* ((struct (org-list-struct))
  19437. (list-end
  19438. (min (org-list-get-bottom-point struct) (1+ end))))
  19439. (save-restriction
  19440. (narrow-to-region (point) list-end)
  19441. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19442. (setq toggled t))
  19443. (forward-line)))
  19444. ;; Case 3. Started at normal text: make every line an heading,
  19445. ;; skipping headlines and items.
  19446. (t (let* ((stars
  19447. (make-string
  19448. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19449. (add-stars
  19450. (cond (nstars "") ; stars from prefix only
  19451. ((equal stars "") "*") ; before first heading
  19452. (org-odd-levels-only "**") ; inside heading, odd
  19453. (t "*"))) ; inside heading, oddeven
  19454. (rpl (concat stars add-stars " "))
  19455. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19456. (while (< (point) (if (equal nstars '(4)) lend end))
  19457. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19458. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19459. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19460. (forward-line)))))))
  19461. (unless toggled (message "Cannot toggle heading from here"))))
  19462. (defun org-meta-return (&optional arg)
  19463. "Insert a new heading or wrap a region in a table.
  19464. Calls `org-insert-heading', `org-insert-item' or
  19465. `org-table-wrap-region', depending on context. When called with
  19466. an argument, unconditionally call `org-insert-heading'."
  19467. (interactive "P")
  19468. (org-check-before-invisible-edit 'insert)
  19469. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19470. (call-interactively (cond (arg #'org-insert-heading)
  19471. ((org-at-table-p) #'org-table-wrap-region)
  19472. ((org-in-item-p) #'org-insert-item)
  19473. (t #'org-insert-heading)))))
  19474. ;;; Menu entries
  19475. (defsubst org-in-subtree-not-table-p ()
  19476. "Are we in a subtree and not in a table?"
  19477. (and (not (org-before-first-heading-p))
  19478. (not (org-at-table-p))))
  19479. ;; Define the Org mode menus
  19480. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19481. '("Tbl"
  19482. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19483. ["Next Field" org-cycle (org-at-table-p)]
  19484. ["Previous Field" org-shifttab (org-at-table-p)]
  19485. ["Next Row" org-return (org-at-table-p)]
  19486. "--"
  19487. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19488. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19489. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19490. "--"
  19491. ("Column"
  19492. ["Move Column Left" org-metaleft (org-at-table-p)]
  19493. ["Move Column Right" org-metaright (org-at-table-p)]
  19494. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19495. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19496. ("Row"
  19497. ["Move Row Up" org-metaup (org-at-table-p)]
  19498. ["Move Row Down" org-metadown (org-at-table-p)]
  19499. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19500. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19501. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19502. "--"
  19503. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19504. ("Rectangle"
  19505. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19506. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19507. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19508. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19509. "--"
  19510. ("Calculate"
  19511. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19512. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19513. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19514. "--"
  19515. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19516. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19517. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19518. "--"
  19519. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19520. "--"
  19521. ["Sum Column/Rectangle" org-table-sum
  19522. (or (org-at-table-p) (org-region-active-p))]
  19523. ["Which Column?" org-table-current-column (org-at-table-p)])
  19524. ["Debug Formulas"
  19525. org-table-toggle-formula-debugger
  19526. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19527. ["Show Col/Row Numbers"
  19528. org-table-toggle-coordinate-overlays
  19529. :style toggle
  19530. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19531. "--"
  19532. ["Create" org-table-create (and (not (org-at-table-p))
  19533. org-enable-table-editor)]
  19534. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19535. ["Import from File" org-table-import (not (org-at-table-p))]
  19536. ["Export to File" org-table-export (org-at-table-p)]
  19537. "--"
  19538. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19539. "--"
  19540. ("Plot"
  19541. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19542. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19543. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19544. '("Org"
  19545. ("Show/Hide"
  19546. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19547. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19548. ["Sparse Tree..." org-sparse-tree t]
  19549. ["Reveal Context" org-reveal t]
  19550. ["Show All" outline-show-all t]
  19551. "--"
  19552. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19553. "--"
  19554. ["New Heading" org-insert-heading t]
  19555. ("Navigate Headings"
  19556. ["Up" outline-up-heading t]
  19557. ["Next" outline-next-visible-heading t]
  19558. ["Previous" outline-previous-visible-heading t]
  19559. ["Next Same Level" outline-forward-same-level t]
  19560. ["Previous Same Level" outline-backward-same-level t]
  19561. "--"
  19562. ["Jump" org-goto t])
  19563. ("Edit Structure"
  19564. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19565. "--"
  19566. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19567. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19568. "--"
  19569. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19570. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19571. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19572. "--"
  19573. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19574. "--"
  19575. ["Copy visible text" org-copy-visible t]
  19576. "--"
  19577. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19578. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19579. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19580. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19581. "--"
  19582. ["Sort Region/Children" org-sort t]
  19583. "--"
  19584. ["Convert to odd levels" org-convert-to-odd-levels t]
  19585. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19586. ("Editing"
  19587. ["Emphasis..." org-emphasize t]
  19588. ["Edit Source Example" org-edit-special t]
  19589. "--"
  19590. ["Footnote new/jump" org-footnote-action t]
  19591. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19592. ("Archive"
  19593. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19594. "--"
  19595. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19596. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19597. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19598. )
  19599. "--"
  19600. ("Hyperlinks"
  19601. ["Store Link (Global)" org-store-link t]
  19602. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19603. ["Insert Link" org-insert-link t]
  19604. ["Follow Link" org-open-at-point t]
  19605. "--"
  19606. ["Next link" org-next-link t]
  19607. ["Previous link" org-previous-link t]
  19608. "--"
  19609. ["Descriptive Links"
  19610. org-toggle-link-display
  19611. :style radio
  19612. :selected org-descriptive-links
  19613. ]
  19614. ["Literal Links"
  19615. org-toggle-link-display
  19616. :style radio
  19617. :selected (not org-descriptive-links)])
  19618. "--"
  19619. ("TODO Lists"
  19620. ["TODO/DONE/-" org-todo t]
  19621. ("Select keyword"
  19622. ["Next keyword" org-shiftright (org-at-heading-p)]
  19623. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19624. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19625. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19626. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19627. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19628. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19629. "--"
  19630. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19631. :selected org-enforce-todo-dependencies :style toggle :active t]
  19632. "Settings for tree at point"
  19633. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19634. :selected (org-entry-get nil "ORDERED")
  19635. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19636. ["Do Children parallel" org-toggle-ordered-property :style radio
  19637. :selected (not (org-entry-get nil "ORDERED"))
  19638. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19639. "--"
  19640. ["Set Priority" org-priority t]
  19641. ["Priority Up" org-shiftup t]
  19642. ["Priority Down" org-shiftdown t]
  19643. "--"
  19644. ["Get news from all feeds" org-feed-update-all t]
  19645. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19646. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19647. ("TAGS and Properties"
  19648. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19649. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19650. "--"
  19651. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19652. ["Column view of properties" org-columns t]
  19653. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19654. ("Dates and Scheduling"
  19655. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19656. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19657. ("Change Date"
  19658. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19659. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19660. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19661. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19662. ["Compute Time Range" org-evaluate-time-range t]
  19663. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19664. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19665. "--"
  19666. ["Custom time format" org-toggle-time-stamp-overlays
  19667. :style radio :selected org-display-custom-times]
  19668. "--"
  19669. ["Goto Calendar" org-goto-calendar t]
  19670. ["Date from Calendar" org-date-from-calendar t]
  19671. "--"
  19672. ["Start/Restart Timer" org-timer-start t]
  19673. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19674. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19675. ["Insert Timer String" org-timer t]
  19676. ["Insert Timer Item" org-timer-item t])
  19677. ("Logging work"
  19678. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19679. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19680. ["Clock out" org-clock-out t]
  19681. ["Clock cancel" org-clock-cancel t]
  19682. "--"
  19683. ["Mark as default task" org-clock-mark-default-task t]
  19684. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19685. ["Goto running clock" org-clock-goto t]
  19686. "--"
  19687. ["Display times" org-clock-display t]
  19688. ["Create clock table" org-clock-report t]
  19689. "--"
  19690. ["Record DONE time"
  19691. (progn (setq org-log-done (not org-log-done))
  19692. (message "Switching to %s will %s record a timestamp"
  19693. (car org-done-keywords)
  19694. (if org-log-done "automatically" "not")))
  19695. :style toggle :selected org-log-done])
  19696. "--"
  19697. ["Agenda Command..." org-agenda t]
  19698. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19699. ("File List for Agenda")
  19700. ("Special views current file"
  19701. ["TODO Tree" org-show-todo-tree t]
  19702. ["Check Deadlines" org-check-deadlines t]
  19703. ["Tags/Property tree" org-match-sparse-tree t])
  19704. "--"
  19705. ["Export/Publish..." org-export-dispatch t]
  19706. ("LaTeX"
  19707. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19708. :selected org-cdlatex-mode]
  19709. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19710. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19711. ["Modify math symbol" org-cdlatex-math-modify
  19712. (org-inside-LaTeX-fragment-p)]
  19713. ["Insert citation" org-reftex-citation t])
  19714. "--"
  19715. ("MobileOrg"
  19716. ["Push Files and Views" org-mobile-push t]
  19717. ["Get Captured and Flagged" org-mobile-pull t]
  19718. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19719. "--"
  19720. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19721. "--"
  19722. ("Documentation"
  19723. ["Show Version" org-version t]
  19724. ["Info Documentation" org-info t])
  19725. ("Customize"
  19726. ["Browse Org Group" org-customize t]
  19727. "--"
  19728. ["Expand This Menu" org-create-customize-menu
  19729. (fboundp 'customize-menu-create)])
  19730. ["Send bug report" org-submit-bug-report t]
  19731. "--"
  19732. ("Refresh/Reload"
  19733. ["Refresh setup current buffer" org-mode-restart t]
  19734. ["Reload Org (after update)" org-reload t]
  19735. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19736. ))
  19737. (defun org-info (&optional node)
  19738. "Read documentation for Org in the info system.
  19739. With optional NODE, go directly to that node."
  19740. (interactive)
  19741. (info (format "(org)%s" (or node ""))))
  19742. ;;;###autoload
  19743. (defun org-submit-bug-report ()
  19744. "Submit a bug report on Org via mail.
  19745. Don't hesitate to report any problems or inaccurate documentation.
  19746. If you don't have setup sending mail from (X)Emacs, please copy the
  19747. output buffer into your mail program, as it gives us important
  19748. information about your Org version and configuration."
  19749. (interactive)
  19750. (require 'reporter)
  19751. (defvar reporter-prompt-for-summary-p)
  19752. (org-load-modules-maybe)
  19753. (org-require-autoloaded-modules)
  19754. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19755. (reporter-submit-bug-report
  19756. "emacs-orgmode@gnu.org"
  19757. (org-version nil 'full)
  19758. (let (list)
  19759. (save-window-excursion
  19760. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19761. (delete-other-windows)
  19762. (erase-buffer)
  19763. (insert "You are about to submit a bug report to the Org mailing list.
  19764. We would like to add your full Org and Outline configuration to the
  19765. bug report. This greatly simplifies the work of the maintainer and
  19766. other experts on the mailing list.
  19767. HOWEVER, some variables you have customized may contain private
  19768. information. The names of customers, colleagues, or friends, might
  19769. appear in the form of file names, tags, todo states, or search strings.
  19770. If you answer yes to the prompt, you might want to check and remove
  19771. such private information before sending the email.")
  19772. (add-text-properties (point-min) (point-max) '(face org-warning))
  19773. (when (yes-or-no-p "Include your Org configuration ")
  19774. (mapatoms
  19775. (lambda (v)
  19776. (and (boundp v)
  19777. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19778. (or (and (symbol-value v)
  19779. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19780. (and
  19781. (get v 'custom-type) (get v 'standard-value)
  19782. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19783. (push v list)))))
  19784. (kill-buffer (get-buffer "*Warn about privacy*"))
  19785. list))
  19786. nil nil
  19787. "Remember to cover the basics, that is, what you expected to happen and
  19788. what in fact did happen. You don't know how to make a good report? See
  19789. http://orgmode.org/manual/Feedback.html#Feedback
  19790. Your bug report will be posted to the Org mailing list.
  19791. ------------------------------------------------------------------------")
  19792. (save-excursion
  19793. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19794. (replace-match "\\1Bug: \\3 [\\2]")))))
  19795. (defun org-install-agenda-files-menu ()
  19796. (let ((bl (buffer-list)))
  19797. (save-excursion
  19798. (while bl
  19799. (set-buffer (pop bl))
  19800. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19801. (when (derived-mode-p 'org-mode)
  19802. (easy-menu-change
  19803. '("Org") "File List for Agenda"
  19804. (append
  19805. (list
  19806. ["Edit File List" (org-edit-agenda-file-list) t]
  19807. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19808. ["Remove Current File from List" org-remove-file t]
  19809. ["Cycle through agenda files" org-cycle-agenda-files t]
  19810. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19811. "--")
  19812. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  19813. ;;;; Documentation
  19814. (defun org-require-autoloaded-modules ()
  19815. (interactive)
  19816. (mapc #'require
  19817. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19818. org-table org-timer)))
  19819. ;;;###autoload
  19820. (defun org-reload (&optional uncompiled)
  19821. "Reload all org lisp files.
  19822. With prefix arg UNCOMPILED, load the uncompiled versions."
  19823. (interactive "P")
  19824. (require 'loadhist)
  19825. (let* ((org-dir (org-find-library-dir "org"))
  19826. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19827. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19828. (remove-re (format "\\`%s\\'"
  19829. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19830. (feats (delete-dups
  19831. (mapcar 'file-name-sans-extension
  19832. (mapcar 'file-name-nondirectory
  19833. (delq nil
  19834. (mapcar 'feature-file
  19835. features))))))
  19836. (lfeat (append
  19837. (sort
  19838. (setq feats
  19839. (delq nil (mapcar
  19840. (lambda (f)
  19841. (if (and (string-match feature-re f)
  19842. (not (string-match remove-re f)))
  19843. f nil))
  19844. feats)))
  19845. 'string-lessp)
  19846. (list "org-version" "org")))
  19847. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19848. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19849. load-uncore load-misses)
  19850. (setq load-misses
  19851. (delq 't
  19852. (mapcar (lambda (f)
  19853. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19854. (and (string= org-dir contrib-dir)
  19855. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19856. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19857. (add-to-list 'load-uncore f 'append)
  19858. 't)
  19859. f))
  19860. lfeat)))
  19861. (when load-uncore
  19862. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19863. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19864. (if load-misses
  19865. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19866. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19867. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19868. ;;;###autoload
  19869. (defun org-customize ()
  19870. "Call the customize function with org as argument."
  19871. (interactive)
  19872. (org-load-modules-maybe)
  19873. (org-require-autoloaded-modules)
  19874. (customize-browse 'org))
  19875. (defun org-create-customize-menu ()
  19876. "Create a full customization menu for Org mode, insert it into the menu."
  19877. (interactive)
  19878. (org-load-modules-maybe)
  19879. (org-require-autoloaded-modules)
  19880. (if (fboundp 'customize-menu-create)
  19881. (progn
  19882. (easy-menu-change
  19883. '("Org") "Customize"
  19884. `(["Browse Org group" org-customize t]
  19885. "--"
  19886. ,(customize-menu-create 'org)
  19887. ["Set" Custom-set t]
  19888. ["Save" Custom-save t]
  19889. ["Reset to Current" Custom-reset-current t]
  19890. ["Reset to Saved" Custom-reset-saved t]
  19891. ["Reset to Standard Settings" Custom-reset-standard t]))
  19892. (message "\"Org\"-menu now contains full customization menu"))
  19893. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19894. ;;;; Miscellaneous stuff
  19895. ;;; Generally useful functions
  19896. (defun org-get-at-eol (property n)
  19897. "Get text property PROPERTY at the end of line less N characters."
  19898. (get-text-property (- (point-at-eol) n) property))
  19899. (defun org-find-text-property-in-string (prop s)
  19900. "Return the first non-nil value of property PROP in string S."
  19901. (or (get-text-property 0 prop s)
  19902. (get-text-property (or (next-single-property-change 0 prop s) 0)
  19903. prop s)))
  19904. (defun org-display-warning (message)
  19905. "Display the given MESSAGE as a warning."
  19906. (display-warning 'org message :warning))
  19907. (defun org-eval (form)
  19908. "Eval FORM and return result."
  19909. (condition-case error
  19910. (eval form)
  19911. (error (format "%%![Error: %s]" error))))
  19912. (defun org-in-clocktable-p ()
  19913. "Check if the cursor is in a clocktable."
  19914. (let ((pos (point)) start)
  19915. (save-excursion
  19916. (end-of-line 1)
  19917. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19918. (setq start (match-beginning 0))
  19919. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19920. (>= (match-end 0) pos)
  19921. start))))
  19922. (defun org-in-verbatim-emphasis ()
  19923. (save-match-data
  19924. (and (org-in-regexp org-verbatim-re 2)
  19925. (>= (point) (match-beginning 3))
  19926. (<= (point) (match-end 4)))))
  19927. (defun org-overlay-display (ovl text &optional face evap)
  19928. "Make overlay OVL display TEXT with face FACE."
  19929. (overlay-put ovl 'display text)
  19930. (if face (overlay-put ovl 'face face))
  19931. (if evap (overlay-put ovl 'evaporate t)))
  19932. (defun org-overlay-before-string (ovl text &optional face evap)
  19933. "Make overlay OVL display TEXT with face FACE."
  19934. (if face (org-add-props text nil 'face face))
  19935. (overlay-put ovl 'before-string text)
  19936. (if evap (overlay-put ovl 'evaporate t)))
  19937. (defun org-find-overlays (prop &optional pos delete)
  19938. "Find all overlays specifying PROP at POS or point.
  19939. If DELETE is non-nil, delete all those overlays."
  19940. (let (found)
  19941. (dolist (ov (overlays-at (or pos (point))) found)
  19942. (cond ((not (overlay-get ov prop)))
  19943. (delete (delete-overlay ov))
  19944. (t (push ov found))))))
  19945. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19946. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19947. (if (and marker (marker-buffer marker)
  19948. (buffer-live-p (marker-buffer marker)))
  19949. (progn
  19950. (pop-to-buffer-same-window (marker-buffer marker))
  19951. (when (or (> marker (point-max)) (< marker (point-min)))
  19952. (widen))
  19953. (goto-char marker)
  19954. (org-show-context 'org-goto))
  19955. (if bookmark
  19956. (bookmark-jump bookmark)
  19957. (error "Cannot find location"))))
  19958. (defun org-quote-csv-field (s)
  19959. "Quote field for inclusion in CSV material."
  19960. (if (string-match "[\",]" s)
  19961. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19962. s))
  19963. (defun org-force-self-insert (N)
  19964. "Needed to enforce self-insert under remapping."
  19965. (interactive "p")
  19966. (self-insert-command N))
  19967. (defun org-string-width (s)
  19968. "Compute width of string, ignoring invisible characters.
  19969. This ignores character with invisibility property `org-link', and also
  19970. characters with property `org-cwidth', because these will become invisible
  19971. upon the next fontification round."
  19972. (let (b l)
  19973. (when (or (eq t buffer-invisibility-spec)
  19974. (assq 'org-link buffer-invisibility-spec))
  19975. (while (setq b (text-property-any 0 (length s)
  19976. 'invisible 'org-link s))
  19977. (setq s (concat (substring s 0 b)
  19978. (substring s (or (next-single-property-change
  19979. b 'invisible s)
  19980. (length s)))))))
  19981. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  19982. (setq s (concat (substring s 0 b)
  19983. (substring s (or (next-single-property-change
  19984. b 'org-cwidth s)
  19985. (length s))))))
  19986. (setq l (string-width s) b -1)
  19987. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  19988. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  19989. l))
  19990. (defun org-shorten-string (s maxlength)
  19991. "Shorten string S so that it is no longer than MAXLENGTH characters.
  19992. If the string is shorter or has length MAXLENGTH, just return the
  19993. original string. If it is longer, the functions finds a space in the
  19994. string, breaks this string off at that locations and adds three dots
  19995. as ellipsis. Including the ellipsis, the string will not be longer
  19996. than MAXLENGTH. If finding a good breaking point in the string does
  19997. not work, the string is just chopped off in the middle of a word
  19998. if necessary."
  19999. (if (<= (length s) maxlength)
  20000. s
  20001. (let* ((n (max (- maxlength 4) 1))
  20002. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20003. (if (string-match re s)
  20004. (concat (match-string 1 s) "...")
  20005. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20006. (defun org-get-indentation (&optional line)
  20007. "Get the indentation of the current line, interpreting tabs.
  20008. When LINE is given, assume it represents a line and compute its indentation."
  20009. (if line
  20010. (when (string-match "^ *" (org-remove-tabs line))
  20011. (match-end 0))
  20012. (save-excursion
  20013. (beginning-of-line 1)
  20014. (skip-chars-forward " \t")
  20015. (current-column))))
  20016. (defun org-get-string-indentation (s)
  20017. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20018. (let ((n -1) (i 0) (w tab-width) c)
  20019. (catch 'exit
  20020. (while (< (setq n (1+ n)) (length s))
  20021. (setq c (aref s n))
  20022. (cond ((= c ?\ ) (setq i (1+ i)))
  20023. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20024. (t (throw 'exit t)))))
  20025. i))
  20026. (defun org-remove-tabs (s &optional width)
  20027. "Replace tabulators in S with spaces.
  20028. Assumes that s is a single line, starting in column 0."
  20029. (setq width (or width tab-width))
  20030. (while (string-match "\t" s)
  20031. (setq s (replace-match
  20032. (make-string
  20033. (- (* width (/ (+ (match-beginning 0) width) width))
  20034. (match-beginning 0)) ?\ )
  20035. t t s)))
  20036. s)
  20037. (defun org-fix-indentation (line ind)
  20038. "Fix indentation in LINE.
  20039. IND is a cons cell with target and minimum indentation.
  20040. If the current indentation in LINE is smaller than the minimum,
  20041. leave it alone. If it is larger than ind, set it to the target."
  20042. (let* ((l (org-remove-tabs line))
  20043. (i (org-get-indentation l))
  20044. (i1 (car ind)) (i2 (cdr ind)))
  20045. (when (>= i i2) (setq l (substring line i2)))
  20046. (if (> i1 0)
  20047. (concat (make-string i1 ?\ ) l)
  20048. l)))
  20049. (defun org-remove-indentation (code &optional n)
  20050. "Remove maximum common indentation in string CODE and return it.
  20051. N may optionally be the number of columns to remove. Return CODE
  20052. as-is if removal failed."
  20053. (with-temp-buffer
  20054. (insert code)
  20055. (if (org-do-remove-indentation n) (buffer-string) code)))
  20056. (defun org-do-remove-indentation (&optional n)
  20057. "Remove the maximum common indentation from the buffer.
  20058. When optional argument N is a positive integer, remove exactly
  20059. that much characters from indentation, if possible. Return nil
  20060. if it fails."
  20061. (catch :exit
  20062. (goto-char (point-min))
  20063. ;; Find maximum common indentation, if not specified.
  20064. (let ((n (or n
  20065. (let ((min-ind (point-max)))
  20066. (save-excursion
  20067. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20068. (let ((ind (1- (current-column))))
  20069. (if (zerop ind) (throw :exit nil)
  20070. (setq min-ind (min min-ind ind))))))
  20071. min-ind))))
  20072. (if (zerop n) (throw :exit nil)
  20073. ;; Remove exactly N indentation, but give up if not possible.
  20074. (while (not (eobp))
  20075. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20076. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20077. ((< ind n) (throw :exit nil))
  20078. (t (indent-line-to (- ind n))))
  20079. (forward-line)))
  20080. ;; Signal success.
  20081. t))))
  20082. (defun org-fill-template (template alist)
  20083. "Find each %key of ALIST in TEMPLATE and replace it."
  20084. (let ((case-fold-search nil))
  20085. (dolist (entry (sort (copy-sequence alist)
  20086. (lambda (a b) (< (length (car a)) (length (car b))))))
  20087. (setq template
  20088. (replace-regexp-in-string
  20089. (concat "%" (regexp-quote (car entry)))
  20090. (or (cdr entry) "") template t t)))
  20091. template))
  20092. (defun org-base-buffer (buffer)
  20093. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20094. (if (not buffer)
  20095. buffer
  20096. (or (buffer-base-buffer buffer)
  20097. buffer)))
  20098. (defun org-wrap (string &optional width lines)
  20099. "Wrap string to either a number of lines, or a width in characters.
  20100. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20101. that costs. If there is a word longer than WIDTH, the text is actually
  20102. wrapped to the length of that word.
  20103. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20104. many lines, whatever width that takes.
  20105. The return value is a list of lines, without newlines at the end."
  20106. (let* ((words (org-split-string string "[ \t\n]+"))
  20107. (maxword (apply 'max (mapcar 'org-string-width words)))
  20108. w ll)
  20109. (cond (width
  20110. (org-do-wrap words (max maxword width)))
  20111. (lines
  20112. (setq w maxword)
  20113. (setq ll (org-do-wrap words maxword))
  20114. (if (<= (length ll) lines)
  20115. ll
  20116. (setq ll words)
  20117. (while (> (length ll) lines)
  20118. (setq w (1+ w))
  20119. (setq ll (org-do-wrap words w)))
  20120. ll))
  20121. (t (error "Cannot wrap this")))))
  20122. (defun org-do-wrap (words width)
  20123. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20124. (let (lines line)
  20125. (while words
  20126. (setq line (pop words))
  20127. (while (and words (< (+ (length line) (length (car words))) width))
  20128. (setq line (concat line " " (pop words))))
  20129. (setq lines (push line lines)))
  20130. (nreverse lines)))
  20131. (defun org-split-string (string &optional separators)
  20132. "Splits STRING into substrings at SEPARATORS.
  20133. SEPARATORS is a regular expression.
  20134. No empty strings are returned if there are matches at the beginning
  20135. and end of string."
  20136. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20137. (let ((start 0) notfirst list)
  20138. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20139. (if (and notfirst
  20140. (= start (match-beginning 0))
  20141. (< start (length string)))
  20142. (1+ start) start))
  20143. (< (match-beginning 0) (length string)))
  20144. (setq notfirst t)
  20145. (or (eq (match-beginning 0) 0)
  20146. (and (eq (match-beginning 0) (match-end 0))
  20147. (eq (match-beginning 0) start))
  20148. (push (substring string start (match-beginning 0)) list))
  20149. (setq start (match-end 0)))
  20150. (or (eq start (length string))
  20151. (push (substring string start) list))
  20152. (nreverse list)))
  20153. (defun org-quote-vert (s)
  20154. "Replace \"|\" with \"\\vert\"."
  20155. (while (string-match "|" s)
  20156. (setq s (replace-match "\\vert" t t s)))
  20157. s)
  20158. (defun org-uuidgen-p (s)
  20159. "Is S an ID created by UUIDGEN?"
  20160. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20161. (defun org-in-src-block-p (&optional inside)
  20162. "Whether point is in a code source block.
  20163. When INSIDE is non-nil, don't consider we are within a src block
  20164. when point is at #+BEGIN_SRC or #+END_SRC."
  20165. (let ((case-fold-search t))
  20166. (or (and (eq (get-char-property (point) 'src-block) t))
  20167. (and (not inside)
  20168. (save-match-data
  20169. (save-excursion
  20170. (beginning-of-line)
  20171. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20172. (defun org-context ()
  20173. "Return a list of contexts of the current cursor position.
  20174. If several contexts apply, all are returned.
  20175. Each context entry is a list with a symbol naming the context, and
  20176. two positions indicating start and end of the context. Possible
  20177. contexts are:
  20178. :headline anywhere in a headline
  20179. :headline-stars on the leading stars in a headline
  20180. :todo-keyword on a TODO keyword (including DONE) in a headline
  20181. :tags on the TAGS in a headline
  20182. :priority on the priority cookie in a headline
  20183. :item on the first line of a plain list item
  20184. :item-bullet on the bullet/number of a plain list item
  20185. :checkbox on the checkbox in a plain list item
  20186. :table in an Org table
  20187. :table-special on a special filed in a table
  20188. :table-table in a table.el table
  20189. :clocktable in a clocktable
  20190. :src-block in a source block
  20191. :link on a hyperlink
  20192. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20193. :target on a <<target>>
  20194. :radio-target on a <<<radio-target>>>
  20195. :latex-fragment on a LaTeX fragment
  20196. :latex-preview on a LaTeX fragment with overlaid preview image
  20197. This function expects the position to be visible because it uses font-lock
  20198. faces as a help to recognize the following contexts: :table-special, :link,
  20199. and :keyword."
  20200. (let* ((f (get-text-property (point) 'face))
  20201. (faces (if (listp f) f (list f)))
  20202. (case-fold-search t)
  20203. (p (point)) clist o)
  20204. ;; First the large context
  20205. (cond
  20206. ((org-at-heading-p t)
  20207. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20208. (when (progn
  20209. (beginning-of-line 1)
  20210. (looking-at org-todo-line-tags-regexp))
  20211. (push (org-point-in-group p 1 :headline-stars) clist)
  20212. (push (org-point-in-group p 2 :todo-keyword) clist)
  20213. (push (org-point-in-group p 4 :tags) clist))
  20214. (goto-char p)
  20215. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20216. (when (looking-at "\\[#[A-Z0-9]\\]")
  20217. (push (org-point-in-group p 0 :priority) clist)))
  20218. ((org-at-item-p)
  20219. (push (org-point-in-group p 2 :item-bullet) clist)
  20220. (push (list :item (point-at-bol)
  20221. (save-excursion (org-end-of-item) (point)))
  20222. clist)
  20223. (and (org-at-item-checkbox-p)
  20224. (push (org-point-in-group p 0 :checkbox) clist)))
  20225. ((org-at-table-p)
  20226. (push (list :table (org-table-begin) (org-table-end)) clist)
  20227. (when (memq 'org-formula faces)
  20228. (push (list :table-special
  20229. (previous-single-property-change p 'face)
  20230. (next-single-property-change p 'face)) clist)))
  20231. ((org-at-table-p 'any)
  20232. (push (list :table-table) clist)))
  20233. (goto-char p)
  20234. (let ((case-fold-search t))
  20235. ;; New the "medium" contexts: clocktables, source blocks
  20236. (cond ((org-in-clocktable-p)
  20237. (push (list :clocktable
  20238. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20239. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20240. (match-beginning 1))
  20241. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20242. (match-end 0))) clist))
  20243. ((org-in-src-block-p)
  20244. (push (list :src-block
  20245. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20246. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20247. (match-beginning 1))
  20248. (and (search-forward "#+END_SRC" nil t)
  20249. (match-beginning 0))) clist))))
  20250. (goto-char p)
  20251. ;; Now the small context
  20252. (cond
  20253. ((org-at-timestamp-p)
  20254. (push (org-point-in-group p 0 :timestamp) clist))
  20255. ((memq 'org-link faces)
  20256. (push (list :link
  20257. (previous-single-property-change p 'face)
  20258. (next-single-property-change p 'face)) clist))
  20259. ((memq 'org-special-keyword faces)
  20260. (push (list :keyword
  20261. (previous-single-property-change p 'face)
  20262. (next-single-property-change p 'face)) clist))
  20263. ((org-at-target-p)
  20264. (push (org-point-in-group p 0 :target) clist)
  20265. (goto-char (1- (match-beginning 0)))
  20266. (when (looking-at org-radio-target-regexp)
  20267. (push (org-point-in-group p 0 :radio-target) clist))
  20268. (goto-char p))
  20269. ((setq o (cl-some
  20270. (lambda (o)
  20271. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20272. o))
  20273. (overlays-at (point))))
  20274. (push (list :latex-fragment
  20275. (overlay-start o) (overlay-end o)) clist)
  20276. (push (list :latex-preview
  20277. (overlay-start o) (overlay-end o)) clist))
  20278. ((org-inside-LaTeX-fragment-p)
  20279. ;; FIXME: positions wrong.
  20280. (push (list :latex-fragment (point) (point)) clist)))
  20281. (setq clist (nreverse (delq nil clist)))
  20282. clist))
  20283. (defun org-in-regexp (regexp &optional nlines visually)
  20284. "Check if point is inside a match of REGEXP.
  20285. Normally only the current line is checked, but you can include
  20286. NLINES extra lines around point into the search. If VISUALLY is
  20287. set, require that the cursor is not after the match but really
  20288. on, so that the block visually is on the match.
  20289. Return nil or a cons cell (BEG . END) where BEG and END are,
  20290. respectively, the positions at the beginning and the end of the
  20291. match."
  20292. (catch :exit
  20293. (let ((pos (point))
  20294. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20295. (save-excursion
  20296. (beginning-of-line (- 1 (or nlines 0)))
  20297. (while (and (re-search-forward regexp eol t)
  20298. (<= (match-beginning 0) pos))
  20299. (let ((end (match-end 0)))
  20300. (when (or (> end pos) (and (= end pos) (not visually)))
  20301. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20302. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20303. "Non-nil when point is between matches of START-RE and END-RE.
  20304. Also return a non-nil value when point is on one of the matches.
  20305. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20306. buffer positions. Default values are the positions of headlines
  20307. surrounding the point.
  20308. The functions returns a cons cell whose car (resp. cdr) is the
  20309. position before START-RE (resp. after END-RE)."
  20310. (save-match-data
  20311. (let ((pos (point))
  20312. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20313. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20314. beg end)
  20315. (save-excursion
  20316. ;; Point is on a block when on START-RE or if START-RE can be
  20317. ;; found before it...
  20318. (and (or (org-in-regexp start-re)
  20319. (re-search-backward start-re limit-up t))
  20320. (setq beg (match-beginning 0))
  20321. ;; ... and END-RE after it...
  20322. (goto-char (match-end 0))
  20323. (re-search-forward end-re limit-down t)
  20324. (> (setq end (match-end 0)) pos)
  20325. ;; ... without another START-RE in-between.
  20326. (goto-char (match-beginning 0))
  20327. (not (re-search-backward start-re (1+ beg) t))
  20328. ;; Return value.
  20329. (cons beg end))))))
  20330. (defun org-in-block-p (names)
  20331. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20332. NAMES is a list of strings containing names of blocks.
  20333. Return first block name matched, or nil. Beware that in case of
  20334. nested blocks, the returned name may not belong to the closest
  20335. block from point."
  20336. (save-match-data
  20337. (catch 'exit
  20338. (let ((case-fold-search t)
  20339. (lim-up (save-excursion (outline-previous-heading)))
  20340. (lim-down (save-excursion (outline-next-heading))))
  20341. (dolist (name names)
  20342. (let ((n (regexp-quote name)))
  20343. (when (org-between-regexps-p
  20344. (concat "^[ \t]*#\\+begin_" n)
  20345. (concat "^[ \t]*#\\+end_" n)
  20346. lim-up lim-down)
  20347. (throw 'exit n)))))
  20348. nil)))
  20349. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20350. "Call `multi-occur' with buffers for all agenda files."
  20351. (interactive "sOrg-files matching: ")
  20352. (let* ((files (org-agenda-files))
  20353. (tnames (mapcar #'file-truename files))
  20354. (extra org-agenda-text-search-extra-files))
  20355. (when (eq (car extra) 'agenda-archives)
  20356. (setq extra (cdr extra))
  20357. (setq files (org-add-archive-files files)))
  20358. (dolist (f extra)
  20359. (unless (member (file-truename f) tnames)
  20360. (unless (member f files) (setq files (append files (list f))))
  20361. (setq tnames (append tnames (list (file-truename f))))))
  20362. (multi-occur
  20363. (mapcar (lambda (x)
  20364. (with-current-buffer
  20365. ;; FIXME: Why not just (find-file-noselect x)?
  20366. ;; Is it to avoid the "revert buffer" prompt?
  20367. (or (get-file-buffer x) (find-file-noselect x))
  20368. (widen)
  20369. (current-buffer)))
  20370. files)
  20371. regexp)))
  20372. (add-hook 'occur-mode-find-occurrence-hook
  20373. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20374. (defun org-occur-link-in-agenda-files ()
  20375. "Create a link and search for it in the agendas.
  20376. The link is not stored in `org-stored-links', it is just created
  20377. for the search purpose."
  20378. (interactive)
  20379. (let ((link (condition-case nil
  20380. (org-store-link nil)
  20381. (error "Unable to create a link to here"))))
  20382. (org-occur-in-agenda-files (regexp-quote link))))
  20383. (defun org-reverse-string (string)
  20384. "Return the reverse of STRING."
  20385. (apply 'string (reverse (string-to-list string))))
  20386. ;; defsubst org-uniquify must be defined before first use
  20387. (defun org-uniquify-alist (alist)
  20388. "Merge elements of ALIST with the same key.
  20389. For example, in this alist:
  20390. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20391. => \\='((a 1 3) (b 2))
  20392. merge (a 1) and (a 3) into (a 1 3).
  20393. The function returns the new ALIST."
  20394. (let (rtn)
  20395. (dolist (e alist rtn)
  20396. (let (n)
  20397. (if (not (assoc (car e) rtn))
  20398. (push e rtn)
  20399. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20400. (setq rtn (assq-delete-all (car e) rtn))
  20401. (push n rtn))))))
  20402. (defun org-delete-all (elts list)
  20403. "Remove all elements in ELTS from LIST.
  20404. Comparison is done with `equal'. It is a destructive operation
  20405. that may remove elements by altering the list structure."
  20406. (while elts
  20407. (setq list (delete (pop elts) list)))
  20408. list)
  20409. (defun org-back-over-empty-lines ()
  20410. "Move backwards over whitespace, to the beginning of the first empty line.
  20411. Returns the number of empty lines passed."
  20412. (let ((pos (point)))
  20413. (if (cdr (assq 'heading org-blank-before-new-entry))
  20414. (skip-chars-backward " \t\n\r")
  20415. (unless (eobp)
  20416. (forward-line -1)))
  20417. (beginning-of-line 2)
  20418. (goto-char (min (point) pos))
  20419. (count-lines (point) pos)))
  20420. (defun org-skip-whitespace ()
  20421. (skip-chars-forward " \t\n\r"))
  20422. (defun org-point-in-group (point group &optional context)
  20423. "Check if POINT is in match-group GROUP.
  20424. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20425. match. If the match group does not exist or point is not inside it,
  20426. return nil."
  20427. (and (match-beginning group)
  20428. (>= point (match-beginning group))
  20429. (<= point (match-end group))
  20430. (if context
  20431. (list context (match-beginning group) (match-end group))
  20432. t)))
  20433. (defun org-switch-to-buffer-other-window (&rest args)
  20434. "Switch to buffer in a second window on the current frame.
  20435. In particular, do not allow pop-up frames.
  20436. Returns the newly created buffer."
  20437. (org-no-popups
  20438. (apply 'switch-to-buffer-other-window args)))
  20439. (defun org-combine-plists (&rest plists)
  20440. "Create a single property list from all plists in PLISTS.
  20441. The process starts by copying the first list, and then setting properties
  20442. from the other lists. Settings in the last list are the most significant
  20443. ones and overrule settings in the other lists."
  20444. (let ((rtn (copy-sequence (pop plists)))
  20445. p v ls)
  20446. (while plists
  20447. (setq ls (pop plists))
  20448. (while ls
  20449. (setq p (pop ls) v (pop ls))
  20450. (setq rtn (plist-put rtn p v))))
  20451. rtn))
  20452. (defun org-replace-escapes (string table)
  20453. "Replace %-escapes in STRING with values in TABLE.
  20454. TABLE is an association list with keys like \"%a\" and string values.
  20455. The sequences in STRING may contain normal field width and padding information,
  20456. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20457. so values can contain further %-escapes if they are define later in TABLE."
  20458. (let ((tbl (copy-alist table))
  20459. (case-fold-search nil)
  20460. (pchg 0)
  20461. re rpl)
  20462. (dolist (e tbl)
  20463. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20464. (when (and (cdr e) (string-match re (cdr e)))
  20465. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20466. (safe "SREF"))
  20467. (add-text-properties 0 3 (list 'sref sref) safe)
  20468. (setcdr e (replace-match safe t t (cdr e)))))
  20469. (while (string-match re string)
  20470. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20471. (cdr e)))
  20472. (setq string (replace-match rpl t t string))))
  20473. (while (setq pchg (next-property-change pchg string))
  20474. (let ((sref (get-text-property pchg 'sref string)))
  20475. (when (and sref (string-match "SREF" string pchg))
  20476. (setq string (replace-match sref t t string)))))
  20477. string))
  20478. (defun org-find-base-buffer-visiting (file)
  20479. "Like `find-buffer-visiting' but always return the base buffer and
  20480. not an indirect buffer."
  20481. (let ((buf (or (get-file-buffer file)
  20482. (find-buffer-visiting file))))
  20483. (if buf
  20484. (or (buffer-base-buffer buf) buf)
  20485. nil)))
  20486. ;;; TODO: Only called once, from ox-odt which should probably use
  20487. ;;; org-export-inline-image-p or something.
  20488. (defun org-file-image-p (file)
  20489. "Return non-nil if FILE is an image."
  20490. (save-match-data
  20491. (string-match (image-file-name-regexp) file)))
  20492. (defun org-get-cursor-date (&optional with-time)
  20493. "Return the date at cursor in as a time.
  20494. This works in the calendar and in the agenda, anywhere else it just
  20495. returns the current time.
  20496. If WITH-TIME is non-nil, returns the time of the event at point (in
  20497. the agenda) or the current time of the day."
  20498. (let (date day defd tp hod mod)
  20499. (when with-time
  20500. (setq tp (get-text-property (point) 'time))
  20501. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20502. (setq hod (string-to-number (match-string 1 tp))
  20503. mod (string-to-number (match-string 2 tp))))
  20504. (or tp (let ((now (decode-time)))
  20505. (setq hod (nth 2 now)
  20506. mod (nth 1 now)))))
  20507. (cond
  20508. ((eq major-mode 'calendar-mode)
  20509. (setq date (calendar-cursor-to-date)
  20510. defd (encode-time 0 (or mod 0) (or hod 0)
  20511. (nth 1 date) (nth 0 date) (nth 2 date))))
  20512. ((eq major-mode 'org-agenda-mode)
  20513. (setq day (get-text-property (point) 'day))
  20514. (when day
  20515. (setq date (calendar-gregorian-from-absolute day)
  20516. defd (encode-time 0 (or mod 0) (or hod 0)
  20517. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20518. (or defd (current-time))))
  20519. (defun org-mark-subtree (&optional up)
  20520. "Mark the current subtree.
  20521. This puts point at the start of the current subtree, and mark at
  20522. the end. If a numeric prefix UP is given, move up into the
  20523. hierarchy of headlines by UP levels before marking the subtree."
  20524. (interactive "P")
  20525. (org-with-limited-levels
  20526. (cond ((org-at-heading-p) (beginning-of-line))
  20527. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20528. (t (outline-previous-visible-heading 1))))
  20529. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20530. (if (called-interactively-p 'any)
  20531. (call-interactively 'org-mark-element)
  20532. (org-mark-element)))
  20533. (defun org-file-newer-than-p (file time)
  20534. "Non-nil if FILE is newer than TIME.
  20535. FILE is a filename, as a string, TIME is a list of integers, as
  20536. returned by, e.g., `current-time'."
  20537. (and (file-exists-p file)
  20538. ;; Only compare times up to whole seconds as some file-systems
  20539. ;; (e.g. HFS+) do not retain any finer granularity. As
  20540. ;; a consequence, make sure we return non-nil when the two
  20541. ;; times are equal.
  20542. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20543. (cl-subseq time 0 2)))))
  20544. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20545. "Compile a SOURCE file using PROCESS.
  20546. PROCESS is either a function or a list of shell commands, as
  20547. strings. EXT is a file extension, without the leading dot, as
  20548. a string. It is used to check if the process actually succeeded.
  20549. PROCESS must create a file with the same base name and directory
  20550. as SOURCE, but ending with EXT. The function then returns its
  20551. filename. Otherwise, it raises an error. The error message can
  20552. then be refined by providing string ERR-MSG, which is appended to
  20553. the standard message.
  20554. If PROCESS is a function, it is called with a single argument:
  20555. the SOURCE file.
  20556. If it is a list of commands, each of them is called using
  20557. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20558. %O are replaced with, respectively, SOURCE base name, name, full
  20559. name, directory and absolute output file name. It is possible,
  20560. however, to use more place-holders by specifying them in optional
  20561. argument SPEC, as an alist following the pattern
  20562. (CHARACTER . REPLACEMENT-STRING).
  20563. When PROCESS is a list of commands, optional argument LOG-BUF can
  20564. be set to a buffer or a buffer name. `shell-command' then uses
  20565. it for output."
  20566. (let* ((base-name (file-name-base source))
  20567. (full-name (file-truename source))
  20568. (out-dir (or (file-name-directory source) "./"))
  20569. (output (expand-file-name (concat base-name "." ext) out-dir))
  20570. (time (current-time))
  20571. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20572. (save-window-excursion
  20573. (pcase process
  20574. ((pred functionp) (funcall process (shell-quote-argument source)))
  20575. ((pred consp)
  20576. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20577. (spec (append spec
  20578. `((?b . ,(shell-quote-argument base-name))
  20579. (?f . ,(shell-quote-argument source))
  20580. (?F . ,(shell-quote-argument full-name))
  20581. (?o . ,(shell-quote-argument out-dir))
  20582. (?O . ,(shell-quote-argument output))))))
  20583. (dolist (command process)
  20584. (shell-command (format-spec command spec) log-buf))
  20585. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20586. (_ (error "No valid command to process %S%s" source err-msg))))
  20587. ;; Check for process failure. Output file is expected to be
  20588. ;; located in the same directory as SOURCE.
  20589. (unless (org-file-newer-than-p output time)
  20590. (error (format "File %S wasn't produced%s" output err-msg)))
  20591. output))
  20592. ;;; Indentation
  20593. (defun org--get-expected-indentation (element contentsp)
  20594. "Expected indentation column for current line, according to ELEMENT.
  20595. ELEMENT is an element containing point. CONTENTSP is non-nil
  20596. when indentation is to be computed according to contents of
  20597. ELEMENT."
  20598. (let ((type (org-element-type element))
  20599. (start (org-element-property :begin element))
  20600. (post-affiliated (org-element-property :post-affiliated element)))
  20601. (org-with-wide-buffer
  20602. (cond
  20603. (contentsp
  20604. (cl-case type
  20605. ((diary-sexp footnote-definition) 0)
  20606. ((headline inlinetask nil)
  20607. (if (not org-adapt-indentation) 0
  20608. (let ((level (org-current-level)))
  20609. (if level (1+ level) 0))))
  20610. ((item plain-list) (org-list-item-body-column post-affiliated))
  20611. (t
  20612. (goto-char start)
  20613. (org-get-indentation))))
  20614. ((memq type '(headline inlinetask nil))
  20615. (if (org-match-line "[ \t]*$")
  20616. (org--get-expected-indentation element t)
  20617. 0))
  20618. ((memq type '(diary-sexp footnote-definition)) 0)
  20619. ;; First paragraph of a footnote definition or an item.
  20620. ;; Indent like parent.
  20621. ((< (line-beginning-position) start)
  20622. (org--get-expected-indentation
  20623. (org-element-property :parent element) t))
  20624. ;; At first line: indent according to previous sibling, if any,
  20625. ;; ignoring footnote definitions and inline tasks, or parent's
  20626. ;; contents.
  20627. ((= (line-beginning-position) start)
  20628. (catch 'exit
  20629. (while t
  20630. (if (= (point-min) start) (throw 'exit 0)
  20631. (goto-char (1- start))
  20632. (let* ((previous (org-element-at-point))
  20633. (parent previous))
  20634. (while (and parent (<= (org-element-property :end parent) start))
  20635. (setq previous parent
  20636. parent (org-element-property :parent parent)))
  20637. (cond
  20638. ((not previous) (throw 'exit 0))
  20639. ((> (org-element-property :end previous) start)
  20640. (throw 'exit (org--get-expected-indentation previous t)))
  20641. ((memq (org-element-type previous)
  20642. '(footnote-definition inlinetask))
  20643. (setq start (org-element-property :begin previous)))
  20644. (t (goto-char (org-element-property :begin previous))
  20645. (throw 'exit
  20646. (if (bolp) (org-get-indentation)
  20647. ;; At first paragraph in an item or
  20648. ;; a footnote definition.
  20649. (org--get-expected-indentation
  20650. (org-element-property :parent previous) t))))))))))
  20651. ;; Otherwise, move to the first non-blank line above.
  20652. (t
  20653. (beginning-of-line)
  20654. (let ((pos (point)))
  20655. (skip-chars-backward " \r\t\n")
  20656. (cond
  20657. ;; Two blank lines end a footnote definition or a plain
  20658. ;; list. When we indent an empty line after them, the
  20659. ;; containing list or footnote definition is over, so it
  20660. ;; qualifies as a previous sibling. Therefore, we indent
  20661. ;; like its first line.
  20662. ((and (memq type '(footnote-definition plain-list))
  20663. (> (count-lines (point) pos) 2))
  20664. (goto-char start)
  20665. (org-get-indentation))
  20666. ;; Line above is the first one of a paragraph at the
  20667. ;; beginning of an item or a footnote definition. Indent
  20668. ;; like parent.
  20669. ((< (line-beginning-position) start)
  20670. (org--get-expected-indentation
  20671. (org-element-property :parent element) t))
  20672. ;; Line above is the beginning of an element, i.e., point
  20673. ;; was originally on the blank lines between element's start
  20674. ;; and contents.
  20675. ((= (line-beginning-position) post-affiliated)
  20676. (org--get-expected-indentation element t))
  20677. ;; POS is after contents in a greater element. Indent like
  20678. ;; the beginning of the element.
  20679. ((and (memq type org-element-greater-elements)
  20680. (let ((cend (org-element-property :contents-end element)))
  20681. (and cend (<= cend pos))))
  20682. ;; As a special case, if point is at the end of a footnote
  20683. ;; definition or an item, indent like the very last element
  20684. ;; within. If that last element is an item, indent like
  20685. ;; its contents.
  20686. (if (memq type '(footnote-definition item plain-list))
  20687. (let ((last (org-element-at-point)))
  20688. (goto-char pos)
  20689. (org--get-expected-indentation
  20690. last (eq (org-element-type last) 'item)))
  20691. (goto-char start)
  20692. (org-get-indentation)))
  20693. ;; In any other case, indent like the current line.
  20694. (t (org-get-indentation)))))))))
  20695. (defun org--align-node-property ()
  20696. "Align node property at point.
  20697. Alignment is done according to `org-property-format', which see."
  20698. (when (save-excursion
  20699. (beginning-of-line)
  20700. (looking-at org-property-re))
  20701. (replace-match
  20702. (concat (match-string 4)
  20703. (org-trim
  20704. (format org-property-format (match-string 1) (match-string 3))))
  20705. t t)))
  20706. (defun org-indent-line ()
  20707. "Indent line depending on context.
  20708. Indentation is done according to the following rules:
  20709. - Footnote definitions, diary sexps, headlines and inline tasks
  20710. have to start at column 0.
  20711. - On the very first line of an element, consider, in order, the
  20712. next rules until one matches:
  20713. 1. If there's a sibling element before, ignoring footnote
  20714. definitions and inline tasks, indent like its first line.
  20715. 2. If element has a parent, indent like its contents. More
  20716. precisely, if parent is an item, indent after the
  20717. description part, if any, or the bullet (see
  20718. `org-list-description-max-indent'). Else, indent like
  20719. parent's first line.
  20720. 3. Otherwise, indent relatively to current level, if
  20721. `org-adapt-indentation' is non-nil, or to left margin.
  20722. - On a blank line at the end of an element, indent according to
  20723. the type of the element. More precisely
  20724. 1. If element is a plain list, an item, or a footnote
  20725. definition, indent like the very last element within.
  20726. 2. If element is a paragraph, indent like its last non blank
  20727. line.
  20728. 3. Otherwise, indent like its very first line.
  20729. - In the code part of a source block, use language major mode
  20730. to indent current line if `org-src-tab-acts-natively' is
  20731. non-nil. If it is nil, do nothing.
  20732. - Otherwise, indent like the first non-blank line above.
  20733. The function doesn't indent an item as it could break the whole
  20734. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20735. `\\[org-shiftmetaright]'.
  20736. Also align node properties according to `org-property-format'."
  20737. (interactive)
  20738. (cond
  20739. (orgstruct-is-++
  20740. (let ((indent-line-function
  20741. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20742. (indent-according-to-mode)))
  20743. ((org-at-heading-p) 'noindent)
  20744. (t
  20745. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20746. (type (org-element-type element)))
  20747. (cond ((and (memq type '(plain-list item))
  20748. (= (line-beginning-position)
  20749. (org-element-property :post-affiliated element)))
  20750. 'noindent)
  20751. ((and (eq type 'latex-environment)
  20752. (>= (point) (org-element-property :post-affiliated element))
  20753. (< (point) (org-with-wide-buffer
  20754. (goto-char (org-element-property :end element))
  20755. (skip-chars-backward " \r\t\n")
  20756. (line-beginning-position 2))))
  20757. 'noindent)
  20758. ((and (eq type 'src-block)
  20759. org-src-tab-acts-natively
  20760. (> (line-beginning-position)
  20761. (org-element-property :post-affiliated element))
  20762. (< (line-beginning-position)
  20763. (org-with-wide-buffer
  20764. (goto-char (org-element-property :end element))
  20765. (skip-chars-backward " \r\t\n")
  20766. (line-beginning-position))))
  20767. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20768. (t
  20769. (let ((column (org--get-expected-indentation element nil)))
  20770. ;; Preserve current column.
  20771. (if (<= (current-column) (current-indentation))
  20772. (indent-line-to column)
  20773. (save-excursion (indent-line-to column))))
  20774. ;; Align node property. Also preserve current column.
  20775. (when (eq type 'node-property)
  20776. (let ((column (current-column)))
  20777. (org--align-node-property)
  20778. (org-move-to-column column)))))))))
  20779. (defun org-indent-region (start end)
  20780. "Indent each non-blank line in the region.
  20781. Called from a program, START and END specify the region to
  20782. indent. The function will not indent contents of example blocks,
  20783. verse blocks and export blocks as leading white spaces are
  20784. assumed to be significant there."
  20785. (interactive "r")
  20786. (save-excursion
  20787. (goto-char start)
  20788. (skip-chars-forward " \r\t\n")
  20789. (unless (eobp) (beginning-of-line))
  20790. (let ((indent-to
  20791. (lambda (ind pos)
  20792. ;; Set IND as indentation for all lines between point and
  20793. ;; POS. Blank lines are ignored. Leave point after POS
  20794. ;; once done.
  20795. (let ((limit (copy-marker pos)))
  20796. (while (< (point) limit)
  20797. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20798. (forward-line))
  20799. (set-marker limit nil))))
  20800. (end (copy-marker end)))
  20801. (while (< (point) end)
  20802. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20803. (let* ((element (org-element-at-point))
  20804. (type (org-element-type element))
  20805. (element-end (copy-marker (org-element-property :end element)))
  20806. (ind (org--get-expected-indentation element nil)))
  20807. (cond
  20808. ;; Element indented as a single block. Example blocks
  20809. ;; preserving indentation are a special case since the
  20810. ;; "contents" must not be indented whereas the block
  20811. ;; boundaries can.
  20812. ((or (memq type '(export-block latex-environment))
  20813. (and (eq type 'example-block)
  20814. (not
  20815. (or org-src-preserve-indentation
  20816. (org-element-property :preserve-indent element)))))
  20817. (let ((offset (- ind (org-get-indentation))))
  20818. (unless (zerop offset)
  20819. (indent-rigidly (org-element-property :begin element)
  20820. (org-element-property :end element)
  20821. offset)))
  20822. (goto-char element-end))
  20823. ;; Elements indented line wise. Be sure to exclude
  20824. ;; example blocks (preserving indentation) and source
  20825. ;; blocks from this category as they are treated
  20826. ;; specially later.
  20827. ((or (memq type '(paragraph table table-row))
  20828. (not (or (org-element-property :contents-begin element)
  20829. (memq type '(example-block src-block)))))
  20830. (when (eq type 'node-property)
  20831. (org--align-node-property)
  20832. (beginning-of-line))
  20833. (funcall indent-to ind (min element-end end)))
  20834. ;; Elements consisting of three parts: before the
  20835. ;; contents, the contents, and after the contents. The
  20836. ;; contents are treated specially, according to the
  20837. ;; element type, or not indented at all. Other parts are
  20838. ;; indented as a single block.
  20839. (t
  20840. (let* ((post (copy-marker
  20841. (org-element-property :post-affiliated element)))
  20842. (cbeg
  20843. (copy-marker
  20844. (cond
  20845. ((not (org-element-property :contents-begin element))
  20846. ;; Fake contents for source blocks.
  20847. (org-with-wide-buffer
  20848. (goto-char post)
  20849. (line-beginning-position 2)))
  20850. ((memq type '(footnote-definition item plain-list))
  20851. ;; Contents in these elements could start on
  20852. ;; the same line as the beginning of the
  20853. ;; element. Make sure we start indenting
  20854. ;; from the second line.
  20855. (org-with-wide-buffer
  20856. (goto-char post)
  20857. (end-of-line)
  20858. (skip-chars-forward " \r\t\n")
  20859. (if (eobp) (point) (line-beginning-position))))
  20860. (t (org-element-property :contents-begin element)))))
  20861. (cend (copy-marker
  20862. (or (org-element-property :contents-end element)
  20863. ;; Fake contents for source blocks.
  20864. (org-with-wide-buffer
  20865. (goto-char element-end)
  20866. (skip-chars-backward " \r\t\n")
  20867. (line-beginning-position)))
  20868. t)))
  20869. ;; Do not change items indentation individually as it
  20870. ;; might break the list as a whole. On the other
  20871. ;; hand, when at a plain list, indent it as a whole.
  20872. (cond ((eq type 'plain-list)
  20873. (let ((offset (- ind (org-get-indentation))))
  20874. (unless (zerop offset)
  20875. (indent-rigidly (org-element-property :begin element)
  20876. (org-element-property :end element)
  20877. offset))
  20878. (goto-char cbeg)))
  20879. ((eq type 'item) (goto-char cbeg))
  20880. (t (funcall indent-to ind (min cbeg end))))
  20881. (when (< (point) end)
  20882. (cl-case type
  20883. ((example-block verse-block))
  20884. (src-block
  20885. ;; In a source block, indent source code
  20886. ;; according to language major mode, but only if
  20887. ;; `org-src-tab-acts-natively' is non-nil.
  20888. (when (and (< (point) end) org-src-tab-acts-natively)
  20889. (ignore-errors
  20890. (org-babel-do-in-edit-buffer
  20891. (indent-region (point-min) (point-max))))))
  20892. (t (org-indent-region (point) (min cend end))))
  20893. (goto-char (min cend end))
  20894. (when (< (point) end)
  20895. (funcall indent-to ind (min element-end end))))
  20896. (set-marker post nil)
  20897. (set-marker cbeg nil)
  20898. (set-marker cend nil))))
  20899. (set-marker element-end nil))))
  20900. (set-marker end nil))))
  20901. (defun org-indent-drawer ()
  20902. "Indent the drawer at point."
  20903. (interactive)
  20904. (unless (save-excursion
  20905. (beginning-of-line)
  20906. (looking-at-p org-drawer-regexp))
  20907. (user-error "Not at a drawer"))
  20908. (let ((element (org-element-at-point)))
  20909. (unless (memq (org-element-type element) '(drawer property-drawer))
  20910. (user-error "Not at a drawer"))
  20911. (org-with-wide-buffer
  20912. (org-indent-region (org-element-property :begin element)
  20913. (org-element-property :end element))))
  20914. (message "Drawer at point indented"))
  20915. (defun org-indent-block ()
  20916. "Indent the block at point."
  20917. (interactive)
  20918. (unless (save-excursion
  20919. (beginning-of-line)
  20920. (let ((case-fold-search t))
  20921. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20922. (user-error "Not at a block"))
  20923. (let ((element (org-element-at-point)))
  20924. (unless (memq (org-element-type element)
  20925. '(comment-block center-block dynamic-block example-block
  20926. export-block quote-block special-block
  20927. src-block verse-block))
  20928. (user-error "Not at a block"))
  20929. (org-with-wide-buffer
  20930. (org-indent-region (org-element-property :begin element)
  20931. (org-element-property :end element))))
  20932. (message "Block at point indented"))
  20933. ;;; Filling
  20934. ;; We use our own fill-paragraph and auto-fill functions.
  20935. ;; `org-fill-paragraph' relies on adaptive filling and context
  20936. ;; checking. Appropriate `fill-prefix' is computed with
  20937. ;; `org-adaptive-fill-function'.
  20938. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20939. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20940. ;; `org-adaptive-fill-function' value. Internally,
  20941. ;; `org-comment-line-break-function' breaks the line.
  20942. ;; `org-setup-filling' installs filling and auto-filling related
  20943. ;; variables during `org-mode' initialization.
  20944. (defvar org-element-paragraph-separate) ; org-element.el
  20945. (defun org-setup-filling ()
  20946. (require 'org-element)
  20947. ;; Prevent auto-fill from inserting unwanted new items.
  20948. (when (boundp 'fill-nobreak-predicate)
  20949. (setq-local
  20950. fill-nobreak-predicate
  20951. (org-uniquify
  20952. (append fill-nobreak-predicate
  20953. '(org-fill-line-break-nobreak-p
  20954. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20955. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20956. (setq-local paragraph-start paragraph-ending)
  20957. (setq-local paragraph-separate paragraph-ending))
  20958. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20959. (setq-local auto-fill-inhibit-regexp nil)
  20960. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20961. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20962. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20963. (defun org-fill-line-break-nobreak-p ()
  20964. "Non-nil when a new line at point would create an Org line break."
  20965. (save-excursion
  20966. (skip-chars-backward "[ \t]")
  20967. (skip-chars-backward "\\\\")
  20968. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20969. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20970. "Non-nil when a new line at point would split a timestamp."
  20971. (and (org-at-timestamp-p 'lax)
  20972. (not (looking-at org-ts-regexp-both))))
  20973. (declare-function message-in-body-p "message" ())
  20974. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20975. (defun org-adaptive-fill-function ()
  20976. "Compute a fill prefix for the current line.
  20977. Return fill prefix, as a string, or nil if current line isn't
  20978. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20979. matches in paragraphs or comments, use it."
  20980. (catch 'exit
  20981. (when (derived-mode-p 'message-mode)
  20982. (save-excursion
  20983. (beginning-of-line)
  20984. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20985. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20986. ((looking-at message-cite-prefix-regexp)
  20987. (throw 'exit (match-string-no-properties 0)))
  20988. ((looking-at org-outline-regexp)
  20989. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20990. (org-with-wide-buffer
  20991. (unless (org-at-heading-p)
  20992. (let* ((p (line-beginning-position))
  20993. (element (save-excursion
  20994. (beginning-of-line)
  20995. (org-element-at-point)))
  20996. (type (org-element-type element))
  20997. (post-affiliated (org-element-property :post-affiliated element)))
  20998. (unless (< p post-affiliated)
  20999. (cl-case type
  21000. (comment
  21001. (save-excursion
  21002. (beginning-of-line)
  21003. (looking-at "[ \t]*")
  21004. (concat (match-string 0) "# ")))
  21005. (footnote-definition "")
  21006. ((item plain-list)
  21007. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21008. (paragraph
  21009. ;; Fill prefix is usually the same as the current line,
  21010. ;; unless the paragraph is at the beginning of an item.
  21011. (let ((parent (org-element-property :parent element)))
  21012. (save-excursion
  21013. (beginning-of-line)
  21014. (cond ((eq (org-element-type parent) 'item)
  21015. (make-string (org-list-item-body-column
  21016. (org-element-property :begin parent))
  21017. ?\s))
  21018. ((and adaptive-fill-regexp
  21019. ;; Locally disable
  21020. ;; `adaptive-fill-function' to let
  21021. ;; `fill-context-prefix' handle
  21022. ;; `adaptive-fill-regexp' variable.
  21023. (let (adaptive-fill-function)
  21024. (fill-context-prefix
  21025. post-affiliated
  21026. (org-element-property :end element)))))
  21027. ((looking-at "[ \t]+") (match-string 0))
  21028. (t "")))))
  21029. (comment-block
  21030. ;; Only fill contents if P is within block boundaries.
  21031. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21032. (forward-line)
  21033. (point)))
  21034. (cend (save-excursion
  21035. (goto-char (org-element-property :end element))
  21036. (skip-chars-backward " \r\t\n")
  21037. (line-beginning-position))))
  21038. (when (and (>= p cbeg) (< p cend))
  21039. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21040. (match-string 0)
  21041. "")))))))))))
  21042. (declare-function message-goto-body "message" ())
  21043. (defvar message-cite-prefix-regexp) ; From message.el
  21044. (defun org-fill-paragraph (&optional justify)
  21045. "Fill element at point, when applicable.
  21046. This function only applies to comment blocks, comments, example
  21047. blocks and paragraphs. Also, as a special case, re-align table
  21048. when point is at one.
  21049. If JUSTIFY is non-nil (interactively, with prefix argument),
  21050. justify as well. If `sentence-end-double-space' is non-nil, then
  21051. period followed by one space does not end a sentence, so don't
  21052. break a line there. The variable `fill-column' controls the
  21053. width for filling.
  21054. For convenience, when point is at a plain list, an item or
  21055. a footnote definition, try to fill the first paragraph within."
  21056. (interactive)
  21057. (if (and (derived-mode-p 'message-mode)
  21058. (or (not (message-in-body-p))
  21059. (save-excursion (move-beginning-of-line 1)
  21060. (looking-at message-cite-prefix-regexp))))
  21061. ;; First ensure filling is correct in message-mode.
  21062. (let ((fill-paragraph-function
  21063. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21064. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21065. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21066. (paragraph-separate
  21067. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21068. (fill-paragraph nil))
  21069. (with-syntax-table org-mode-transpose-word-syntax-table
  21070. ;; Move to end of line in order to get the first paragraph
  21071. ;; within a plain list or a footnote definition.
  21072. (let ((element (save-excursion
  21073. (end-of-line)
  21074. (or (ignore-errors (org-element-at-point))
  21075. (user-error "An element cannot be parsed line %d"
  21076. (line-number-at-pos (point)))))))
  21077. ;; First check if point is in a blank line at the beginning of
  21078. ;; the buffer. In that case, ignore filling.
  21079. (cl-case (org-element-type element)
  21080. ;; Use major mode filling function is src blocks.
  21081. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21082. ;; Align Org tables, leave table.el tables as-is.
  21083. (table-row (org-table-align) t)
  21084. (table
  21085. (when (eq (org-element-property :type element) 'org)
  21086. (save-excursion
  21087. (goto-char (org-element-property :post-affiliated element))
  21088. (org-table-align)))
  21089. t)
  21090. (paragraph
  21091. ;; Paragraphs may contain `line-break' type objects.
  21092. (let ((beg (max (point-min)
  21093. (org-element-property :contents-begin element)))
  21094. (end (min (point-max)
  21095. (org-element-property :contents-end element))))
  21096. ;; Do nothing if point is at an affiliated keyword.
  21097. (if (< (line-end-position) beg) t
  21098. (when (derived-mode-p 'message-mode)
  21099. ;; In `message-mode', do not fill following citation
  21100. ;; in current paragraph nor text before message body.
  21101. (let ((body-start (save-excursion (message-goto-body))))
  21102. (when body-start (setq beg (max body-start beg))))
  21103. (when (save-excursion
  21104. (re-search-forward
  21105. (concat "^" message-cite-prefix-regexp) end t))
  21106. (setq end (match-beginning 0))))
  21107. ;; Fill paragraph, taking line breaks into account.
  21108. (save-excursion
  21109. (goto-char beg)
  21110. (let ((cuts (list beg)))
  21111. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21112. (when (eq 'line-break
  21113. (org-element-type
  21114. (save-excursion (backward-char)
  21115. (org-element-context))))
  21116. (push (point) cuts)))
  21117. (dolist (c (delq end cuts))
  21118. (fill-region-as-paragraph c end justify)
  21119. (setq end c))))
  21120. t)))
  21121. ;; Contents of `comment-block' type elements should be
  21122. ;; filled as plain text, but only if point is within block
  21123. ;; markers.
  21124. (comment-block
  21125. (let* ((case-fold-search t)
  21126. (beg (save-excursion
  21127. (goto-char (org-element-property :begin element))
  21128. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21129. (forward-line)
  21130. (point)))
  21131. (end (save-excursion
  21132. (goto-char (org-element-property :end element))
  21133. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21134. (line-beginning-position))))
  21135. (if (or (< (point) beg) (> (point) end)) t
  21136. (fill-region-as-paragraph
  21137. (save-excursion (end-of-line)
  21138. (re-search-backward "^[ \t]*$" beg 'move)
  21139. (line-beginning-position))
  21140. (save-excursion (beginning-of-line)
  21141. (re-search-forward "^[ \t]*$" end 'move)
  21142. (line-beginning-position))
  21143. justify))))
  21144. ;; Fill comments.
  21145. (comment
  21146. (let ((begin (org-element-property :post-affiliated element))
  21147. (end (org-element-property :end element)))
  21148. (when (and (>= (point) begin) (<= (point) end))
  21149. (let ((begin (save-excursion
  21150. (end-of-line)
  21151. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21152. (progn (forward-line) (point))
  21153. begin)))
  21154. (end (save-excursion
  21155. (end-of-line)
  21156. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21157. (1- (line-beginning-position))
  21158. (skip-chars-backward " \r\t\n")
  21159. (line-end-position)))))
  21160. ;; Do not fill comments when at a blank line.
  21161. (when (> end begin)
  21162. (let ((fill-prefix
  21163. (save-excursion
  21164. (beginning-of-line)
  21165. (looking-at "[ \t]*#")
  21166. (let ((comment-prefix (match-string 0)))
  21167. (goto-char (match-end 0))
  21168. (if (looking-at adaptive-fill-regexp)
  21169. (concat comment-prefix (match-string 0))
  21170. (concat comment-prefix " "))))))
  21171. (save-excursion
  21172. (fill-region-as-paragraph begin end justify))))))
  21173. t))
  21174. ;; Ignore every other element.
  21175. (otherwise t))))))
  21176. (defun org-auto-fill-function ()
  21177. "Auto-fill function."
  21178. ;; Check if auto-filling is meaningful.
  21179. (let ((fc (current-fill-column)))
  21180. (when (and fc (> (current-column) fc))
  21181. (let* ((fill-prefix (org-adaptive-fill-function))
  21182. ;; Enforce empty fill prefix, if required. Otherwise, it
  21183. ;; will be computed again.
  21184. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21185. (when fill-prefix (do-auto-fill))))))
  21186. (defun org-comment-line-break-function (&optional soft)
  21187. "Break line at point and indent, continuing comment if within one.
  21188. The inserted newline is marked hard if variable
  21189. `use-hard-newlines' is true, unless optional argument SOFT is
  21190. non-nil."
  21191. (if soft (insert-and-inherit ?\n) (newline 1))
  21192. (save-excursion (forward-char -1) (delete-horizontal-space))
  21193. (delete-horizontal-space)
  21194. (indent-to-left-margin)
  21195. (insert-before-markers-and-inherit fill-prefix))
  21196. ;;; Fixed Width Areas
  21197. (defun org-toggle-fixed-width ()
  21198. "Toggle fixed-width markup.
  21199. Add or remove fixed-width markup on current line, whenever it
  21200. makes sense. Return an error otherwise.
  21201. If a region is active and if it contains only fixed-width areas
  21202. or blank lines, remove all fixed-width markup in it. If the
  21203. region contains anything else, convert all non-fixed-width lines
  21204. to fixed-width ones.
  21205. Blank lines at the end of the region are ignored unless the
  21206. region only contains such lines."
  21207. (interactive)
  21208. (if (not (org-region-active-p))
  21209. ;; No region:
  21210. ;;
  21211. ;; Remove fixed width marker only in a fixed-with element.
  21212. ;;
  21213. ;; Add fixed width maker in paragraphs, in blank lines after
  21214. ;; elements or at the beginning of a headline or an inlinetask,
  21215. ;; and before any one-line elements (e.g., a clock).
  21216. (progn
  21217. (beginning-of-line)
  21218. (let* ((element (org-element-at-point))
  21219. (type (org-element-type element)))
  21220. (cond
  21221. ((and (eq type 'fixed-width)
  21222. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21223. (replace-match
  21224. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21225. ((and (memq type '(babel-call clock comment diary-sexp headline
  21226. horizontal-rule keyword paragraph
  21227. planning))
  21228. (<= (org-element-property :post-affiliated element) (point)))
  21229. (skip-chars-forward " \t")
  21230. (insert ": "))
  21231. ((and (looking-at-p "[ \t]*$")
  21232. (or (eq type 'inlinetask)
  21233. (save-excursion
  21234. (skip-chars-forward " \r\t\n")
  21235. (<= (org-element-property :end element) (point)))))
  21236. (delete-region (point) (line-end-position))
  21237. (org-indent-line)
  21238. (insert ": "))
  21239. (t (user-error "Cannot insert a fixed-width line here")))))
  21240. ;; Region active.
  21241. (let* ((begin (save-excursion
  21242. (goto-char (region-beginning))
  21243. (line-beginning-position)))
  21244. (end (copy-marker
  21245. (save-excursion
  21246. (goto-char (region-end))
  21247. (unless (eolp) (beginning-of-line))
  21248. (if (save-excursion (re-search-backward "\\S-" begin t))
  21249. (progn (skip-chars-backward " \r\t\n") (point))
  21250. (point)))))
  21251. (all-fixed-width-p
  21252. (catch 'not-all-p
  21253. (save-excursion
  21254. (goto-char begin)
  21255. (skip-chars-forward " \r\t\n")
  21256. (when (eobp) (throw 'not-all-p nil))
  21257. (while (< (point) end)
  21258. (let ((element (org-element-at-point)))
  21259. (if (eq (org-element-type element) 'fixed-width)
  21260. (goto-char (org-element-property :end element))
  21261. (throw 'not-all-p nil))))
  21262. t))))
  21263. (if all-fixed-width-p
  21264. (save-excursion
  21265. (goto-char begin)
  21266. (while (< (point) end)
  21267. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21268. (replace-match
  21269. "" nil nil nil
  21270. (if (= (line-end-position) (match-end 0)) 0 1)))
  21271. (forward-line)))
  21272. (let ((min-ind (point-max)))
  21273. ;; Find minimum indentation across all lines.
  21274. (save-excursion
  21275. (goto-char begin)
  21276. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21277. (setq min-ind 0)
  21278. (catch 'zerop
  21279. (while (< (point) end)
  21280. (unless (looking-at-p "[ \t]*$")
  21281. (let ((ind (org-get-indentation)))
  21282. (setq min-ind (min min-ind ind))
  21283. (when (zerop ind) (throw 'zerop t))))
  21284. (forward-line)))))
  21285. ;; Loop over all lines and add fixed-width markup everywhere
  21286. ;; but in fixed-width lines.
  21287. (save-excursion
  21288. (goto-char begin)
  21289. (while (< (point) end)
  21290. (cond
  21291. ((org-at-heading-p)
  21292. (insert ": ")
  21293. (forward-line)
  21294. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21295. (insert ":")
  21296. (forward-line)))
  21297. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21298. (let* ((element (org-element-at-point))
  21299. (element-end (org-element-property :end element)))
  21300. (if (eq (org-element-type element) 'fixed-width)
  21301. (progn (goto-char element-end)
  21302. (skip-chars-backward " \r\t\n")
  21303. (forward-line))
  21304. (let ((limit (min end element-end)))
  21305. (while (< (point) limit)
  21306. (org-move-to-column min-ind t)
  21307. (insert ": ")
  21308. (forward-line))))))
  21309. (t
  21310. (org-move-to-column min-ind t)
  21311. (insert ": ")
  21312. (forward-line)))))))
  21313. (set-marker end nil))))
  21314. ;;; Comments
  21315. ;; Org comments syntax is quite complex. It requires the entire line
  21316. ;; to be just a comment. Also, even with the right syntax at the
  21317. ;; beginning of line, some elements (e.g., verse-block or
  21318. ;; example-block) don't accept comments. Usual Emacs comment commands
  21319. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21320. ;; Org still relies on `comment-dwim', but cannot trust
  21321. ;; `comment-only-p'. So, `comment-region-function' and
  21322. ;; `uncomment-region-function' both point
  21323. ;; to`org-comment-or-uncomment-region'. Eventually,
  21324. ;; `org-insert-comment' takes care of insertion of comments at the
  21325. ;; beginning of line.
  21326. ;; `org-setup-comments-handling' install comments related variables
  21327. ;; during `org-mode' initialization.
  21328. (defun org-setup-comments-handling ()
  21329. (interactive)
  21330. (setq-local comment-use-syntax nil)
  21331. (setq-local comment-start "# ")
  21332. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21333. (setq-local comment-insert-comment-function 'org-insert-comment)
  21334. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21335. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21336. (defun org-insert-comment ()
  21337. "Insert an empty comment above current line.
  21338. If the line is empty, insert comment at its beginning. When
  21339. point is within a source block, comment according to the related
  21340. major mode."
  21341. (if (let ((element (org-element-at-point)))
  21342. (and (eq (org-element-type element) 'src-block)
  21343. (< (save-excursion
  21344. (goto-char (org-element-property :post-affiliated element))
  21345. (line-end-position))
  21346. (point))
  21347. (> (save-excursion
  21348. (goto-char (org-element-property :end element))
  21349. (skip-chars-backward " \r\t\n")
  21350. (line-beginning-position))
  21351. (point))))
  21352. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21353. (beginning-of-line)
  21354. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21355. (open-line 1))
  21356. (org-indent-line)
  21357. (insert "# ")))
  21358. (defvar comment-empty-lines) ; From newcomment.el.
  21359. (defun org-comment-or-uncomment-region (beg end &rest _)
  21360. "Comment or uncomment each non-blank line in the region.
  21361. Uncomment each non-blank line between BEG and END if it only
  21362. contains commented lines. Otherwise, comment them. If region is
  21363. strictly within a source block, use appropriate comment syntax."
  21364. (if (let ((element (org-element-at-point)))
  21365. (and (eq (org-element-type element) 'src-block)
  21366. (< (save-excursion
  21367. (goto-char (org-element-property :post-affiliated element))
  21368. (line-end-position))
  21369. beg)
  21370. (>= (save-excursion
  21371. (goto-char (org-element-property :end element))
  21372. (skip-chars-backward " \r\t\n")
  21373. (line-beginning-position))
  21374. end)))
  21375. ;; Translate region boundaries for the Org buffer to the source
  21376. ;; buffer.
  21377. (let ((offset (- end beg)))
  21378. (save-excursion
  21379. (goto-char beg)
  21380. (org-babel-do-in-edit-buffer
  21381. (comment-or-uncomment-region (point) (+ offset (point))))))
  21382. (save-restriction
  21383. ;; Restrict region
  21384. (narrow-to-region (save-excursion (goto-char beg)
  21385. (skip-chars-forward " \r\t\n" end)
  21386. (line-beginning-position))
  21387. (save-excursion (goto-char end)
  21388. (skip-chars-backward " \r\t\n" beg)
  21389. (line-end-position)))
  21390. (let ((uncommentp
  21391. ;; UNCOMMENTP is non-nil when every non blank line between
  21392. ;; BEG and END is a comment.
  21393. (save-excursion
  21394. (goto-char (point-min))
  21395. (while (and (not (eobp))
  21396. (let ((element (org-element-at-point)))
  21397. (and (eq (org-element-type element) 'comment)
  21398. (goto-char (min (point-max)
  21399. (org-element-property
  21400. :end element)))))))
  21401. (eobp))))
  21402. (if uncommentp
  21403. ;; Only blank lines and comments in region: uncomment it.
  21404. (save-excursion
  21405. (goto-char (point-min))
  21406. (while (not (eobp))
  21407. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21408. (replace-match "" nil nil nil 1))
  21409. (forward-line)))
  21410. ;; Comment each line in region.
  21411. (let ((min-indent (point-max)))
  21412. ;; First find the minimum indentation across all lines.
  21413. (save-excursion
  21414. (goto-char (point-min))
  21415. (while (and (not (eobp)) (not (zerop min-indent)))
  21416. (unless (looking-at "[ \t]*$")
  21417. (setq min-indent (min min-indent (current-indentation))))
  21418. (forward-line)))
  21419. ;; Then loop over all lines.
  21420. (save-excursion
  21421. (goto-char (point-min))
  21422. (while (not (eobp))
  21423. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21424. ;; Don't get fooled by invisible text (e.g. link path)
  21425. ;; when moving to column MIN-INDENT.
  21426. (let ((buffer-invisibility-spec nil))
  21427. (org-move-to-column min-indent t))
  21428. (insert comment-start))
  21429. (forward-line)))))))))
  21430. (defun org-comment-dwim (_arg)
  21431. "Call `comment-dwim' within a source edit buffer if needed."
  21432. (interactive "*P")
  21433. (if (org-in-src-block-p)
  21434. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21435. (call-interactively 'comment-dwim)))
  21436. ;;; Timestamps API
  21437. ;; This section contains tools to operate on timestamp objects, as
  21438. ;; returned by, e.g. `org-element-context'.
  21439. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21440. "Encode TIMESTAMP object into Emacs internal time.
  21441. Use end of date range or time range when END is non-nil."
  21442. (apply #'encode-time
  21443. (cons 0
  21444. (mapcar
  21445. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21446. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21447. '(:minute-start :hour-start :day-start :month-start
  21448. :year-start))))))
  21449. (defun org-timestamp-has-time-p (timestamp)
  21450. "Non-nil when TIMESTAMP has a time specified."
  21451. (org-element-property :hour-start timestamp))
  21452. (defun org-timestamp-format (timestamp format &optional end utc)
  21453. "Format a TIMESTAMP object into a string.
  21454. FORMAT is a format specifier to be passed to
  21455. `format-time-string'.
  21456. When optional argument END is non-nil, use end of date-range or
  21457. time-range, if possible.
  21458. When optional argument UTC is non-nil, time will be expressed as
  21459. Universal Time."
  21460. (format-time-string
  21461. format (org-timestamp--to-internal-time timestamp end)
  21462. (and utc t)))
  21463. (defun org-timestamp-split-range (timestamp &optional end)
  21464. "Extract a TIMESTAMP object from a date or time range.
  21465. END, when non-nil, means extract the end of the range.
  21466. Otherwise, extract its start.
  21467. Return a new timestamp object."
  21468. (let ((type (org-element-property :type timestamp)))
  21469. (if (memq type '(active inactive diary)) timestamp
  21470. (let ((split-ts (org-element-copy timestamp)))
  21471. ;; Set new type.
  21472. (org-element-put-property
  21473. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21474. ;; Copy start properties over end properties if END is
  21475. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21476. (let ((p-alist '((:minute-start . :minute-end)
  21477. (:hour-start . :hour-end)
  21478. (:day-start . :day-end)
  21479. (:month-start . :month-end)
  21480. (:year-start . :year-end))))
  21481. (dolist (p-cell p-alist)
  21482. (org-element-put-property
  21483. split-ts
  21484. (funcall (if end #'car #'cdr) p-cell)
  21485. (org-element-property
  21486. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21487. ;; Eventually refresh `:raw-value'.
  21488. (org-element-put-property split-ts :raw-value nil)
  21489. (org-element-put-property
  21490. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21491. (defun org-timestamp-translate (timestamp &optional boundary)
  21492. "Translate TIMESTAMP object to custom format.
  21493. Format string is defined in `org-time-stamp-custom-formats',
  21494. which see.
  21495. When optional argument BOUNDARY is non-nil, it is either the
  21496. symbol `start' or `end'. In this case, only translate the
  21497. starting or ending part of TIMESTAMP if it is a date or time
  21498. range. Otherwise, translate both parts.
  21499. Return timestamp as-is if `org-display-custom-times' is nil or if
  21500. it has a `diary' type."
  21501. (let ((type (org-element-property :type timestamp)))
  21502. (if (or (not org-display-custom-times) (eq type 'diary))
  21503. (org-element-interpret-data timestamp)
  21504. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21505. org-time-stamp-custom-formats)))
  21506. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21507. (concat (org-timestamp-format timestamp fmt)
  21508. "--"
  21509. (org-timestamp-format timestamp fmt t))
  21510. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21511. ;;; Other stuff.
  21512. (defvar reftex-docstruct-symbol)
  21513. (defvar org--rds)
  21514. (defun org-reftex-citation ()
  21515. "Use reftex-citation to insert a citation into the buffer.
  21516. This looks for a line like
  21517. #+BIBLIOGRAPHY: foo plain option:-d
  21518. and derives from it that foo.bib is the bibliography file relevant
  21519. for this document. It then installs the necessary environment for RefTeX
  21520. to work in this buffer and calls `reftex-citation' to insert a citation
  21521. into the buffer.
  21522. Export of such citations to both LaTeX and HTML is handled by the contributed
  21523. package ox-bibtex by Taru Karttunen."
  21524. (interactive)
  21525. (let ((reftex-docstruct-symbol 'org--rds)
  21526. org--rds bib)
  21527. (org-with-wide-buffer
  21528. (let ((case-fold-search t)
  21529. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21530. (if (not (save-excursion
  21531. (or (re-search-forward re nil t)
  21532. (re-search-backward re nil t))))
  21533. (user-error "No bibliography defined in file")
  21534. (setq bib (concat (match-string 1) ".bib")
  21535. org--rds (list (list 'bib bib))))))
  21536. (call-interactively 'reftex-citation)))
  21537. ;;;; Functions extending outline functionality
  21538. (defun org-beginning-of-line (&optional n)
  21539. "Go to the beginning of the current visible line.
  21540. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21541. tags on the first attempt, and only move to after the tags when
  21542. the cursor is already beyond the end of the headline.
  21543. With argument N not nil or 1, move forward N - 1 lines first."
  21544. (interactive "^p")
  21545. (let ((origin (point))
  21546. (special (pcase org-special-ctrl-a/e
  21547. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21548. deactivate-mark)
  21549. ;; First move to a visible line.
  21550. (if (bound-and-true-p visual-line-mode)
  21551. (beginning-of-visual-line n)
  21552. (move-beginning-of-line n)
  21553. ;; `move-beginning-of-line' may leave point after invisible
  21554. ;; characters if line starts with such of these (e.g., with
  21555. ;; a link at column 0). Really move to the beginning of the
  21556. ;; current visible line.
  21557. (beginning-of-line))
  21558. (cond
  21559. ;; No special behavior. Point is already at the beginning of
  21560. ;; a line, logical or visual.
  21561. ((not special))
  21562. ;; `beginning-of-visual-line' left point before logical beginning
  21563. ;; of line: point is at the beginning of a visual line. Bail
  21564. ;; out.
  21565. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21566. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21567. ;; At a headline, special position is before the title, but
  21568. ;; after any TODO keyword or priority cookie.
  21569. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21570. (line-end-position)))
  21571. (bol (point)))
  21572. (if (eq special 'reversed)
  21573. (when (and (= origin bol) (eq last-command this-command))
  21574. (goto-char refpos))
  21575. (when (or (> origin refpos) (= origin bol))
  21576. (goto-char refpos)))))
  21577. ((and (looking-at org-list-full-item-re)
  21578. (memq (org-element-type (save-match-data (org-element-at-point)))
  21579. '(item plain-list)))
  21580. ;; Set special position at first white space character after
  21581. ;; bullet, and check-box, if any.
  21582. (let ((after-bullet
  21583. (let ((box (match-end 3)))
  21584. (cond ((not box) (match-end 1))
  21585. ((eq (char-after box) ?\s) (1+ box))
  21586. (t box)))))
  21587. (if (eq special 'reversed)
  21588. (when (and (= (point) origin) (eq last-command this-command))
  21589. (goto-char after-bullet))
  21590. (when (or (> origin after-bullet) (= (point) origin))
  21591. (goto-char after-bullet)))))
  21592. ;; No special context. Point is already at beginning of line.
  21593. (t nil))))
  21594. (defun org-end-of-line (&optional n)
  21595. "Go to the end of the line, but before ellipsis, if any.
  21596. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21597. tags on the first attempt, and only move to after the tags when
  21598. the cursor is already beyond the end of the headline.
  21599. With argument N not nil or 1, move forward N - 1 lines first."
  21600. (interactive "^p")
  21601. (let ((origin (point))
  21602. (special (pcase org-special-ctrl-a/e
  21603. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21604. deactivate-mark)
  21605. ;; First move to a visible line.
  21606. (if (bound-and-true-p visual-line-mode)
  21607. (beginning-of-visual-line n)
  21608. (move-beginning-of-line n))
  21609. (cond
  21610. ;; At a headline, with tags.
  21611. ((and special
  21612. (save-excursion
  21613. (beginning-of-line)
  21614. (let ((case-fold-search nil))
  21615. (looking-at org-complex-heading-regexp)))
  21616. (match-end 5))
  21617. (let ((tags (save-excursion
  21618. (goto-char (match-beginning 5))
  21619. (skip-chars-backward " \t")
  21620. (point)))
  21621. (visual-end (and (bound-and-true-p visual-line-mode)
  21622. (save-excursion
  21623. (end-of-visual-line)
  21624. (point)))))
  21625. ;; If `end-of-visual-line' brings us before end of line or
  21626. ;; even tags, i.e., the headline spans over multiple visual
  21627. ;; lines, move there.
  21628. (cond ((and visual-end
  21629. (< visual-end tags)
  21630. (<= origin visual-end))
  21631. (goto-char visual-end))
  21632. ((eq special 'reversed)
  21633. (if (and (= origin (line-end-position))
  21634. (eq this-command last-command))
  21635. (goto-char tags)
  21636. (end-of-line)))
  21637. (t
  21638. (if (or (< origin tags) (= origin (line-end-position)))
  21639. (goto-char tags)
  21640. (end-of-line))))))
  21641. ((bound-and-true-p visual-line-mode)
  21642. (let ((bol (line-beginning-position)))
  21643. (end-of-visual-line)
  21644. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21645. ;; end of a line, backtrack and use `end-of-line' instead.
  21646. (when (/= bol (line-beginning-position))
  21647. (goto-char bol)
  21648. (end-of-line))))
  21649. (t (end-of-line)))))
  21650. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21651. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21652. (defun org-backward-sentence (&optional _arg)
  21653. "Go to beginning of sentence, or beginning of table field.
  21654. This will call `backward-sentence' or `org-table-beginning-of-field',
  21655. depending on context."
  21656. (interactive)
  21657. (let* ((element (org-element-at-point))
  21658. (contents-begin (org-element-property :contents-begin element))
  21659. (table (org-element-lineage element '(table) t)))
  21660. (if (and table
  21661. (> (point) contents-begin)
  21662. (<= (point) (org-element-property :contents-end table)))
  21663. (call-interactively #'org-table-beginning-of-field)
  21664. (save-restriction
  21665. (when (and contents-begin
  21666. (< (point-min) contents-begin)
  21667. (> (point) contents-begin))
  21668. (narrow-to-region contents-begin
  21669. (org-element-property :contents-end element)))
  21670. (call-interactively #'backward-sentence)))))
  21671. (defun org-forward-sentence (&optional _arg)
  21672. "Go to end of sentence, or end of table field.
  21673. This will call `forward-sentence' or `org-table-end-of-field',
  21674. depending on context."
  21675. (interactive)
  21676. (let* ((element (org-element-at-point))
  21677. (contents-end (org-element-property :contents-end element))
  21678. (table (org-element-lineage element '(table) t)))
  21679. (if (and table
  21680. (>= (point) (org-element-property :contents-begin table))
  21681. (< (point) contents-end))
  21682. (call-interactively #'org-table-end-of-field)
  21683. (save-restriction
  21684. (when (and contents-end
  21685. (> (point-max) contents-end)
  21686. ;; Skip blank lines between elements.
  21687. (< (org-element-property :end element)
  21688. (save-excursion (goto-char contents-end)
  21689. (skip-chars-forward " \r\t\n"))))
  21690. (narrow-to-region (org-element-property :contents-begin element)
  21691. contents-end))
  21692. (call-interactively #'forward-sentence)))))
  21693. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21694. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21695. (defun org-kill-line (&optional _arg)
  21696. "Kill line, to tags or end of line."
  21697. (interactive)
  21698. (cond
  21699. ((or (not org-special-ctrl-k)
  21700. (bolp)
  21701. (not (org-at-heading-p)))
  21702. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21703. org-ctrl-k-protect-subtree
  21704. (or (eq org-ctrl-k-protect-subtree 'error)
  21705. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21706. (user-error "C-k aborted as it would kill a hidden subtree"))
  21707. (call-interactively
  21708. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21709. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21710. (kill-region (point) (match-beginning 1))
  21711. (org-set-tags nil t))
  21712. (t (kill-region (point) (point-at-eol)))))
  21713. (define-key org-mode-map "\C-k" 'org-kill-line)
  21714. (defun org-yank (&optional arg)
  21715. "Yank. If the kill is a subtree, treat it specially.
  21716. This command will look at the current kill and check if is a single
  21717. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21718. cursor is at the beginning of a line or after the stars of a currently
  21719. empty headline, then the yank is handled specially. How exactly depends
  21720. on the value of the following variables.
  21721. `org-yank-folded-subtrees'
  21722. By default, this variable is non-nil, which results in
  21723. subtree(s) being folded after insertion, except if doing so
  21724. would swallow text after the yanked text.
  21725. `org-yank-adjusted-subtrees'
  21726. When non-nil (the default value is nil), the subtree will be
  21727. promoted or demoted in order to fit into the local outline tree
  21728. structure, which means that the level will be adjusted so that it
  21729. becomes the smaller one of the two *visible* surrounding headings.
  21730. Any prefix to this command will cause `yank' to be called directly with
  21731. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21732. will just
  21733. plainly yank the text as it is.
  21734. \[1] The test checks if the first non-white line is a heading
  21735. and if there are no other headings with fewer stars."
  21736. (interactive "P")
  21737. (org-yank-generic 'yank arg))
  21738. (defun org-yank-generic (command arg)
  21739. "Perform some yank-like command.
  21740. This function implements the behavior described in the `org-yank'
  21741. documentation. However, it has been generalized to work for any
  21742. interactive command with similar behavior."
  21743. ;; pretend to be command COMMAND
  21744. (setq this-command command)
  21745. (if arg
  21746. (call-interactively command)
  21747. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21748. (and (org-kill-is-subtree-p)
  21749. (or (bolp)
  21750. (and (looking-at "[ \t]*$")
  21751. (string-match
  21752. "\\`\\*+\\'"
  21753. (buffer-substring (point-at-bol) (point)))))))
  21754. swallowp)
  21755. (cond
  21756. ((and subtreep org-yank-folded-subtrees)
  21757. (let ((beg (point))
  21758. end)
  21759. (if (and subtreep org-yank-adjusted-subtrees)
  21760. (org-paste-subtree nil nil 'for-yank)
  21761. (call-interactively command))
  21762. (setq end (point))
  21763. (goto-char beg)
  21764. (when (and (bolp) subtreep
  21765. (not (setq swallowp
  21766. (org-yank-folding-would-swallow-text beg end))))
  21767. (org-with-limited-levels
  21768. (or (looking-at org-outline-regexp)
  21769. (re-search-forward org-outline-regexp-bol end t))
  21770. (while (and (< (point) end) (looking-at org-outline-regexp))
  21771. (outline-hide-subtree)
  21772. (org-cycle-show-empty-lines 'folded)
  21773. (condition-case nil
  21774. (outline-forward-same-level 1)
  21775. (error (goto-char end))))))
  21776. (when swallowp
  21777. (message
  21778. "Inserted text not folded because that would swallow text"))
  21779. (goto-char end)
  21780. (skip-chars-forward " \t\n\r")
  21781. (beginning-of-line 1)
  21782. (push-mark beg 'nomsg)))
  21783. ((and subtreep org-yank-adjusted-subtrees)
  21784. (let ((beg (point-at-bol)))
  21785. (org-paste-subtree nil nil 'for-yank)
  21786. (push-mark beg 'nomsg)))
  21787. (t
  21788. (call-interactively command))))))
  21789. (defun org-yank-folding-would-swallow-text (beg end)
  21790. "Would hide-subtree at BEG swallow any text after END?"
  21791. (let (level)
  21792. (org-with-limited-levels
  21793. (save-excursion
  21794. (goto-char beg)
  21795. (when (or (looking-at org-outline-regexp)
  21796. (re-search-forward org-outline-regexp-bol end t))
  21797. (setq level (org-outline-level)))
  21798. (goto-char end)
  21799. (skip-chars-forward " \t\r\n\v\f")
  21800. (not (or (eobp)
  21801. (and (bolp) (looking-at-p org-outline-regexp)
  21802. (<= (org-outline-level) level))))))))
  21803. (define-key org-mode-map "\C-y" 'org-yank)
  21804. (defun org-truely-invisible-p ()
  21805. "Check if point is at a character currently not visible.
  21806. This version does not only check the character property, but also
  21807. `visible-mode'."
  21808. ;; Early versions of noutline don't have `outline-invisible-p'.
  21809. (unless (bound-and-true-p visible-mode)
  21810. (outline-invisible-p)))
  21811. (defun org-invisible-p2 ()
  21812. "Check if point is at a character currently not visible."
  21813. (save-excursion
  21814. (when (and (eolp) (not (bobp))) (backward-char 1))
  21815. ;; Early versions of noutline don't have `outline-invisible-p'.
  21816. (outline-invisible-p)))
  21817. (defun org-back-to-heading (&optional invisible-ok)
  21818. "Call `outline-back-to-heading', but provide a better error message."
  21819. (condition-case nil
  21820. (outline-back-to-heading invisible-ok)
  21821. (error (error "Before first headline at position %d in buffer %s"
  21822. (point) (current-buffer)))))
  21823. (defun org-before-first-heading-p ()
  21824. "Before first heading?"
  21825. (save-excursion
  21826. (end-of-line)
  21827. (null (re-search-backward org-outline-regexp-bol nil t))))
  21828. (defun org-at-heading-p (&optional ignored)
  21829. (outline-on-heading-p t))
  21830. (defun org-in-commented-heading-p (&optional no-inheritance)
  21831. "Non-nil if point is under a commented heading.
  21832. This function also checks ancestors of the current headline,
  21833. unless optional argument NO-INHERITANCE is non-nil."
  21834. (cond
  21835. ((org-before-first-heading-p) nil)
  21836. ((let ((headline (nth 4 (org-heading-components))))
  21837. (and headline
  21838. (let ((case-fold-search nil))
  21839. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21840. headline)))))
  21841. (no-inheritance nil)
  21842. (t
  21843. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21844. (defun org-at-comment-p nil
  21845. "Is cursor in a commented line?"
  21846. (save-excursion
  21847. (save-match-data
  21848. (beginning-of-line)
  21849. (looking-at "^[ \t]*# "))))
  21850. (defun org-at-drawer-p nil
  21851. "Is cursor at a drawer keyword?"
  21852. (save-excursion
  21853. (move-beginning-of-line 1)
  21854. (looking-at org-drawer-regexp)))
  21855. (defun org-at-block-p nil
  21856. "Is cursor at a block keyword?"
  21857. (save-excursion
  21858. (move-beginning-of-line 1)
  21859. (looking-at org-block-regexp)))
  21860. (defun org-point-at-end-of-empty-headline ()
  21861. "If point is at the end of an empty headline, return t, else nil.
  21862. If the heading only contains a TODO keyword, it is still still considered
  21863. empty."
  21864. (let ((case-fold-search nil))
  21865. (and (looking-at "[ \t]*$")
  21866. org-todo-line-regexp
  21867. (save-excursion
  21868. (beginning-of-line)
  21869. (looking-at org-todo-line-regexp)
  21870. (string= (match-string 3) "")))))
  21871. (defun org-at-heading-or-item-p ()
  21872. (or (org-at-heading-p) (org-at-item-p)))
  21873. (defun org-at-target-p ()
  21874. (or (org-in-regexp org-radio-target-regexp)
  21875. (org-in-regexp org-target-regexp)))
  21876. ;; Compatibility alias with Org versions < 7.8.03
  21877. (defalias 'org-on-target-p 'org-at-target-p)
  21878. (defun org-up-heading-all (arg)
  21879. "Move to the heading line of which the present line is a subheading.
  21880. This function considers both visible and invisible heading lines.
  21881. With argument, move up ARG levels."
  21882. (outline-up-heading arg t))
  21883. (defun org-up-heading-safe ()
  21884. "Move to the heading line of which the present line is a subheading.
  21885. This version will not throw an error. It will return the level of the
  21886. headline found, or nil if no higher level is found.
  21887. Also, this function will be a lot faster than `outline-up-heading',
  21888. because it relies on stars being the outline starters. This can really
  21889. make a significant difference in outlines with very many siblings."
  21890. (when (ignore-errors (org-back-to-heading t))
  21891. (let ((level-up (1- (funcall outline-level))))
  21892. (and (> level-up 0)
  21893. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21894. (funcall outline-level)))))
  21895. (defun org-first-sibling-p ()
  21896. "Is this heading the first child of its parents?"
  21897. (interactive)
  21898. (let ((re org-outline-regexp-bol)
  21899. level l)
  21900. (unless (org-at-heading-p t)
  21901. (user-error "Not at a heading"))
  21902. (setq level (funcall outline-level))
  21903. (save-excursion
  21904. (if (not (re-search-backward re nil t))
  21905. t
  21906. (setq l (funcall outline-level))
  21907. (< l level)))))
  21908. (defun org-goto-sibling (&optional previous)
  21909. "Goto the next sibling, even if it is invisible.
  21910. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21911. when a sibling was found. When none is found, return nil and don't
  21912. move point."
  21913. (let ((fun (if previous 're-search-backward 're-search-forward))
  21914. (pos (point))
  21915. (re org-outline-regexp-bol)
  21916. level l)
  21917. (when (ignore-errors (org-back-to-heading t))
  21918. (setq level (funcall outline-level))
  21919. (catch 'exit
  21920. (or previous (forward-char 1))
  21921. (while (funcall fun re nil t)
  21922. (setq l (funcall outline-level))
  21923. (when (< l level) (goto-char pos) (throw 'exit nil))
  21924. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21925. (goto-char pos)
  21926. nil))))
  21927. (defun org-show-siblings ()
  21928. "Show all siblings of the current headline."
  21929. (save-excursion
  21930. (while (org-goto-sibling) (org-flag-heading nil)))
  21931. (save-excursion
  21932. (while (org-goto-sibling 'previous)
  21933. (org-flag-heading nil))))
  21934. (defun org-goto-first-child ()
  21935. "Goto the first child, even if it is invisible.
  21936. Return t when a child was found. Otherwise don't move point and
  21937. return nil."
  21938. (let (level (pos (point)) (re org-outline-regexp-bol))
  21939. (when (ignore-errors (org-back-to-heading t))
  21940. (setq level (outline-level))
  21941. (forward-char 1)
  21942. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21943. (progn (goto-char (match-beginning 0)) t)
  21944. (goto-char pos) nil))))
  21945. (defun org-show-hidden-entry ()
  21946. "Show an entry where even the heading is hidden."
  21947. (save-excursion
  21948. (org-show-entry)))
  21949. (defun org-flag-heading (flag &optional entry)
  21950. "Flag the current heading. FLAG non-nil means make invisible.
  21951. When ENTRY is non-nil, show the entire entry."
  21952. (save-excursion
  21953. (org-back-to-heading t)
  21954. ;; Check if we should show the entire entry
  21955. (if entry
  21956. (progn
  21957. (org-show-entry)
  21958. (save-excursion
  21959. (and (outline-next-heading)
  21960. (org-flag-heading nil))))
  21961. (outline-flag-region (max (point-min) (1- (point)))
  21962. (save-excursion (outline-end-of-heading) (point))
  21963. flag))))
  21964. (defun org-get-next-sibling ()
  21965. "Move to next heading of the same level, and return point.
  21966. If there is no such heading, return nil.
  21967. This is like outline-next-sibling, but invisible headings are ok."
  21968. (let ((level (funcall outline-level)))
  21969. (outline-next-heading)
  21970. (while (and (not (eobp)) (> (funcall outline-level) level))
  21971. (outline-next-heading))
  21972. (unless (or (eobp) (< (funcall outline-level) level))
  21973. (point))))
  21974. (defun org-get-last-sibling ()
  21975. "Move to previous heading of the same level, and return point.
  21976. If there is no such heading, return nil."
  21977. (let ((opoint (point))
  21978. (level (funcall outline-level)))
  21979. (outline-previous-heading)
  21980. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21981. (while (and (> (funcall outline-level) level)
  21982. (not (bobp)))
  21983. (outline-previous-heading))
  21984. (unless (< (funcall outline-level) level)
  21985. (point)))))
  21986. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21987. "Goto to the end of a subtree."
  21988. ;; This contains an exact copy of the original function, but it uses
  21989. ;; `org-back-to-heading', to make it work also in invisible
  21990. ;; trees. And is uses an invisible-ok argument.
  21991. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21992. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21993. ;; with many children and grandchildren etc, this can be much faster
  21994. ;; than the outline version.
  21995. (org-back-to-heading invisible-ok)
  21996. (let ((first t)
  21997. (level (funcall outline-level)))
  21998. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21999. ;; A true heading (not a plain list item), in Org
  22000. ;; This means we can easily find the end by looking
  22001. ;; only for the right number of stars. Using a regexp to do
  22002. ;; this is so much faster than using a Lisp loop.
  22003. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22004. (forward-char 1)
  22005. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22006. ;; something else, do it the slow way
  22007. (while (and (not (eobp))
  22008. (or first (> (funcall outline-level) level)))
  22009. (setq first nil)
  22010. (outline-next-heading)))
  22011. (unless to-heading
  22012. (when (memq (preceding-char) '(?\n ?\^M))
  22013. ;; Go to end of line before heading
  22014. (forward-char -1)
  22015. (when (memq (preceding-char) '(?\n ?\^M))
  22016. ;; leave blank line before heading
  22017. (forward-char -1)))))
  22018. (point))
  22019. (defun org-end-of-meta-data (&optional full)
  22020. "Skip planning line and properties drawer in current entry.
  22021. When optional argument FULL is non-nil, also skip empty lines,
  22022. clocking lines and regular drawers at the beginning of the
  22023. entry."
  22024. (org-back-to-heading t)
  22025. (forward-line)
  22026. (when (looking-at-p org-planning-line-re) (forward-line))
  22027. (when (looking-at org-property-drawer-re)
  22028. (goto-char (match-end 0))
  22029. (forward-line))
  22030. (when (and full (not (org-at-heading-p)))
  22031. (catch 'exit
  22032. (let ((end (save-excursion (outline-next-heading) (point)))
  22033. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22034. (while (not (eobp))
  22035. (cond ((looking-at-p org-drawer-regexp)
  22036. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22037. (forward-line)
  22038. (throw 'exit t)))
  22039. ((looking-at-p re) (forward-line))
  22040. (t (throw 'exit t))))))))
  22041. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22042. "Move forward to the ARG'th subheading at same level as this one.
  22043. Stop at the first and last subheadings of a superior heading.
  22044. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22045. non-nil it will also look at invisible ones."
  22046. (interactive "p")
  22047. (let ((backward? (and arg (< arg 0))))
  22048. (if (org-before-first-heading-p)
  22049. (if backward? (goto-char (point-min)) (outline-next-heading))
  22050. (org-back-to-heading invisible-ok)
  22051. (unless backward? (end-of-line)) ;do not match current headline
  22052. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22053. (f (if backward? #'re-search-backward #'re-search-forward))
  22054. (count (if arg (abs arg) 1))
  22055. (result (point)))
  22056. (while (and (> count 0)
  22057. (funcall f org-outline-regexp-bol nil 'move))
  22058. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22059. (cond ((< l level) (setq count 0))
  22060. ((and (= l level)
  22061. (or invisible-ok
  22062. (not (outline-invisible-p
  22063. (line-beginning-position)))))
  22064. (cl-decf count)
  22065. (when (= l level) (setq result (point)))))))
  22066. (goto-char result))
  22067. (beginning-of-line))))
  22068. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22069. "Move backward to the ARG'th subheading at same level as this one.
  22070. Stop at the first and last subheadings of a superior heading."
  22071. (interactive "p")
  22072. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22073. (defun org-next-visible-heading (arg)
  22074. "Move to the next visible heading.
  22075. This function wraps `outline-next-visible-heading' with
  22076. `org-with-limited-levels' in order to skip over inline tasks and
  22077. respect customization of `org-odd-levels-only'."
  22078. (interactive "p")
  22079. (org-with-limited-levels
  22080. (outline-next-visible-heading arg)))
  22081. (defun org-previous-visible-heading (arg)
  22082. "Move to the previous visible heading.
  22083. This function wraps `outline-previous-visible-heading' with
  22084. `org-with-limited-levels' in order to skip over inline tasks and
  22085. respect customization of `org-odd-levels-only'."
  22086. (interactive "p")
  22087. (org-with-limited-levels
  22088. (outline-previous-visible-heading arg)))
  22089. (defun org-next-block (arg &optional backward block-regexp)
  22090. "Jump to the next block.
  22091. With a prefix argument ARG, jump forward ARG many blocks.
  22092. When BACKWARD is non-nil, jump to the previous block.
  22093. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22094. Match data is set according to this regexp when the function
  22095. returns.
  22096. Return point at beginning of the opening line of found block.
  22097. Throw an error if no block is found."
  22098. (interactive "p")
  22099. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22100. (case-fold-search t)
  22101. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22102. (count (or arg 1))
  22103. (origin (point))
  22104. last-element)
  22105. (if backward (beginning-of-line) (end-of-line))
  22106. (while (and (> count 0) (funcall search-fn re nil t))
  22107. (let ((element (save-excursion
  22108. (goto-char (match-beginning 0))
  22109. (save-match-data (org-element-at-point)))))
  22110. (when (and (memq (org-element-type element)
  22111. '(center-block comment-block dynamic-block
  22112. example-block export-block quote-block
  22113. special-block src-block verse-block))
  22114. (<= (match-beginning 0)
  22115. (org-element-property :post-affiliated element)))
  22116. (setq last-element element)
  22117. (cl-decf count))))
  22118. (if (= count 0)
  22119. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22120. (save-match-data (org-show-context)))
  22121. (goto-char origin)
  22122. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22123. (defun org-previous-block (arg &optional block-regexp)
  22124. "Jump to the previous block.
  22125. With a prefix argument ARG, jump backward ARG many source blocks.
  22126. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22127. (interactive "p")
  22128. (org-next-block arg t block-regexp))
  22129. (defun org-forward-paragraph ()
  22130. "Move forward to beginning of next paragraph or equivalent.
  22131. The function moves point to the beginning of the next visible
  22132. structural element, which can be a paragraph, a table, a list
  22133. item, etc. It also provides some special moves for convenience:
  22134. - On an affiliated keyword, jump to the beginning of the
  22135. relative element.
  22136. - On an item or a footnote definition, move to the second
  22137. element inside, if any.
  22138. - On a table or a property drawer, jump after it.
  22139. - On a verse or source block, stop after blank lines."
  22140. (interactive)
  22141. (when (eobp) (user-error "Cannot move further down"))
  22142. (let* ((deactivate-mark nil)
  22143. (element (org-element-at-point))
  22144. (type (org-element-type element))
  22145. (post-affiliated (org-element-property :post-affiliated element))
  22146. (contents-begin (org-element-property :contents-begin element))
  22147. (contents-end (org-element-property :contents-end element))
  22148. (end (let ((end (org-element-property :end element)) (parent element))
  22149. (while (and (setq parent (org-element-property :parent parent))
  22150. (= (org-element-property :contents-end parent) end))
  22151. (setq end (org-element-property :end parent)))
  22152. end)))
  22153. (cond ((not element)
  22154. (skip-chars-forward " \r\t\n")
  22155. (or (eobp) (beginning-of-line)))
  22156. ;; On affiliated keywords, move to element's beginning.
  22157. ((< (point) post-affiliated)
  22158. (goto-char post-affiliated))
  22159. ;; At a table row, move to the end of the table. Similarly,
  22160. ;; at a node property, move to the end of the property
  22161. ;; drawer.
  22162. ((memq type '(node-property table-row))
  22163. (goto-char (org-element-property
  22164. :end (org-element-property :parent element))))
  22165. ((memq type '(property-drawer table)) (goto-char end))
  22166. ;; Consider blank lines as separators in verse and source
  22167. ;; blocks to ease editing.
  22168. ((memq type '(src-block verse-block))
  22169. (when (eq type 'src-block)
  22170. (setq contents-end
  22171. (save-excursion (goto-char end)
  22172. (skip-chars-backward " \r\t\n")
  22173. (line-beginning-position))))
  22174. (beginning-of-line)
  22175. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22176. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22177. (goto-char end)
  22178. (skip-chars-forward " \r\t\n")
  22179. (if (= (point) contents-end) (goto-char end)
  22180. (beginning-of-line))))
  22181. ;; With no contents, just skip element.
  22182. ((not contents-begin) (goto-char end))
  22183. ;; If contents are invisible, skip the element altogether.
  22184. ((outline-invisible-p (line-end-position))
  22185. (cl-case type
  22186. (headline
  22187. (org-with-limited-levels (outline-next-visible-heading 1)))
  22188. ;; At a plain list, make sure we move to the next item
  22189. ;; instead of skipping the whole list.
  22190. (plain-list (forward-char)
  22191. (org-forward-paragraph))
  22192. (otherwise (goto-char end))))
  22193. ((>= (point) contents-end) (goto-char end))
  22194. ((>= (point) contents-begin)
  22195. ;; This can only happen on paragraphs and plain lists.
  22196. (cl-case type
  22197. (paragraph (goto-char end))
  22198. ;; At a plain list, try to move to second element in
  22199. ;; first item, if possible.
  22200. (plain-list (end-of-line)
  22201. (org-forward-paragraph))))
  22202. ;; When contents start on the middle of a line (e.g. in
  22203. ;; items and footnote definitions), try to reach first
  22204. ;; element starting after current line.
  22205. ((> (line-end-position) contents-begin)
  22206. (end-of-line)
  22207. (org-forward-paragraph))
  22208. (t (goto-char contents-begin)))))
  22209. (defun org-backward-paragraph ()
  22210. "Move backward to start of previous paragraph or equivalent.
  22211. The function moves point to the beginning of the current
  22212. structural element, which can be a paragraph, a table, a list
  22213. item, etc., or to the beginning of the previous visible one if
  22214. point is already there. It also provides some special moves for
  22215. convenience:
  22216. - On an affiliated keyword, jump to the first one.
  22217. - On a table or a property drawer, move to its beginning.
  22218. - On a verse or source block, stop before blank lines."
  22219. (interactive)
  22220. (when (bobp) (user-error "Cannot move further up"))
  22221. (let* ((deactivate-mark nil)
  22222. (element (org-element-at-point))
  22223. (type (org-element-type element))
  22224. (contents-begin (org-element-property :contents-begin element))
  22225. (contents-end (org-element-property :contents-end element))
  22226. (post-affiliated (org-element-property :post-affiliated element))
  22227. (begin (org-element-property :begin element)))
  22228. (cond
  22229. ((not element) (goto-char (point-min)))
  22230. ((= (point) begin)
  22231. (backward-char)
  22232. (org-backward-paragraph))
  22233. ((<= (point) post-affiliated) (goto-char begin))
  22234. ((memq type '(node-property table-row))
  22235. (goto-char (org-element-property
  22236. :post-affiliated (org-element-property :parent element))))
  22237. ((memq type '(property-drawer table)) (goto-char begin))
  22238. ((memq type '(src-block verse-block))
  22239. (when (eq type 'src-block)
  22240. (setq contents-begin
  22241. (save-excursion (goto-char begin) (forward-line) (point))))
  22242. (if (= (point) contents-begin) (goto-char post-affiliated)
  22243. ;; Inside a verse block, see blank lines as paragraph
  22244. ;; separators.
  22245. (let ((origin (point)))
  22246. (skip-chars-backward " \r\t\n" contents-begin)
  22247. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22248. (skip-chars-forward " \r\t\n" origin)
  22249. (if (= (point) origin) (goto-char contents-begin)
  22250. (beginning-of-line))))))
  22251. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22252. ((eq type 'paragraph)
  22253. (goto-char contents-begin)
  22254. ;; When at first paragraph in an item or a footnote definition,
  22255. ;; move directly to beginning of line.
  22256. (let ((parent-contents
  22257. (org-element-property
  22258. :contents-begin (org-element-property :parent element))))
  22259. (when (and parent-contents (= parent-contents contents-begin))
  22260. (beginning-of-line))))
  22261. ;; At the end of a greater element, move to the beginning of the
  22262. ;; last element within.
  22263. ((>= (point) contents-end)
  22264. (goto-char (1- contents-end))
  22265. (org-backward-paragraph))
  22266. (t (goto-char (or post-affiliated begin))))
  22267. ;; Ensure we never leave point invisible.
  22268. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22269. (defun org-forward-element ()
  22270. "Move forward by one element.
  22271. Move to the next element at the same level, when possible."
  22272. (interactive)
  22273. (cond ((eobp) (user-error "Cannot move further down"))
  22274. ((org-with-limited-levels (org-at-heading-p))
  22275. (let ((origin (point)))
  22276. (goto-char (org-end-of-subtree nil t))
  22277. (unless (org-with-limited-levels (org-at-heading-p))
  22278. (goto-char origin)
  22279. (user-error "Cannot move further down"))))
  22280. (t
  22281. (let* ((elem (org-element-at-point))
  22282. (end (org-element-property :end elem))
  22283. (parent (org-element-property :parent elem)))
  22284. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22285. (goto-char (org-element-property :end parent)))
  22286. ((integer-or-marker-p end) (goto-char end))
  22287. (t (message "No element at point")))))))
  22288. (defun org-backward-element ()
  22289. "Move backward by one element.
  22290. Move to the previous element at the same level, when possible."
  22291. (interactive)
  22292. (cond ((bobp) (user-error "Cannot move further up"))
  22293. ((org-with-limited-levels (org-at-heading-p))
  22294. ;; At a headline, move to the previous one, if any, or stay
  22295. ;; here.
  22296. (let ((origin (point)))
  22297. (org-with-limited-levels (org-backward-heading-same-level 1))
  22298. ;; When current headline has no sibling above, move to its
  22299. ;; parent.
  22300. (when (= (point) origin)
  22301. (or (org-with-limited-levels (org-up-heading-safe))
  22302. (progn (goto-char origin)
  22303. (user-error "Cannot move further up"))))))
  22304. (t
  22305. (let* ((elem (org-element-at-point))
  22306. (beg (org-element-property :begin elem)))
  22307. (cond
  22308. ;; Move to beginning of current element if point isn't
  22309. ;; there already.
  22310. ((null beg) (message "No element at point"))
  22311. ((/= (point) beg) (goto-char beg))
  22312. (t (goto-char beg)
  22313. (skip-chars-backward " \r\t\n")
  22314. (unless (bobp)
  22315. (let ((prev (org-element-at-point)))
  22316. (goto-char (org-element-property :begin prev))
  22317. (while (and (setq prev (org-element-property :parent prev))
  22318. (<= (org-element-property :end prev) beg))
  22319. (goto-char (org-element-property :begin prev)))))))))))
  22320. (defun org-up-element ()
  22321. "Move to upper element."
  22322. (interactive)
  22323. (if (org-with-limited-levels (org-at-heading-p))
  22324. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22325. (let* ((elem (org-element-at-point))
  22326. (parent (org-element-property :parent elem)))
  22327. (if parent (goto-char (org-element-property :begin parent))
  22328. (if (org-with-limited-levels (org-before-first-heading-p))
  22329. (user-error "No surrounding element")
  22330. (org-with-limited-levels (org-back-to-heading)))))))
  22331. (defvar org-element-greater-elements)
  22332. (defun org-down-element ()
  22333. "Move to inner element."
  22334. (interactive)
  22335. (let ((element (org-element-at-point)))
  22336. (cond
  22337. ((memq (org-element-type element) '(plain-list table))
  22338. (goto-char (org-element-property :contents-begin element))
  22339. (forward-char))
  22340. ((memq (org-element-type element) org-element-greater-elements)
  22341. ;; If contents are hidden, first disclose them.
  22342. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22343. (goto-char (or (org-element-property :contents-begin element)
  22344. (user-error "No content for this element"))))
  22345. (t (user-error "No inner element")))))
  22346. (defun org-drag-element-backward ()
  22347. "Move backward element at point."
  22348. (interactive)
  22349. (let ((elem (or (org-element-at-point)
  22350. (user-error "No element at point"))))
  22351. (if (eq (org-element-type elem) 'headline)
  22352. ;; Preserve point when moving a whole tree, even if point was
  22353. ;; on blank lines below the headline.
  22354. (let ((offset (skip-chars-backward " \t\n")))
  22355. (unwind-protect (org-move-subtree-up)
  22356. (forward-char (- offset))))
  22357. (let ((prev-elem
  22358. (save-excursion
  22359. (goto-char (org-element-property :begin elem))
  22360. (skip-chars-backward " \r\t\n")
  22361. (unless (bobp)
  22362. (let* ((beg (org-element-property :begin elem))
  22363. (prev (org-element-at-point))
  22364. (up prev))
  22365. (while (and (setq up (org-element-property :parent up))
  22366. (<= (org-element-property :end up) beg))
  22367. (setq prev up))
  22368. prev)))))
  22369. ;; Error out if no previous element or previous element is
  22370. ;; a parent of the current one.
  22371. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22372. (user-error "Cannot drag element backward")
  22373. (let ((pos (point)))
  22374. (org-element-swap-A-B prev-elem elem)
  22375. (goto-char (+ (org-element-property :begin prev-elem)
  22376. (- pos (org-element-property :begin elem))))))))))
  22377. (defun org-drag-element-forward ()
  22378. "Move forward element at point."
  22379. (interactive)
  22380. (let* ((pos (point))
  22381. (elem (or (org-element-at-point)
  22382. (user-error "No element at point"))))
  22383. (when (= (point-max) (org-element-property :end elem))
  22384. (user-error "Cannot drag element forward"))
  22385. (goto-char (org-element-property :end elem))
  22386. (let ((next-elem (org-element-at-point)))
  22387. (when (or (org-element-nested-p elem next-elem)
  22388. (and (eq (org-element-type next-elem) 'headline)
  22389. (not (eq (org-element-type elem) 'headline))))
  22390. (goto-char pos)
  22391. (user-error "Cannot drag element forward"))
  22392. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22393. ;; body's length (without final blanks) and by the length of
  22394. ;; blanks between ELEM and NEXT-ELEM.
  22395. (let ((size-next (- (save-excursion
  22396. (goto-char (org-element-property :end next-elem))
  22397. (skip-chars-backward " \r\t\n")
  22398. (forward-line)
  22399. ;; Small correction if buffer doesn't end
  22400. ;; with a newline character.
  22401. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22402. (org-element-property :begin next-elem)))
  22403. (size-blank (- (org-element-property :end elem)
  22404. (save-excursion
  22405. (goto-char (org-element-property :end elem))
  22406. (skip-chars-backward " \r\t\n")
  22407. (forward-line)
  22408. (point)))))
  22409. (org-element-swap-A-B elem next-elem)
  22410. (goto-char (+ pos size-next size-blank))))))
  22411. (defun org-drag-line-forward (arg)
  22412. "Drag the line at point ARG lines forward."
  22413. (interactive "p")
  22414. (dotimes (_ (abs arg))
  22415. (let ((c (current-column)))
  22416. (if (< 0 arg)
  22417. (progn
  22418. (beginning-of-line 2)
  22419. (transpose-lines 1)
  22420. (beginning-of-line 0))
  22421. (transpose-lines 1)
  22422. (beginning-of-line -1))
  22423. (org-move-to-column c))))
  22424. (defun org-drag-line-backward (arg)
  22425. "Drag the line at point ARG lines backward."
  22426. (interactive "p")
  22427. (org-drag-line-forward (- arg)))
  22428. (defun org-mark-element ()
  22429. "Put point at beginning of this element, mark at end.
  22430. Interactively, if this command is repeated or (in Transient Mark
  22431. mode) if the mark is active, it marks the next element after the
  22432. ones already marked."
  22433. (interactive)
  22434. (let (deactivate-mark)
  22435. (if (and (called-interactively-p 'any)
  22436. (or (and (eq last-command this-command) (mark t))
  22437. (and transient-mark-mode mark-active)))
  22438. (set-mark
  22439. (save-excursion
  22440. (goto-char (mark))
  22441. (goto-char (org-element-property :end (org-element-at-point)))))
  22442. (let ((element (org-element-at-point)))
  22443. (end-of-line)
  22444. (push-mark (org-element-property :end element) t t)
  22445. (goto-char (org-element-property :begin element))))))
  22446. (defun org-narrow-to-element ()
  22447. "Narrow buffer to current element."
  22448. (interactive)
  22449. (let ((elem (org-element-at-point)))
  22450. (cond
  22451. ((eq (car elem) 'headline)
  22452. (narrow-to-region
  22453. (org-element-property :begin elem)
  22454. (org-element-property :end elem)))
  22455. ((memq (car elem) org-element-greater-elements)
  22456. (narrow-to-region
  22457. (org-element-property :contents-begin elem)
  22458. (org-element-property :contents-end elem)))
  22459. (t
  22460. (narrow-to-region
  22461. (org-element-property :begin elem)
  22462. (org-element-property :end elem))))))
  22463. (defun org-transpose-element ()
  22464. "Transpose current and previous elements, keeping blank lines between.
  22465. Point is moved after both elements."
  22466. (interactive)
  22467. (org-skip-whitespace)
  22468. (let ((end (org-element-property :end (org-element-at-point))))
  22469. (org-drag-element-backward)
  22470. (goto-char end)))
  22471. (defun org-unindent-buffer ()
  22472. "Un-indent the visible part of the buffer.
  22473. Relative indentation (between items, inside blocks, etc.) isn't
  22474. modified."
  22475. (interactive)
  22476. (unless (eq major-mode 'org-mode)
  22477. (user-error "Cannot un-indent a buffer not in Org mode"))
  22478. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22479. (unindent-tree
  22480. (lambda (contents)
  22481. (dolist (element (reverse contents))
  22482. (if (memq (org-element-type element) '(headline section))
  22483. (funcall unindent-tree (org-element-contents element))
  22484. (save-excursion
  22485. (save-restriction
  22486. (narrow-to-region
  22487. (org-element-property :begin element)
  22488. (org-element-property :end element))
  22489. (org-do-remove-indentation))))))))
  22490. (funcall unindent-tree (org-element-contents parse-tree))))
  22491. (defun org-show-children (&optional level)
  22492. "Show all direct subheadings of this heading.
  22493. Prefix arg LEVEL is how many levels below the current level
  22494. should be shown. Default is enough to cause the following
  22495. heading to appear."
  22496. (interactive "p")
  22497. ;; If `orgstruct-mode' is active, use the slower version.
  22498. (if orgstruct-mode (call-interactively #'outline-show-children)
  22499. (save-excursion
  22500. (org-back-to-heading t)
  22501. (let* ((current-level (funcall outline-level))
  22502. (max-level (org-get-valid-level
  22503. current-level
  22504. (if level (prefix-numeric-value level) 1)))
  22505. (end (save-excursion (org-end-of-subtree t t)))
  22506. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22507. (past-first-child nil)
  22508. ;; Make sure to skip inlinetasks.
  22509. (re (format regexp-fmt
  22510. current-level
  22511. (cond
  22512. ((not (featurep 'org-inlinetask)) "")
  22513. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22514. 3))
  22515. (t (1- org-inlinetask-min-level))))))
  22516. ;; Display parent heading.
  22517. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22518. (forward-line)
  22519. ;; Display children. First child may be deeper than expected
  22520. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22521. ;; MAX-LEVEL accordingly.
  22522. (while (re-search-forward re end t)
  22523. (unless past-first-child
  22524. (setq re (format regexp-fmt
  22525. current-level
  22526. (max (funcall outline-level) max-level)))
  22527. (setq past-first-child t))
  22528. (outline-flag-region
  22529. (line-end-position 0) (line-end-position) nil))))))
  22530. (defun org-show-subtree ()
  22531. "Show everything after this heading at deeper levels."
  22532. (interactive)
  22533. (outline-flag-region
  22534. (point)
  22535. (save-excursion
  22536. (org-end-of-subtree t t))
  22537. nil))
  22538. (defun org-show-entry ()
  22539. "Show the body directly following this heading.
  22540. Show the heading too, if it is currently invisible."
  22541. (interactive)
  22542. (save-excursion
  22543. (ignore-errors
  22544. (org-back-to-heading t)
  22545. (outline-flag-region
  22546. (max (point-min) (1- (point)))
  22547. (save-excursion
  22548. (if (re-search-forward
  22549. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22550. (match-beginning 1)
  22551. (point-max)))
  22552. nil)
  22553. (org-cycle-hide-drawers 'children))))
  22554. (defun org-make-options-regexp (kwds &optional extra)
  22555. "Make a regular expression for keyword lines.
  22556. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22557. when non-nil, is a regexp matching keywords names."
  22558. (concat "^[ \t]*#\\+\\("
  22559. (regexp-opt kwds)
  22560. (and extra (concat (and kwds "\\|") extra))
  22561. "\\):[ \t]*\\(.*\\)"))
  22562. ;;;; Integration with and fixes for other packages
  22563. ;;; Imenu support
  22564. (defvar-local org-imenu-markers nil
  22565. "All markers currently used by Imenu.")
  22566. (defun org-imenu-new-marker (&optional pos)
  22567. "Return a new marker for use by Imenu, and remember the marker."
  22568. (let ((m (make-marker)))
  22569. (move-marker m (or pos (point)))
  22570. (push m org-imenu-markers)
  22571. m))
  22572. (defun org-imenu-get-tree ()
  22573. "Produce the index for Imenu."
  22574. (dolist (x org-imenu-markers) (move-marker x nil))
  22575. (setq org-imenu-markers nil)
  22576. (let* ((case-fold-search nil)
  22577. (n org-imenu-depth)
  22578. (re (concat "^" (org-get-limited-outline-regexp)))
  22579. (subs (make-vector (1+ n) nil))
  22580. (last-level 0)
  22581. m level head0 head)
  22582. (org-with-wide-buffer
  22583. (goto-char (point-max))
  22584. (while (re-search-backward re nil t)
  22585. (setq level (org-reduced-level (funcall outline-level)))
  22586. (when (and (<= level n)
  22587. (looking-at org-complex-heading-regexp)
  22588. (setq head0 (match-string-no-properties 4)))
  22589. (setq head (org-link-display-format head0)
  22590. m (org-imenu-new-marker))
  22591. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22592. (if (>= level last-level)
  22593. (push (cons head m) (aref subs level))
  22594. (push (cons head (aref subs (1+ level))) (aref subs level))
  22595. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22596. (setq last-level level))))
  22597. (aref subs 1)))
  22598. (eval-after-load "imenu"
  22599. '(progn
  22600. (add-hook 'imenu-after-jump-hook
  22601. (lambda ()
  22602. (when (derived-mode-p 'org-mode)
  22603. (org-show-context 'org-goto))))))
  22604. (defun org-link-display-format (s)
  22605. "Replace links in string S with their description.
  22606. If there is no description, use the link target."
  22607. (save-match-data
  22608. (replace-regexp-in-string
  22609. org-bracket-link-analytic-regexp
  22610. (lambda (m)
  22611. (if (match-end 5) (match-string 5 m)
  22612. (concat (match-string 1 m) (match-string 3 m))))
  22613. s nil t)))
  22614. (defun org-toggle-link-display ()
  22615. "Toggle the literal or descriptive display of links."
  22616. (interactive)
  22617. (if org-descriptive-links
  22618. (progn (org-remove-from-invisibility-spec '(org-link))
  22619. (org-restart-font-lock)
  22620. (setq org-descriptive-links nil))
  22621. (progn (add-to-invisibility-spec '(org-link))
  22622. (org-restart-font-lock)
  22623. (setq org-descriptive-links t))))
  22624. ;; Speedbar support
  22625. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22626. "Overlay marking the agenda restriction line in speedbar.")
  22627. (overlay-put org-speedbar-restriction-lock-overlay
  22628. 'face 'org-agenda-restriction-lock)
  22629. (overlay-put org-speedbar-restriction-lock-overlay
  22630. 'help-echo "Agendas are currently limited to this item.")
  22631. (delete-overlay org-speedbar-restriction-lock-overlay)
  22632. (defun org-speedbar-set-agenda-restriction ()
  22633. "Restrict future agenda commands to the location at point in speedbar.
  22634. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22635. (interactive)
  22636. (require 'org-agenda)
  22637. (let (p m tp np dir txt)
  22638. (cond
  22639. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22640. 'org-imenu t))
  22641. (setq m (get-text-property p 'org-imenu-marker))
  22642. (with-current-buffer (marker-buffer m)
  22643. (goto-char m)
  22644. (org-agenda-set-restriction-lock 'subtree)))
  22645. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22646. 'speedbar-function 'speedbar-find-file))
  22647. (setq tp (previous-single-property-change
  22648. (1+ p) 'speedbar-function)
  22649. np (next-single-property-change
  22650. tp 'speedbar-function)
  22651. dir (speedbar-line-directory)
  22652. txt (buffer-substring-no-properties (or tp (point-min))
  22653. (or np (point-max))))
  22654. (with-current-buffer (find-file-noselect
  22655. (let ((default-directory dir))
  22656. (expand-file-name txt)))
  22657. (unless (derived-mode-p 'org-mode)
  22658. (user-error "Cannot restrict to non-Org mode file"))
  22659. (org-agenda-set-restriction-lock 'file)))
  22660. (t (user-error "Don't know how to restrict Org mode agenda")))
  22661. (move-overlay org-speedbar-restriction-lock-overlay
  22662. (point-at-bol) (point-at-eol))
  22663. (setq current-prefix-arg nil)
  22664. (org-agenda-maybe-redo)))
  22665. (defvar speedbar-file-key-map)
  22666. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22667. (eval-after-load "speedbar"
  22668. '(progn
  22669. (speedbar-add-supported-extension ".org")
  22670. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22671. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22672. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22673. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22674. (add-hook 'speedbar-visiting-tag-hook
  22675. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22676. ;;; Fixes and Hacks for problems with other packages
  22677. (defun org--flyspell-object-check-p (element)
  22678. "Non-nil when Flyspell can check object at point.
  22679. ELEMENT is the element at point."
  22680. (let ((object (save-excursion
  22681. (when (looking-at-p "\\>") (backward-char))
  22682. (org-element-context element))))
  22683. (cl-case (org-element-type object)
  22684. ;; Prevent checks in links due to keybinding conflict with
  22685. ;; Flyspell.
  22686. ((code entity export-snippet inline-babel-call
  22687. inline-src-block line-break latex-fragment link macro
  22688. statistics-cookie target timestamp verbatim)
  22689. nil)
  22690. (footnote-reference
  22691. ;; Only in inline footnotes, within the definition.
  22692. (and (eq (org-element-property :type object) 'inline)
  22693. (< (save-excursion
  22694. (goto-char (org-element-property :begin object))
  22695. (search-forward ":" nil t 2))
  22696. (point))))
  22697. (otherwise t))))
  22698. (defun org-mode-flyspell-verify ()
  22699. "Function used for `flyspell-generic-check-word-predicate'."
  22700. (if (org-at-heading-p)
  22701. ;; At a headline or an inlinetask, check title only. This is
  22702. ;; faster than relying on `org-element-at-point'.
  22703. (and (save-excursion (beginning-of-line)
  22704. (and (let ((case-fold-search t))
  22705. (not (looking-at-p "\\*+ END[ \t]*$")))
  22706. (let ((case-fold-search nil))
  22707. (looking-at org-complex-heading-regexp))))
  22708. (match-beginning 4)
  22709. (>= (point) (match-beginning 4))
  22710. (or (not (match-beginning 5))
  22711. (< (point) (match-beginning 5))))
  22712. (let* ((element (org-element-at-point))
  22713. (post-affiliated (org-element-property :post-affiliated element)))
  22714. (cond
  22715. ;; Ignore checks in all affiliated keywords but captions.
  22716. ((< (point) post-affiliated)
  22717. (and (save-excursion
  22718. (beginning-of-line)
  22719. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22720. (> (point) (match-end 0))
  22721. (org--flyspell-object-check-p element)))
  22722. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22723. ((let ((log (org-log-into-drawer)))
  22724. (and log
  22725. (let ((drawer (org-element-lineage element '(drawer))))
  22726. (and drawer
  22727. (eq (compare-strings
  22728. log nil nil
  22729. (org-element-property :drawer-name drawer) nil nil t)
  22730. t)))))
  22731. nil)
  22732. (t
  22733. (cl-case (org-element-type element)
  22734. ((comment quote-section) t)
  22735. (comment-block
  22736. ;; Allow checks between block markers, not on them.
  22737. (and (> (line-beginning-position) post-affiliated)
  22738. (save-excursion
  22739. (end-of-line)
  22740. (skip-chars-forward " \r\t\n")
  22741. (< (point) (org-element-property :end element)))))
  22742. ;; Arbitrary list of keywords where checks are meaningful.
  22743. ;; Make sure point is on the value part of the element.
  22744. (keyword
  22745. (and (member (org-element-property :key element)
  22746. '("DESCRIPTION" "TITLE"))
  22747. (save-excursion
  22748. (search-backward ":" (line-beginning-position) t))))
  22749. ;; Check is globally allowed in paragraphs verse blocks and
  22750. ;; table rows (after affiliated keywords) but some objects
  22751. ;; must not be affected.
  22752. ((paragraph table-row verse-block)
  22753. (let ((cbeg (org-element-property :contents-begin element))
  22754. (cend (org-element-property :contents-end element)))
  22755. (and cbeg (>= (point) cbeg) (< (point) cend)
  22756. (org--flyspell-object-check-p element))))))))))
  22757. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22758. (defun org-remove-flyspell-overlays-in (beg end)
  22759. "Remove flyspell overlays in region."
  22760. (and (bound-and-true-p flyspell-mode)
  22761. (fboundp 'flyspell-delete-region-overlays)
  22762. (flyspell-delete-region-overlays beg end)))
  22763. (defvar flyspell-delayed-commands)
  22764. (eval-after-load "flyspell"
  22765. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22766. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22767. (eval-after-load "bookmark"
  22768. '(if (boundp 'bookmark-after-jump-hook)
  22769. ;; We can use the hook
  22770. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22771. ;; Hook not available, use advice
  22772. (defadvice bookmark-jump (after org-make-visible activate)
  22773. "Make the position visible."
  22774. (org-bookmark-jump-unhide))))
  22775. ;; Make sure saveplace shows the location if it was hidden
  22776. (eval-after-load "saveplace"
  22777. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22778. "Make the position visible."
  22779. (org-bookmark-jump-unhide)))
  22780. ;; Make sure ecb shows the location if it was hidden
  22781. (eval-after-load "ecb"
  22782. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22783. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22784. (when (derived-mode-p 'org-mode)
  22785. (org-show-context))))
  22786. (defun org-bookmark-jump-unhide ()
  22787. "Unhide the current position, to show the bookmark location."
  22788. (and (derived-mode-p 'org-mode)
  22789. (or (outline-invisible-p)
  22790. (save-excursion (goto-char (max (point-min) (1- (point))))
  22791. (outline-invisible-p)))
  22792. (org-show-context 'bookmark-jump)))
  22793. (defun org-mark-jump-unhide ()
  22794. "Make the point visible with `org-show-context' after jumping to the mark."
  22795. (when (and (derived-mode-p 'org-mode)
  22796. (outline-invisible-p))
  22797. (org-show-context 'mark-goto)))
  22798. (eval-after-load "simple"
  22799. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22800. "Make the point visible with `org-show-context'."
  22801. (org-mark-jump-unhide)))
  22802. (eval-after-load "simple"
  22803. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22804. "Make the point visible with `org-show-context'."
  22805. (org-mark-jump-unhide)))
  22806. (eval-after-load "simple"
  22807. '(defadvice pop-global-mark (after org-make-visible activate)
  22808. "Make the point visible with `org-show-context'."
  22809. (org-mark-jump-unhide)))
  22810. ;; Make session.el ignore our circular variable
  22811. (defvar session-globals-exclude)
  22812. (eval-after-load "session"
  22813. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22814. ;;;; Finish up
  22815. (provide 'org)
  22816. (run-hooks 'org-load-hook)
  22817. ;;; org.el ends here